Node.js requires the path to be 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

what I'm trying to require is myPlug.js

like this:

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

      

As it NODE PATH

is source

, I also tried:

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

      

But for my application, I will have to require a separate connection every time, so I would really like to create a path like this:

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

      

When I try to do this, I get the error: Error: Cannot find module './../plugs/myPlug'

I have already tried path.normalize

and even join paths with path.join

, but get the same results. Any ideas?

Update: answer

This answer can be solved with RequireJS, Dynamic requirement in RequireJS getting "Module name not yet loaded for context" error?

+3


source to share


1 answer


I use compound strings, but not entirely.

Wrong:

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

      



Right:

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

      

0


source







All Articles