[英]Get path to function declaration in javascript
For example, given 例如,给定
// foo.js
function bar() {
...
}
How can I implement a function such as 我该如何实现诸如的功能
function getPathOf(func) {
return ...
}
console.log(getPathOf(foo.bar)) // Prints: "foo.js:1:1"
That is to say, how can I get the source file path, line number, and column number of a given function. 也就是说,如何获取给定函数的源文件路径,行号和列号。
I know Function.name gives the name of a function, and I have seen assertion libraries such as chai.js print the path to a function when printing a stack trace. 我知道Function.name给出了一个函数的名称,我看到断层库如chai.js在打印堆栈跟踪时打印了函数的路径。
The only expression that exposes the current line number and file is new Error
: 公开当前行号和文件的唯一表达式是
new Error
:
console.log((new Error()).stack);
thats how the libraries generate stacktraces, there is no other way to get it. 这就是库如何生成堆栈跟踪,没有其他方法可以获得它。
I guess something like: 我猜是这样的:
fs.readFileSync("foo.js").indexOf(func.toString())
might work somehow but thats just ugly and serves no real purpose. 可能会以某种方式工作,但这只是丑陋,并没有真正的目的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.