Reputation: 1181
Let's say I have a node.js module
module.exports = function () {
console.log(__filename);
}
And in the main file I call it like
var x = require('path/to/module');
x();
That gives me the path to the module file. For example if I stored the module at ~/project-root/lib/mod.js
and the main.js
file lies at ~/project-root/main.js
, that setup gives me the output:
~/project-root/lib/mod.js
I want to use something in place of __filename
in the module that gives me to location of of the file from which it was called from. (e.g. the output would be ~/project-root/main.js
instead, in this example).
The module can be located anywhere. So using path
to adjust for only this example would fail in other scenarios (for example if module is stored in ~/project-root/node_modules/
or the global node.js modules directory.
I have a feeling it's something fairly trivial and I'm overlooking something. But I haven't found a solution from anything Google has yielded during an hour long search. Maybe I'm using the wrong keywords!
Upvotes: 4
Views: 1382
Reputation: 604
Module.parent called in your module lets you access to the exports
of the file it was called from.
You can put the function below in your main.js
and you can call module.parent.filename()
in your module.
module.exports.filename = function () {
return __filename;
}
Upvotes: 2