Accessing line number in V8 JavaScript (Chrome & Node.js)
Solution 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(__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.
Solution 2
The problem with the accepted answer, IMO, is that when you want to print something you might be using a logger, and when that is the case, using the accepted solution will always print the same line :)
Some minor changes will help avoiding such a case!
In our case, we're using Winston for logging, so the code looks like this (pay attention to the code-comments below):
/**
* 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;
}
};
james_womack
I started programming via JScript in IE 4, 1998. iOS/iPhoneOS in 2008, Node in 2011. I love teaching people new technologies and want to leverage technology to make everyday life better for everyone. Currently, I focus on: Improving dev + customer happiness by integrating cutting-edge tech into existing stacks at Netflix. This also is increasing frequency of feature deployments while decreasing bugs Implementing best practices in cross-functional multi-team dev environments, to produce more cohesive experiences for the customer Architecting full-stack systems that utilize bluetooth & cameras on mobile devices to deliver modern, friction-less customer experiences Client/server/database sharing of JavaScript code—I started on this in early 2012 along with some great programmers at Amco-IES and continued this work in ソニー
Updated on July 08, 2022Comments
-
james_womack almost 2 years
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.
-
zamnuts almost 11 yearscode.google.com/p/v8/wiki/… has a list of other methods available in the v8 StackTrace API. A general list: getThis, getTypeName, getFunction, getFunctionName, getMethodName, getFileName, getLineNumber, getColumnNumber, getEvalOrigin, isToplevel, isEval, isNative, isConstructor
-
Charles Kendrick about 10 yearsSee also this answer for some sample code to output the whole trace. stackoverflow.com/questions/6163807/…
-
james_womack about 10 yearsOne can see some example use of this API here: github.com/jameswomack/capn/blob/master/test/capn.js
-
Michael over 7 years@zamnuts That page doesn't seem to list any of those functions any more
-
mattyb about 7 yearsThis does not work in strict mode as it relies on arguments.callee :/
-
james_womack about 7 years@Midas It works in strict mode in Node.js—just paste 'use strict' and then my code example into the Node REPL to test. That said, the
__stack
technique is a special operation that you largely should not use in production code. FWIW I also typically use in Node.js rather than in Chrome. Many of the benefits of strict mode can be attained by using ESLint w/ ES6 in recent versions of Node. You can use a transpiler or bundler plugin to add 'strict' and strip out __stack for prod if you'd like. See Bunyan for a package that recommends conditionally using this technique. -
gtzilla over 4 yearsThe URL for documentation of v8 stack trace API in 2019 is v8.dev/docs/stack-trace-api
-
james_womack over 4 yearsThis is another great solution. My answer was written so long ago, but I believe my reference to
arguments.callee.caller
was about resolving the issue you raise here as well -
Nir Alfasi over 4 years@james_womack
arguments.callee.caller
is not always reachable (in my nodejs application it isn't). Also: eslint.org/docs/rules/no-caller but I guess it was okay to use it at the time your wrote the answer :) -
james_womack over 4 yearsunderstood—what you're saying makes sense
-
Jason Stewart over 2 years
arguments.callee
removed from ES5 strict mode: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… -
J-D3V about 2 yearsThe only problem with this answer is arguments.callee. It really shouldn't be used. Im surprised its even supported at all.