Nodejs Getting Parent Module Path
Suppose you have a module that loads files from a directory. But that directory is relative to the file requiring the module rather than to the module itself.
let App = require('core.io-express-server').defaultApp({
basepath: __dirname
});
How can we make core.io-express-server
to have a default value for basepath
to be the same as __dirname
?
We can use a the module
object:
In each module, the module free variable is a reference to the object representing the current module. For convenience, module.exports is also accessible via the exports module-global. module is not actually a global but rather local to each module.
Specifically, the parent
and filename
properties:
The module that first required this one.
The fully resolved filename to the module.
So we could use module.parent.filename
.
Code
example-module.js:
exports = function() {
return {
print : function(message) {
console.log(module.parent.filename + ' ' + message);
}
};
};
test.js:
var module = require('./example-module')();
module.print('Hello World!');
Output:
/path/to/module/test.js Hello World!