Node.js: How to get filename where function was required from within a module?

北城余情 提交于 2019-12-11 03:34:36

问题


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

What ends up happening is it will print module.js hello but I really want to see app.js hello.

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.

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.


回答1:


Getting Parent Module

You can do this by using module.parent , then resolving the filename property like so:

module.js

module.exports(function() {
   return {
     print : function(message) {
        console.log(module.parent.filename + ' ' + message);
     };
   }
});

app.js

var module = require('./module')();
module.print('hello');

Output:

/path/to/app.js hello

Which is almost what you're asking for.

Qualifying The Solution

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

Which would then give you "/app.js" in parentModFilename.




回答2:


You can use require.resolve(moduleName) to get the full path to the file. path.basename can strip the parent directories. So in your example:

var path = require("path");
var module = require('./module')();
process.stdout.write(path.basename(require.resolve('./module') + " ");
module.print('hello');


来源:https://stackoverflow.com/questions/28684480/node-js-how-to-get-filename-where-function-was-required-from-within-a-module

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!