10

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?

4
  • 3
    Do you mean console.log(myPath === './../plugs/nameOfPlug') (with quotes around the string)? Commented Jun 10, 2015 at 9:36
  • jfriend00, yes, I meat it with '...', thanks. And nameOfPlugs is just the name of the argument. When testing I pass myPlug as nameOfPlugs. Commented Jun 10, 2015 at 10:19
  • Try require('../plugs/myPlug') instead of require('./../plugs/myPlug') Commented Jun 10, 2015 at 10:26
  • @victork, it does not work, as I already said in the question. ('../plugs/myPlug' is the return value of path.normalize('./../plugs/myPlug')) Commented Jun 10, 2015 at 11:38

2 Answers 2

2

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`);
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.