Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js require path stored in a variable

I am testing some nodejs code, and this is how my directory looks like:

-> source  //NODE PATH=./source ...
-> plugs
   -myPlug.js
   -test.js

In test.js I try to require myPlug.js like this:

function(){
     var myRequiredPlug = require('./myPlug.js') //this works
}

Since the NODE PATH is source, I have also tried:

function(){
     var myRequiredPlug = require('./../plugs/myPlug') //also works
}

But I will have to require a different plug every time for my app, so I would very much like to create the path this way:

 function(nameOfPlug){  // nameOfPlug := myPlug
     var myPath = './../plugs/' + nameOfPlug;
     console.log(myPath === './../plugs/myPlug') // true, so same string
     var myRequiredPlug = require(myPath);  
}

When I try it his way, I get the error: Error: Cannot find module './../plugs/myPlug'

I have already tried path.normalize, and even to join the paths with path.join, but get the same results. Any ideas?

Update: Answer

This answer can be solved using RequireJS, Dynamic require in RequireJS, getting "Module name has not been loaded yet for context" error?

like image 486
regina_fallangi Avatar asked Jun 10 '15 09:06

regina_fallangi


1 Answers

I use compound lines, but not completely.

Wrong:

const path = './some/path.file';
const data = require(`${path}`);

Right:

const path = 'file';
const data = require(`./some/${path}.file`);
like image 141
kolserdav Avatar answered Sep 18 '22 09:09

kolserdav