如何获取在 Node 中调用函数的文件名和行号
How to get filename and line number of where a function is called in Node?
在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 --save
和npm 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 月才添加的。
- 是否可以将一个函数输入连接到另一个函数调用的文本
- 在输入字段上有两个函数调用,一个在Blur上,一个不在Angular中
- 如何在Javascript函数调用中循环变量
- Javascript:应为赋值或函数调用,但实际看到的却是表达式
- 如何远程检查JavaScript应用程序的函数调用堆栈
- javascript函数调用不起作用
- 为什么这个函数调用会破坏程序并导致未定义的变量
- 如何通过函数调用设置图像的src
- 从全局函数调用Ember控制器上的方法
- 为什么Jquery$.ajax在函数调用中触发所有statusCode,即使调用成功
- JavaScript函数调用(arg1)(arg2)
- 打印链接时,将javascript函数调用到链接中
- 在函数调用中封装数据除了隐藏数据之外还有什么优点
- 无法从JavaScript中的函数调用对象属性
- 对中的函数调用进行排序是回调的唯一方法
- 函数调用方法有什么用
- Javascript:JSHint:应为赋值或函数调用,但实际看到的却是表达式
- HTML5(Bootstrap)通过函数调用运行动画
- 函数调用不起作用
- 函数中的Javascript函数调用