以下是来自三个文件的示例代码:
// foo.js
var myFunc = require("./myFunc");
function foo(){
myFunc("message");
}
// bar.js
var myFunc = require("./myFunc");
function bar(){
myFunc("message");
}
// myFunc.js
module.exports = myFunc;
function myFunc(arg1){
console.log(arg1);
// Here I need the file path of the caller function
// For example, "/path/to/foo.js" and "/path/to/bar.js"
}
我需要动态地获取调用函数的文件路径,而不需要传递任何额外参数,对于myFunc
。
console.log((new Error()).stack.split("\n")[1].split("/").slice(-1)[0].split(":")[0]) // "caller_file_name.js"
- marcelosalloum