gpt4 book ai didi

javascript - 在 node.js 中获取调用函数的名称和行

转载 作者:IT老高 更新时间:2023-10-28 21:53:31 25 4
gpt4 key购买 nike

如何获得调用当前函数的函数的名称和行?我想要一个像这样的基本调试功能(使用 npmlog 定义 log.debug):

function debug() {
var callee, line;
/* MAGIC */
log.debug(callee + ":" + line, arguments)
}

当从另一个函数调用时,它会是这样的:

function hello() {
debug("world!")
}
// outputs something like:
// "hello:2 'world!'"

为了清楚起见,我想要的基本上类似于 this in Python :

import inspect
def caller():
return inspect.stack()[2][3]
// line no from getframeinfo().lineno

是否有等效的 Node 来完成此操作?

最佳答案

使用此处的信息:Accessing line number in V8 JavaScript (Chrome & Node.js)

您可以添加一些原型(prototype)以提供从 V8 访问此信息的权限:

Object.defineProperty(global, '__stack', {
get: function() {
var orig = Error.prepareStackTrace;
Error.prepareStackTrace = function(_, stack) {
return stack;
};
var err = new Error;
Error.captureStackTrace(err, arguments.callee);
var stack = err.stack;
Error.prepareStackTrace = orig;
return stack;
}
});

Object.defineProperty(global, '__line', {
get: function() {
return __stack[1].getLineNumber();
}
});

Object.defineProperty(global, '__function', {
get: function() {
return __stack[1].getFunctionName();
}
});

function foo() {
console.log(__line);
console.log(__function);
}

foo()

分别返回“28”和“foo”。

关于javascript - 在 node.js 中获取调用函数的名称和行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14172455/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com