如何获取Node中调用函数的文件名和行号?

kra*_*r65 7 javascript node.js

在Python中工作时,我总是有这个简单的实用程序函数,它返回调用函数的文件名和行号:

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)
Run Code Online (Sandbox Code Playgroud)

所以在我的代码中我只是简单地放了几个这样的调试行来看看在发生错误之前我们得到了多少:

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

这对我来说非常有用,因为它确实有助于快速调试.

我现在正在寻找节点后端脚本中的等价物.我在寻找,但我找不到任何有用的东西(也许我在寻找错误的词?).

有谁知道如何创建一个Javascript/nodejs函数,它输出调用函数的文件名和行号?欢迎所有提示!

lil*_*zek 9

您可以创建一个错误来获取错误所在的位置及其堆栈跟踪.然后你可以将它放入一个函数中,以获得它所在的行.

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());
Run Code Online (Sandbox Code Playgroud)

这适用于Google Chrome.

而且在节点中.

请注意@ j08691的评论:

这个这个似乎可以用lineNumber,这是不存在的(据我可以测试)中的NodeJS.