0

How can I make require look in the relative path of the executing script (not whatever script has require'd the executing script)? Example:

index.js

require('lib/foo.js');

--

lib/foo.js

var barFunction = require('./bar.js').barFunction;
barFunction();

--

lib/bar.js

module.exports.barFunction = function(){
    return true;
}

When you node index.js, foo.js looks for bar.js instead of lib/bar.js.

If foo.js is amended to require('lib/bar.js'), then node foo.js will stop working.

How can I set up require in a way that I can both node index.js and node lib/foo.js and have then both work?

2
  • 1
    Did you try using ./lib/foo.js instead of lib/foo.js? Other than that, there isn't anything wrong with your code. Commented Dec 2, 2014 at 23:43
  • @mscdex: That won't work if I node foo.js directly in the lib folder. I need that to work as well. Commented Dec 2, 2014 at 23:43

1 Answer 1

2

You can use __dirname to get the absolute directory the currently executing script resides in. For example:

index.js:

require(__dirname + '/lib/foo.js');

lib/foo.js:

var barFunction = require(__dirname + '/bar.js').barFunction;
barFunction();
Sign up to request clarification or add additional context in comments.

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.