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

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.

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.

apparently this works too in node or chrome browser (possibly others as well)

line = (o) ->
  b = Error.prepareStackTrace
  Error.prepareStackTrace = (_, stack) -> stack
  e = new Error
  Error.captureStackTrace e, o
  s = e.stack
  Error.prepareStackTrace = b
  s[1].getLineNumber()

console.log line this

or:

lineNumber=(o)->E=Error;p='prepareStackTrace';b=E[p];E[p]=((_,s)->s);e=new E;E.captureStackTrace e,o;s=e.stack;E[p]=b;s[1].getLineNumber()

console.log lineNumber this