如何在node.js中获取调用函数的文件路径?
以下是三个文件的示例代码:
Here is some sample code from three files:
// 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
。
I need to get the file path of the caller function dynamically, without any extra argument passing, for myFunc
.
你需要摆弄 V8
。请参阅:有关JavaScript Stack Trace API的Wiki条目。
You need to fiddle with the inner workings of v8
. See: the wiki entry about the JavaScript Stack Trace API.
我对提议的一些代码进行了一点测试提交,它似乎工作。最终得到绝对路径。
I've based a little test on some code in a proposed commit and it seems to work. You end up with an absolute path.
// omfg.js
module.exports = omfg
function omfg() {
var caller = getCaller()
console.log(caller.filename)
}
// private
function getCaller() {
var stack = getStack()
// Remove superfluous function calls on stack
stack.shift() // getCaller --> getStack
stack.shift() // omfg --> getCaller
// Return caller's caller
return stack[1].receiver
}
function getStack() {
// Save original Error.prepareStackTrace
var origPrepareStackTrace = Error.prepareStackTrace
// Override with function that just returns `stack`
Error.prepareStackTrace = function (_, stack) {
return stack
}
// Create a new `Error`, which automatically gets `stack`
var err = new Error()
// Evaluate `err.stack`, which calls our new `Error.prepareStackTrace`
var stack = err.stack
// Restore original `Error.prepareStackTrace`
Error.prepareStackTrace = origPrepareStackTrace
// Remove superfluous function call on stack
stack.shift() // getStack --> Error
return stack
}
包含的测试包括 omfg
模块:
#!/usr/bin/env node
// test.js
var omfg = require("./omfg")
omfg()
您将在控制台上获得 test.js
的绝对路径。
And you will get on the console the absolute path of test.js
.
说明
这不是一个node.js问题,因为它是v8问题。
This is not so much a "node.js" issue as it is a "v8" issue.
请参阅:自定义例外的堆栈跟踪集合
Error.captureStackTrace(error,constructorOpt)
添加错误
参数 stack
属性,该属性进行评估默认为字符串
(通过 FormatStackTrace
)。如果 Error.prepareStackTrace(error,structuredStackTrace)
是函数
,则调用它而不是 FormatStackTrace
。
Error.captureStackTrace(error, constructorOpt)
adds to the error
parameter a stack
property, which evaluates by default to a String
(by way of FormatStackTrace
). If Error.prepareStackTrace(error, structuredStackTrace)
is a Function
, then it is called instead of FormatStackTrace
.
因此,我们可以使用我们自己的函数覆盖 Error.prepareStackTrace
这将返回我们想要的任何东西 - 在这种情况下,只需 structuredStackTrace
参数。
So, we can override Error.prepareStackTrace
with our own function that will return whatever we want--in this case, just the structuredStackTrace
parameter.
然后, structuredStackTrace [1] .receiver
是表示调用者的对象。
Then, structuredStackTrace[1].receiver
is an object representing the caller.