从函数中,如何获取实际调用此函数的模块的详细信息?

时间:2017-04-28 19:55:16

标签: node.js

在通用函数中,我想获得有关调用此函数的模块的信息(特别是基本目录,它本身可以在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);

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

我正在寻找什么

例如:

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()函数内部,如何在不将其作为参数传递的情况下获取调用模块对象?也许处理堆栈跟踪的事情?

2 个答案:

答案 0 :(得分:1)

查看文档https://nodejs.org/api/modules.html#modules_the_module_object 他们提到require.mainrequire.parent属性。 如果它不适合您,请使用a.p关于使用new Error().stack

的评论

答案 1 :(得分:0)

我最后使用new Error().stack作为a.p建议;这里是最后的代码,遵循问题中的示例:

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

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