获取node.js中的调用函数的名称和行 [英] Get name and line of calling function in node.js
本文介绍了获取node.js中的调用函数的名称和行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何获取调用当前函数的函数的名称和行?我希望有这样一个基本的调试功能(使用 npmlog 定义日志。 debug
):
How can one get the name and line of a function that called the current one? I would like to have a rudimentary debugging function like this (with npmlog defining log.debug
):
function debug() {
var callee, line;
/* MAGIC */
log.debug(callee + ":" + line, arguments)
}
当从另一个函数调用时,它将是这样的:
When called from another function it would be something like this:
function hello() {
debug("world!")
}
// outputs something like:
// "hello:2 'world!'"
为清楚起见,我想要的基本上类似于这在Python中:
For clarity, what I want is essentially analogous to this in Python:
import inspect
def caller():
return inspect.stack()[2][3]
// line no from getframeinfo().lineno
是否有一个等效的Node来实现这个目标?
Is there a Node equivalent to accomplish this?
推荐答案
使用此处的信息:访问V8 JavaScript中的行号(Chrome& Node.js)
你可以在pr中添加一些原型ovide从V8访问此信息:
you can add some prototypes to provide access to this info from 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',分别。
Returns '28' and 'foo', respectively.
这篇关于获取node.js中的调用函数的名称和行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文