Accessing line number in V8 JavaScript (Chrome & Node.js)

james_womack picture james_womack · Jul 8, 2012 · Viewed 27.5k times · Source

JavaScript developers who have spent time in languages like C often miss the ability to use certain types of introspection, like logging line numbers, and what method the current method was invoked from. Well if you're using V8 (Chrome, Node.js) you can employ the following.

Answer

james_womack picture james_womack · Jul 8, 2012
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);

The above will log 19.

Combined with arguments.callee.caller you can get closer to the type of useful logging you get in C via macros.