a blog for those who code

Tuesday, 9 June 2015

Get Call Stack Information in NodeJS

In this post we are going to discuss about extracting stack-trace/call stack information in NodeJS using traceback. As a developer is always a boon if you can reduce your development time or more precisely debugging time. NodeJS has a number of excellent feature, but it is not as good in terms of debugging.

According to traceback, you will get an easy access to the call stack which is actually written in pure JavaScript. Traceback provides a normal JavaScript array of the execution stack frames. You can see function names, line numbers and other useful stuff.


Also Read : Better logging in Nodejs using Bunyan

Suppose we have a following code snippet where I forgot to initialize the server ( See commented code).

var dgram = require('dgram');
//var server = dgram.createSocket('udp4');
server.on("message", function(msg, rinfo) {
console.log("Message: " + msg + " from " + rinfo.address + ":" + rinfo.port);
});
server.bind(8124);

This code will give us the error server is not defined and actually point us to the actual location, but the problem is it is the string. What if you want to send a report of the error via email or you need to write that in a file. Then traceback will come to our rescue.



Installation and Use of traceback

Traceback is available for installation from NPM using npm install traceback. Simply calling the traceback() will give you the stack, with the current function in position 0. You can get the function name, path name, file name, line number, column number, byte position etc.

var traceback = require('traceback');
function a() { b(); }
function b() { trace(); }

function trace() {
    var stack = traceback();
    for(var i= 0; i<3;i++)
    {
console.log('Function Name : ' + stack[i].name);
console.log('File Name : ' + stack[i].file);
console.log('Line Number : ' + stack[i].line);
    }
}
a();

The above code will yield an output as :


Share your experience with traceback and how you would like to use it in your application. Please Like and Share the Blog, if you find it interesting and helpful.

2 comments:

  1. This not works :(

    ReplyDelete
    Replies
    1. I would suggest using module callsite instead....

      Delete