Node.js:如何在模块中需要功能的地方获取文件名? [英] Node.js: How to get filename where function was required from within a module?
问题描述
我正在尝试从需要模块功能的位置获取原始文件名.我知道您可以使用__filename
来获取当前文件,但是我想获取原始文件.
I'm trying to get the original filename from where a module's function has been required from. I know you can use __filename
to get the current file, but I want to get the original file.
例如,我将拥有一个简单的模块
For example a simple module I have would be
module.js
module.exports(function() {
return {
print : function(message) {
console.log(__filename + ' ' + message);
};
}
});
app.js
var module = require('./module')();
module.print('hello');
最终发生的事情是它将打印module.js hello
,但是我真的很想看看app.js hello
.
What ends up happening is it will print module.js hello
but I really want to see app.js hello
.
我正在探索获取它的方法,我知道您可以使用console.trace
来查看调用堆栈,但是我无法解析它来执行我想要的操作.
I was exploring ways to get it and I know you can use console.trace
to see the stack of calls but I can't parse it to do what I want.
现在,我已经通过使print
函数采用另一个参数来解决此问题,您只需从app.js
内部传递__filename
,但是我有点想找到一种解决方案,我不必做到这一点.
Right now I've worked about it by making the print
function take in another parameter and you simply pass __filename
from within app.js
but I kind of want to find a solution where I don't have to do this.
推荐答案
获取父模块
您可以使用 module.parent
来解决此问题,然后解析
Getting Parent Module
You can do this by using module.parent
, then resolving the filename
property like so:
module.exports(function() {
return {
print : function(message) {
console.log(module.parent.filename + ' ' + message);
};
}
});
app.js
var module = require('./module')();
module.print('hello');
输出:
/path/to/app.js hello
您几乎要的是什么.
此解决方案为您提供了完全限定的路径,但是您可以通过用路径分隔符分割路径来获取文件名.
This solution provides you with a fully qualified path, but you get the filename by splitting the path by its delimiter.
var parentModFilename = module.parent.filename.split(/\\|\//).pop()
然后在parentModFilename
中给您"/app.js"
.
这篇关于Node.js:如何在模块中需要功能的地方获取文件名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!