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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14172455/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 15:54:52  来源:igfitidea点击:

Get name and line of calling function in node.js

javascriptnode.js

提问by Brian M. Hunt

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 npmlogdefining log.debug):

如何获得调用当前函数的函数的名称和行?我想要一个像这样的基本调试功能(使用npmlog定义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!'"

For clarity, what I want is essentially analogous to this in Python:

为清楚起见,我想要的本质上类似于Python 中的这个

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

Is there a Node equivalent to accomplish this?

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

回答by Joe

Using info from here: Accessing line number in V8 JavaScript (Chrome & Node.js)

使用此处的信息:访问 V8 JavaScript 中的行号(Chrome 和 Node.js)

you can add some prototypes to provide access to this info from V8:

您可以添加一些原型来提供对 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()

Returns '28' and 'foo', respectively.

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

回答by Vikash

I also had similar requirement. I used stack property of Error class provided by nodejs.
I am still learning node so, there may be the chances of error.

我也有类似的需求。我使用了 nodejs 提供的 Error 类的 stack 属性。
我还在学习节点,所以可能有错误的机会。

Below is the explanation for the same. Also created npm module for the same, if you like, you can check at:
1. npm module 'logat'
2. git repo

下面是相同的解释。还为此创建了 npm 模块,如果您愿意,可以查看:
1. npm module 'logat'
2. git repo

suppose we 'logger' object with method 'log'

假设我们使用方法“log”来“记录”对象

var logger = {
 log: log
}
function log(msg){
  let logLineDetails = ((new Error().stack).split("at ")[3]).trim();
  console.log('DEBUG', new Date().toUTCString(), logLineDetails, msg);
}

Example:

例子:

//suppose file name: /home/vikash/example/age.js
function getAge(age) {
    logger.log('Inside getAge function');    //suppose line no: 9
}

Output of above Example:

上面例子的输出:

    DEBUG on Sat, 24 Sept 2016 12:12:10 GMT at getAge(/home/vikash/example/age.js:9:12)
    Inside getAge function

回答by Cosmin Staicu

The following code uses only core elements. It parses the stack from an error instance.

以下代码仅使用核心元素。它从错误实例解析堆栈。

"use strict";
function debugLine(message) {
    let e = new Error();
    let frame = e.stack.split("\n")[2];
    let lineNumber = frame.split(":")[1];
    let functionName = frame.split(" ")[5];
    return functionName + ":" + lineNumber + " " + message;
}
function myCallingFunction() {
    console.log(debugLine("error_message"));
}
myCallingFunction();

It outputs something like myCallingFunction:10 error_message

它输出类似 myCallingFunction:10 error_message

I've extracted the elements of the error as variables (lineNumber, functionName) so you can format the return value any way you want.

我已将错误的元素提取为变量(lineNumber、functionName),因此您可以以任何您想要的方式格式化返回值。

As a side note: the use strict;statement is optional and can be used only if your entire code is using the strictstandard. If your code is not compatible with that (although it should be), then feel free to remove it.

附带说明:该use strict;语句是可选的,只有在您的整个代码都使用严格标准时才能使用。如果您的代码与此不兼容(尽管它应该是),请随时将其删除。

回答by Brian M. Hunt

I found and installed the node-stack-tracemodule (installed with npm install stack-trace), and then defined echoas:

我找到并安装了node-stack-trace模块(用 安装npm install stack-trace),然后定义echo为:

function echo() {
  var args, file, frame, line, method;
  args = 1 <= arguments.length ? __slice.call(arguments, 0) : [];

  frame = stackTrace.get()[1];
  file = path.basename(frame.getFileName());
  line = frame.getLineNumber();
  method = frame.getFunctionName();

  args.unshift("" + file + ":" + line + " in " + method + "()");
  return log.info.apply(log, args); // changed 'debug' to canonical npmlog 'info'
};

回答by Alexander Klimetschek

Here is a one liner for quick debugging purposes:

这是一个用于快速调试的单行代码:

console.log("DEBUG", (new Error().stack.split("at ")[1]).trim());

This will log something like this with Node.js:

这将使用 Node.js 记录如下内容:

DEBUG SomeObject.function (/path/to/the/code.js:152:37) 

--

——

You can also add custom args at the end, e.g.

您还可以在最后添加自定义参数,例如

console.log("DEBUG", (new Error().stack.split("at ")[1]).trim(), ">>>", myVar);

Note that if you put this into a helper function, adjust the stack index from e.g. [1]to [2].

请注意,如果您将其放入辅助函数中,请将堆栈索引从 eg 调整[1][2]