从一个函数,如何获得有关实际调用此函数的模块的详细信息?

在一个通用函数中,我想获取有关调用此函数的模块的信息(特别是基本目录,它本身可以在模块内用path.dirname(module.filename) )进行检索。

我试过了

现在,我发现这样做的唯一方法是添加module作为函数的参数:

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

…但它强制使用一个额外的参数,污染function的参数列表(可能?)可抵扣信息。

我在找什么

例如:

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 */); 

print_calling_module_path()函数内部,如何获取调用模块对象,而不将其作为parameter passing? 也许处理堆栈跟踪的东西?

查看文档https://nodejs.org/api/modules.html#modules_the_module_object他们提到&#x4E86;require.mainrequire.parent属性。 如果它不适合你,那么使用ap关于使用new Error().stack的注释

我最后使用new Error().stackbuild议; 这里是最后的代码,下面的问题中的例子:

LIB / MY-lib.js:

 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]); } 

不过,我不确定这种方法是否足够可靠,可用于生产。
有关它的任何评论将是受欢迎的。