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

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

本文关键字:函数 调用 文件名 Node 何获取 获取      更新时间:2024-02-19

在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

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

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

有谁知道我如何创建一个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());

这在谷歌浏览器中对我有用。

并且在节点中。

请注意@j08691的评论:

和这似乎都在使用 lineNumber ,这在 NodeJS 中不存在(据我测试

(。

使用自定义字符串打印行号

const moment = require('moment');
const log = console.log;
const path = require('path');
function getTime(time) { return moment().format('YYYY-MM-DD HH:mm:ss') };
function line(num = 2) {
    const e = new Error();
    const regex = /'((.*):('d+):('d+)')$/
    const match = regex.exec(e.stack.split("'n")[num]);
    const filepath = match[1];
    const fileName = path.basename(filepath);
    const line = match[2];
    const column = match[3];
    return {
        filepath,
        fileName,
        line,
        column,
        str: `${getTime()} - ${fileName}:${line}:${column}`
    };
}
log(line().str, "mylog1");
log(line().str, "mylog2");
log(line().str, "mylog3");

输出

2021-11-22 13:07:15 - test.js:44:5 mylog1
2021-11-22 13:07:15 - test.js:45:5 mylog2
2021-11-22 13:07:15 - test.js:46:5 mylog3

你可以使用这个 gulp 插件 gulp-log-line .它记录文件和行号,而无需读取堆栈的额外费用。

你只需要安装gulp和gulp-log-line使用。 npm install gulp --savenpm install gulp-log-line命令。之后,您需要在gulpfile中创建并编写以下代码.js然后运行 gulp log-line在构建文件夹中创建重复文件:-

var gulp = require('gulp');
var logLine = require('gulp-log-line');
gulp.task('line-log', function() {
  return gulp.src("file.js", {buffer : true})
//Write here the loggers you use.
    .pipe(logLine(['console.log', 'winston.info']))
    .pipe(gulp.dest('./build'))
})
gulp.task('default', ['line-log'])

文件.js :-

console.log('First log')
var someVariable
console.log('Second log')

成为

console.log('file.js:1', 'First log')
var someVariable
console.log('file.js:3', 'Second log')

我发现获取与行号相关的任何内容的唯一方法是捕获window.onerror函数,当出现将传递错误消息的错误时,文件 URL 和行号:

window.onerror = function(msg, url, line) {
    alert(msg + "'n" + url + ":" + line);
};

这在 Chrome 上对我有用 - 我不知道其他浏览器。

编辑 当这个答案在 2 月 15 日给出时,问题中没有提到 NodeJS。 这是在 17 年 11 月才添加的。