apscience
apscience

Reputation: 7273

Node.js relative require paths to executing script

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?

Upvotes: 0

Views: 163

Answers (1)

mscdex
mscdex

Reputation: 106736

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

Upvotes: 2

Related Questions