Skip to content

Instantly share code, notes, and snippets.

@wrenoud
Last active December 22, 2015 17:59
Show Gist options
  • Save wrenoud/6510325 to your computer and use it in GitHub Desktop.
Save wrenoud/6510325 to your computer and use it in GitHub Desktop.
Used to print debug message in node.js that include filename and line number.
// Modified from code found in the following stackoverflow answer:
// http://stackoverflow.com/questions/14172455/get-name-and-line-of-calling-function-in-node-js
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();
}
});
Object.defineProperty(global, '__parent_line', {
get: function(){
return __stack[2].getLineNumber();
}
});
Object.defineProperty(global, '__filename', {
get: function(){
return __stack[1].getFileName();
}
});
Object.defineProperty(global, '__parent_filename', {
get: function(){
return __stack[2].getFileName();
}
});
Object.defineProperty(global, '__parent_function', {
get: function(){
return __stack[2].getFunctionName();
}
});
var debug = function(msg, obj){
var cwd = process.cwd();
var filename = __parent_filename.slice(cwd.length + 1); // plus one to trim leading slash
var title = "" + filename + ":" + __parent_line + " ";
console.log();
console.log("__ " + title + " " + new Array( 76-title.length ).join( '_' ));
if(typeof msg == 'string') console.log(msg);
else console.log(util.inspect(msg, {colors: true, depth: 2}));
if(obj) console.log(util.inspect(obj, {colors: true, depth: 2}));
}
module.exports = debug;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment