访问V8 JavaScript中的行号(Chrome和Node.js)

jam*_*ack 60 javascript google-chrome v8 node.js

花在C之类的语言上的JavaScript开发人员经常会错过使用某些类型的内省的能力,比如记录行号,以及调用当前方法的方法.好吧,如果您使用的是V8(Chrome,Node.js),您可以使用以下内容.

jam*_*ack 93

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();
  }
});

console.log(__line);
Run Code Online (Sandbox Code Playgroud)

以上将记录19.

结合arguments.callee.caller您可以更接近通过宏在C中获得的有用日志记录的类型.

  • https://code.google.com/p/v8/wiki/JavaScriptStackTraceApi#Customizing_stack_traces列出了v8 StackTrace API中提供的其他方法.一般列表:getThis,getTypeName,getFunction,getFunctionName,getMethodName,getFileName,getLineNumber,getColumnNumber,getEvalOrigin,isToplevel,isEval,isNative,isConstructor (3认同)
  • @Michael https://github.com/v8/v8/wiki/Stack-Trace-API v8搬到了github wiki (2认同)
  • 2019 年 v8 堆栈跟踪 API 文档的 URL 为 https://v8.dev/docs/stack-trace-api (2认同)

alf*_*sin 5

接受的答案 IMO 的问题在于,当您想打印某些内容时,您可能会使用记录器,在这种情况下,使用已接受的解决方案将始终打印同一行:)

一些小的改变将有助于避免这种情况!

在我们的例子中,我们使用 Winston 进行日志记录,因此代码如下所示(注意下面的代码注释):

/**
 * Use CallSite to extract filename and number, for more info read: https://v8.dev/docs/stack-trace-api#customizing-stack-traces
 * @returns {string} filename and line number separated by a colon
 */
const getFileNameAndLineNumber = () => {
    const oldStackTrace = Error.prepareStackTrace;
    try {
        // eslint-disable-next-line handle-callback-err
        Error.prepareStackTrace = (err, structuredStackTrace) => structuredStackTrace;
        Error.captureStackTrace(this);
        // in this example I needed to "peel" the first CallSites in order to get to the caller we're looking for
        // in your code, the number of stacks depends on the levels of abstractions you're using
        // in my code I'm stripping frames that come from logger module and winston (node_module)
        const callSite = this.stack.find(line => line.getFileName().indexOf('/logger/') < 0 && line.getFileName().indexOf('/node_modules/') < 0);
        return callSite.getFileName() + ':' + callSite.getLineNumber();
    } finally {
        Error.prepareStackTrace = oldStackTrace;
    }
};
Run Code Online (Sandbox Code Playgroud)

  • 这是另一个很好的解决方案。我的答案是很久以前写的,但我相信我对“arguments.callee.caller”的引用也是为了解决您在这里提出的问题 (2认同)