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

标签 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)

所以在我的代码中,我只是简单地放置了几行这样的调试行,以查看在出现错误之前我们能走多远:

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

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

我现在正在寻找 Node 后端脚本中的等效项。我四处搜索,但找不到任何有用的东西(也许我在寻找错误的词?)。

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

最佳答案

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

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 .

注意@j08691 的评论:

两者都是thisthis似乎正在使用 lineNumber,它在 NodeJS 中不存在(据我测试)。

关于javascript - 如何获取在 Node 中调用函数的文件名和行号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28631260/

相关文章:

javascript - WebUI Popover 无法使用 html 元素设置标题

javascript - 无法在 React 中更改类

javascript - Express:获取完整路线参数

javascript - Node 集群在master和集群之间共享数据

javascript - 在现有网站中实现 Nodejs 应用程序

javascript - Node JS 将可能未定义的 JavaScript 对象传递给 pug 模板

javascript - 初学者 javascript/jquery - document.write

javascript - mCustomScrollbar 滚动条显示在隐藏的div上

javascript - 如何检查 DOM 中 div 的所有类名是否具有带有 vanilla Javascript 的特定字符串?

node.js - 快速记录响应正文