Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get path to function declaration in javascript

Tags:

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.

like image 575
JustinLovinger Avatar asked Dec 27 '25 22:12

JustinLovinger


1 Answers

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.

like image 73
Jonas Wilms Avatar answered Dec 30 '25 10:12

Jonas Wilms



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!