Extract stacktrace information in Node.js

Node.js is great in many features such as clustering, async and many more but it was really bad in debugging. I got work assignment to invoke e-mail when any error occur in my script and i was wondering to put line number and other debug information in same email.

To do so there were many alternatives and some are painful too, but i figured out this awesome node.js package called “traceback”.

Stacktrace in Node.js

Node.js provides stack information if any particular error occurs, let’s say if any variable is undefined, stacktrace will look like this.

/home/unixroot/Desktop/node-debug/app.js:10
    var stack = new traceback();
                    ^
ReferenceError: traceback is not defined
    at demo.callNext (/home/unixroot/Desktop/node-debug/app.js:10:18)
    at new demo (/home/unixroot/Desktop/node-debug/app.js:5:7)
    at Object.<anonymous> (/home/unixroot/Desktop/node-debug/app.js:14:1)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Function.Module.runMain (module.js:497:10)
    at startup (node.js:119:16)
    at node.js:906:3

But the problem is it is string, you need to write some code to convert it into JSON or you can manipulate it with “Error” object. But why to do extra piece of work when something awesome is already there ! Yeah let’s look into it.

Installation :

You can install it from npm by using

npm install traceback

and add it into your script using

var traceback = require("traceback");

You can use it anywhere in program, wherever you need stack just instantiate traceback.

How to use traceback:

Here is sample snippet to show you how to use this node package.

app.js
//Load the module
var traceback = require("traceback");
//just parent class
function demo() {
        var self = this;
        self.callNext();
}
//inherit one from parent
demo.prototype.callNext = function() {
        var self = this;
        var stack = new traceback();
        //console the trace to know more
        console.log("File Name : " + stack[0].file + "n" + "Method Name : " + stack[0].method);
}

new demo();

Run the app by typing

node app.js

and you may be able to see following output.

File Name : app.js
Method Name : callNext

You can even print line number from where traceback is invoked as a debugging information.

Conclusion:

I am not sure how many of you need it because the problem on which i have worked last week is pretty rare but if you stuck at something where you need every piece of information for particular error to store somewhere or send an email out ! This is right tool for you.

Shahid
Shahid

Founder of Codeforgeek. Technologist. Published Author. Engineer. Content Creator. Teaching Everything I learn!

Articles: 126