Node.js 当调用方法位于nodejs中的另一个文件中时,如何获取该方法的dirname?
假设我有两个文件,Node.js 当调用方法位于nodejs中的另一个文件中时,如何获取该方法的dirname?,node.js,Node.js,假设我有两个文件,dir/a.js和lib/b.js a、 js: b、 js: 本例中b.js的全部目的是读取json文件,因此我可以将其称为b.someFn(“path/to/file.json”) 但是我希望有一个默认值,比如一个配置文件。但是默认值应该是相对于a.js而不是b.js。换句话说,我应该能够从a.js调用b.someFn(),它应该说,“既然您没有向我传递路径,我将假定默认路径为config.json”,但是默认路径应该是相对于a.js,也就是说,应该是dir/config.
dir/a.js
和lib/b.js
a、 js:
b、 js:
本例中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()中说,“给我调用我的函数的\uu dirname
?”使用,然后:
b、 js:
如果您想要获取调用函数脚本的目录,那么使用stacktrace,如上面的答案所示,否则,硬编码a.js的目录有什么问题
var fallback = "dir_a/config.json";
module.exports = {
someFn = function(jsonFile) {
console.log(require(jsonFile || fallback);
}
}
或者,使用:
你能修改b
模块吗?是的,我拥有b
,没问题。实际上,b
正在变成一个模块,我只希望它能够有一个相对于调用方的默认文件。然后只需设置a.js所在的目录即可。查看答案。因为b.js
不知道a.js
的目录。在我的示例中,我对其进行了简化,以便我们两者都知道,但实际上b.js
位于npm
模块中。这正是我所寻找的
var fallback = "./config.json";
module.exports = {
someFn = function(jsonFile) {
console.log(require(jsonFile || fallback);
}
}
var path = require('path'),
callsite = require('callsite');
module.exports = {
someFn: function () {
var stack = callsite(),
requester = stack[1].getFileName();
console.log(path.dirname(requester));
}
};
var fallback = "dir_a/config.json";
module.exports = {
someFn = function(jsonFile) {
console.log(require(jsonFile || fallback);
}
}
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'))));