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)).
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.
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 get the calling module object, without passing it as a parameter? Maybe something dealing with the stack trace?
Check out documentation https://nodejs.org/api/modules.html#modules_the_module_object
They mention require.main and require.parent properties.
If it will not work for you, then use a.p's comment about using new Error().stack
I finally use new Error().stack as a.p suggested; here the final code, following the example in the question:
function unique_filter(value, index, self) {
return self.indexOf(value) === index;
}
function get_module_stack() {
return new Error().stack.split(/\n/)
.map(line => line.match(/\(([^:\)]*)/)) // Match lines with filenames
.filter(match => match !== null) // Remove null matches
.map(match => match[1]) // Map to the the actual filenames
.filter(unique_filter) // Make filenames unique
}
exports.print_calling_module_path = function()
{
console.log(get_module_stack()[1]);
}
However I'm not sure if this method is reliable enough to use it for production.
Any comment about it will be welcome.