How to print a stack trace in Node.js?
Any Error
object has a stack
member that traps the point at which it was constructed.
var stack = new Error().stackconsole.log( stack )
or more simply:
console.trace("Here I am!")
As already answered, you can simply use the trace command:
console.trace("I am here");
However, if you came to this question searching about how to log the stack trace of an exception, you can simply log the Exception object.
try { // if something unexpected throw new Error("Something unexpected has occurred."); } catch (e) { console.error(e);}
It will log:
Error: Something unexpected has occurred.
at main (c:\Users\Me\Documents\MyApp\app.js:9:15)
at Object. (c:\Users\Me\Documents\MyApp\app.js:17:1)
at Module._compile (module.js:460:26)
at Object.Module._extensions..js (module.js:478:10)
at Module.load (module.js:355:32)
at Function.Module._load (module.js:310:12)
at Function.Module.runMain (module.js:501:10)
at startup (node.js:129:16)
at node.js:814:3
If your Node.js version is < than 6.0.0, logging the Exception object will not be enough. In this case, it will print only:
[Error: Something unexpected has occurred.]
For Node version < 6, use console.error(e.stack)
instead of console.error(e)
to print the error message plus the full stack, like the current Node version does.
Note: if the exception is created as a string like throw "myException"
, it's not possible to retrieve the stack trace and logging e.stack
yields undefined.
To be safe, you can use
console.error(e.stack || e);
and it will work for old and new Node.js versions.