[javascript] How to print a stack trace in Node.js?

Does anyone know how to print a stack trace in Node.js?

This question is related to javascript node.js stack-trace

The answer is


With a readily available Node module, it is possible to get full-length stack traces out of Node (albeit with a minor performance penalty): http://www.mattinsler.com/post/26396305882/announcing-longjohn-long-stack-traces-for-node-js


@isaacs answer is correct, but if you need more specific or cleaner error stack, you can use this function:

function getCleanerStack() {
   var err = new Error();
   Error.captureStackTrace(err, getStack);

   return err.stack;
}

This function is inspired directly from the console.trace function in NodeJS.

Source code: Recent version or Old version.


Try Error.captureStackTrace(targetObject[, constructorOpt]).

const myObj = {};
function c() {
  // pass
}

function b() {
    Error.captureStackTrace(myObj)
    c()
} 

function a() {
    b()
}

a()

console.log(myObj.stack)

The function a and b are captured in error stack and stored in myObj.


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.


Any Error object has a stack member that traps the point at which it was constructed.

var stack = new Error().stack
console.log( stack )

or more simply:

console.trace("Here I am!")

In case someone is still looking for this like I was, then there is a module we can use called "stack-trace". It is really popular. NPM Link

Then walk through the trace.

  var stackTrace = require('stack-trace');
  .
  .
  .
  var trace = stackTrace.get();
  trace.map(function (item){ 
    console.log(new Date().toUTCString() + ' : ' +  item.toString() );  
  });

Or just simply print the trace:

var stackTrace = require('stack-trace');
.
.
.
var trace = stackTrace.get();
trace.toString();

To print stacktrace of Error in console in more readable way:

console.log(ex, ex.stack.split("\n"));

Example result:

[Error] [ 'Error',
  '    at repl:1:7',
  '    at REPLServer.self.eval (repl.js:110:21)',
  '    at Interface.<anonymous> (repl.js:239:12)',
  '    at Interface.EventEmitter.emit (events.js:95:17)',
  '    at Interface._onLine (readline.js:202:10)',
  '    at Interface._line (readline.js:531:8)',
  '    at Interface._ttyWrite (readline.js:760:14)',
  '    at ReadStream.onkeypress (readline.js:99:10)',
  '    at ReadStream.EventEmitter.emit (events.js:98:17)',
  '    at emitKey (readline.js:1095:12)' ]

For what I know printing the complete stack trace in nodejs is not possible, you can just print a "partial" stack trace, you can not see from where you came from in the code, just where the Exception occur. That's what Ryan Dahl explains in this youtube video. http://youtu.be/jo_B4LTHi3I at min 56:30 for being precise. Hope this helps


Now there's a dedicated function on console for that:

console.trace()

you can use node-stack-trace module which is a power full module to track call stacks.


If you want to only log the stack trace of the error (and not the error message) Node 6 and above automatically includes the error name and message inside the stack trace, which is a bit annoying if you want to do some custom error handling:

console.log(error.stack.replace(error.message, ''))

This workaround will log only the error name and stack trace (so you can, for example, format the error message and display it how you want somewhere else in your code).

The above example would print only the error name follow by the stack trace, for example:

Error: 
    at /Users/cfisher/Git/squashed/execProcess.js:6:17
    at ChildProcess.exithandler (child_process.js:213:5)
    at emitTwo (events.js:106:13)
    at ChildProcess.emit (events.js:191:7)
    at maybeClose (internal/child_process.js:877:16)
    at Socket.<anonymous> (internal/child_process.js:334:11)
    at emitOne (events.js:96:13)
    at Socket.emit (events.js:188:7)
    at Pipe._handle.close [as _onclose] (net.js:498:12)

Instead of:

Error: Error: Command failed: sh ./commands/getBranchCommitCount.sh HEAD
git: 'rev-lists' is not a git command. See 'git --help'.

Did you mean this?
        rev-list

    at /Users/cfisher/Git/squashed/execProcess.js:6:17
    at ChildProcess.exithandler (child_process.js:213:5)
    at emitTwo (events.js:106:13)
    at ChildProcess.emit (events.js:191:7)
    at maybeClose (internal/child_process.js:877:16)
    at Socket.<anonymous> (internal/child_process.js:334:11)
    at emitOne (events.js:96:13)
    at Socket.emit (events.js:188:7)
    at Pipe._handle.close [as _onclose] (net.js:498:12)

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to node.js

Hide Signs that Meteor.js was Used Querying date field in MongoDB with Mongoose SyntaxError: Cannot use import statement outside a module Server Discovery And Monitoring engine is deprecated How to fix ReferenceError: primordials is not defined in node UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block dyld: Library not loaded: /usr/local/opt/icu4c/lib/libicui18n.62.dylib error running php after installing node with brew on Mac internal/modules/cjs/loader.js:582 throw err DeprecationWarning: Buffer() is deprecated due to security and usability issues when I move my script to another server Please run `npm cache clean`

Examples related to stack-trace

Couldn't load memtrack module Logcat Error How to Add Stacktrace or debug Option when Building Android Studio Project How to log as much information as possible for a Java Exception? e.printStackTrace equivalent in python Why is exception.printStackTrace() considered bad practice? How to store printStackTrace into a string Get exception description and stack trace which caused an exception, all as a string How to send a stacktrace to log4j? How to print full stack trace in exception? What is a stack trace, and how can I use it to debug my application errors?