Get the path to the file from which the module is called?

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

      

This gives me the path to the module file. For example, if I saved the module in ~/project-root/lib/mod.js

and the file main.js

is in ~/project-root/main.js

, this setting gives me the output:

~/project-root/lib/mod.js

      

I want to use something instead __filename

in a module that gives me the location of the file it was called from. (for example, in this example, the output will be ~/project-root/main.js

).

The module can be located anywhere. Therefore, using path

just this example for configuration will fail in other scenarios (for example, if the module is stored in the ~/project-root/node_modules/

node.js modules or global directory.

I have a feeling this is pretty trivial and I am missing something. But I didn’t find a solution from anything that Google relented within an hour of searching. I may be using the wrong keywords!

+3


source to share


1 answer


Module.parent called in your module allows you to access the exports

file from which it was called.

You can put the function below in main.js

and you can call module.parent.filename()

in your module.



module.exports.filename = function () { return __filename; }

+1


source







All Articles