Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get filename and line number of where a function is called in Node?

When working in Python I always have this simple utility function which returns the file name and line number from where the function is called:

from inspect import getframeinfo, stack
def d():
    """ d stands for Debug. It returns the file name and line number from where this function is called."""
    caller = getframeinfo(stack()[1][0])
    return "%s:%d -" % (caller.filename, caller.lineno)

So in my code I simply put a couple debug lines like this to see how far we get before some error occurs:

print d()
# Some buggy code here
print d()
# More buggy code here
print d(), 'here is the result of some var: ', someVar

This works really well for me because it really helps debugging quickly.

I'm now looking for the equivalent in a node backend script. I was searching around but I can't find anything useful (maybe I'm looking for the wrong words?).

Does anybody know how I can create a Javascript/nodejs function which outputs the file name and line number from where the function is called? All tips are welcome!

like image 321
kramer65 Avatar asked Feb 20 '15 14:02

kramer65


People also ask

What is __ filename in node?

The __filename represents the filename of the code being executed. This is the resolved absolute path of this code file. For a main program, this is not necessarily the same filename used in the command line. The value inside a module is the path to that module file.

How do you call a node function?

To call a function, you can either pass its name and arguments to User. callFunction() or call the function as if it was a method on the User.


1 Answers

You can create an Error to get where the Error is, and its stack trace. Then you can put that into a function, to get the line where it is.

function thisLine() {
  const e = new Error();
  const regex = /\((.*):(\d+):(\d+)\)$/
  const match = regex.exec(e.stack.split("\n")[2]);
  return {
    filepath: match[1],
    line: match[2],
    column: match[3]
  };
}

console.log(thisLine());

This works for me in Google Chrome.

And also in node.

Note to @j08691's comment:

Both this and this seem to be using lineNumber, which is not present (as far as I could test) in NodeJS.

like image 160
lilezek Avatar answered Oct 14 '22 10:10

lilezek