【问题标题】:Get line number of every statement that is evaluated in a script获取脚本中评估的每个语句的行号
【发布时间】:2012-10-10 17:42:02
【问题描述】:

在 Node.js 中,我试图获取脚本中调用的每个函数的行号。有没有办法生成脚本中调用的每个函数的摘要?我想获取脚本中每个函数调用的行号列表,以便我可以注释掉其中一个函数调用(我仍在尝试查找。)

一个例子:

function printStuff(){
    console.log("This is an example.");
}
printStuff();
printStuff();

现在我想获得此脚本中所有事件的摘要(无需修改脚本)。它可能看起来像这样:

calling printStuff at line 4
calling console.log at line 2
calling printStuff at line 5
calling console.log at line 2

是否有任何测试/调试工具可以做到这一点?

【问题讨论】:

标签: javascript node.js


【解决方案1】:

我猜这不是你要找的东西,但你应该能够根据自己的需要进行修改:

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("I am running from line " + __line);

讨论过here

【讨论】:

  • 如何修改此脚本,以便打印脚本中运行的每个函数的行号?
  • 这里在 jsfiddle 上:jsfiddle.net/jarble/dG5Q2 运行它时收到以下错误消息:Uncaught ReferenceError: global is not defined
  • 这个脚本在 node.js 中运行得很好,但是。是否有可能让它在浏览器中也能工作?
猜你喜欢
  • 2014-11-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多