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.
The only expression that exposes the current line number and file is 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With