【问题标题】:How do I get the dirname of the calling method when it is in a different file in nodejs?当调用方法位于nodejs的不同文件中时,如何获取调用方法的目录名?
【发布时间】:2013-08-09 10:44:10
【问题描述】:

假设我有两个文件,dir/a.jslib/b.js

a.js:

b = require('../lib/b');
b.someFn();

b.js:

var fallback = "./config.json";
module.exports = {
  someFn = function(jsonFile) {
    console.log(require(jsonFile || fallback);
  }
}

这个例子中b.js的全部目的是读取一个json文件,所以我可以称它为b.someFn("path/to/file.json")

但我希望有一个默认值,例如配置文件。但默认值应该是相对于 a.js 而不是 b.js。换句话说,我应该能够从a.js 调用b.someFn(),它应该说,“既然你没有把路径传递给我,我将假设一个默认路径config.json。”但是默认值应该是相对于a.js,即应该是dir/config.json不是 lib/config.json,如果我这样做require(jsonFile),我会得到。

我可以获得cwd,但这只有在我从dir/ 中启动脚本时才有效。

b.js 有什么办法可以在someFn() 内部说“给我调用我的函数的__dirname?”

【问题讨论】:

  • 可以修改b模块吗?
  • 是的,我拥有b,没问题。实际上,b 正在变成一个模块,我只是希望它能够拥有一个相对于调用者的默认文件。
  • 然后简单的设置使用a.js所在的目录。查看答案。

标签: node.js


【解决方案1】:

使用callsite,然后:

b.js:

var path = require('path'),
    callsite = require('callsite');

module.exports = {
  someFn: function () {
    var stack = callsite(),
        requester = stack[1].getFileName();

    console.log(path.dirname(requester));
  }
};

【讨论】:

  • 这正是我想要的
【解决方案2】:

或者,使用parent-module:

const path = require('path');
const parentModule = require('parent-module');

// get caller of current script
console.log(path.dirname(parentModule()));
// get caller of module, change './index.js' to your "main" script
console.log(path.dirname(parentModule(require.resolve('./index.js'))));

【讨论】:

    【解决方案3】:

    如果要获取调用者函数的脚本目录,那么就使用上面答案的stacktrace,不然的话,a.js的目录硬编码有什么问题?

    var fallback = "dir_a/config.json";
    module.exports = {
      someFn = function(jsonFile) {
        console.log(require(jsonFile || fallback);
      }
    }
    

    【讨论】:

    • 因为b.js不知道a.js的目录。在我的示例中,我对其进行了简化,以便我们知道两者,但实际上 b.js 位于 npm 模块中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-08
    • 2017-11-10
    • 2013-07-07
    • 2011-01-17
    相关资源
    最近更新 更多