Node.js require path stored in a variable

11.6k views Asked by At

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?

2

There are 2 answers

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

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`);