0

I'm wondering if it's possible to get the line number of a statement inside a .js file. For instance:

// line 1
// line 2
detectLineNumber();
// line 4

How can I have detectLineNumber() to find where it was invoked and console-log the line number 3? Is it possible?

UPDATE I'm afraid (new Error).lineNumber won't work for me since it doesn't work in Chrome. Answer should be cross-browser.

Ramtin Soltani
  • 2,650
  • 3
  • 24
  • 45
  • 2
    Just curious: why would you want to? – nnnnnn Jul 03 '16 at 08:24
  • I'm implementing a reporter for my unit tests. I want to console-log the line number of where the reporter's function reported something. Usually when an error occurs, most native reporters show the file and line number of where it occurred. So it would be a big help to know where to look for the error. – Ramtin Soltani Jul 03 '16 at 08:27
  • 1
    @RamtinSoltani see the second part of the answer on that question, and also http://stackoverflow.com/questions/1340872/how-to-get-javascript-caller-function-line-number-how-to-get-javascript-caller – CupawnTae Jul 03 '16 at 08:42
  • *"Answer should be cross-browser."* Well, presumably it would be fine if the answer were specific to V8, as you're doing this in NodeJS. (And the linked question has answers applicable to V8.) Re your comment on the answer below (which may not still be there) *"The problem with it is that I can't determine the exact line number of the function. If I do it inside the function, it would always return where the function is defined, not where it got invoked."* The second entry in the stack tells you where it was invoked. – T.J. Crowder Jul 03 '16 at 08:46
  • @CupawnTae Does it work in all browsers? I've checked Chrome and Firefox and it checks out. – Ramtin Soltani Jul 03 '16 at 08:47

0 Answers0