Accessing Line Number in JavaScript V8 (Chrome & Node.js)

JavaScript developers who have spent time in languages ​​such as C often overlook the ability to use certain types of introspection, such as log line numbers and the method from which the current method was called. Well, if you use V8 (Chrome, Node.js), you can use the following.

+45
javascript google-chrome v8
Jul 08 2018-12-12T00:
source share
2 answers
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 be recorded 19 .

When combined with arguments.callee.caller you can come close to the type of useful logging you get in C through macros.

+75
Jul 08 2018-12-12T00:
source share

Apparently this works in a node or Chrome browser as well (possibly others)

 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 
-2
Jan 02 '13 at 4:52
source share



All Articles