In a general-purpose function, I would like to get informations about the module which calls this function (especially the base directory, which can itself be retrieved inside a module with path.dirname(module.filename)
).
What I tried
For now, the only way I found to do it is to add module
as a parameter for the function:
lib/my-lib.js:
const path = require('path');
exports.print_calling_module_path = function(calling_module) {
console.log(path.dirname(calling_module.filename));
}
main.js:
const my_lib = require('./lib/my-lib.js');
console.log('Here is the path of this actual module:');
my_lib.print_calling_module_path(module);
... but it forces to use an extra parameter, which pollutes the argument list of functions with a (possibly?) deductible information.
What I'm looking for
For example:
lib/my-lib.js:
const path = require('path');
exports.print_calling_module_path = function(/* no extra argument */) {
let calling_module = .... ; // <== How to get this ??
console.log(path.dirname(calling_module.filename));
}
main.js:
const my_lib = require('./lib/my-lib.js');
console.log('Here is the path of this actual module:');
my_lib.print_calling_module_path(/* no extra argument */);
Inside the print_calling_module_path()
function, how can I deduct the calling module's whole path without passing it as a parameter? Maybe something dealing with the stack trace?
via yolenoyer
No comments:
Post a Comment