Skip to content

Instantly share code, notes, and snippets.

@alator21
Last active November 13, 2018 22:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alator21/b7939a5ccaa27581769a2aea7ad3871a to your computer and use it in GitHub Desktop.
Save alator21/b7939a5ccaa27581769a2aea7ad3871a to your computer and use it in GitHub Desktop.
Node.JS print filename and line number prefixed to console log output
//Inspired by Mike Smullin (https://github.com/mikesmullin)
//Almost same as his gist (https://gist.github.com/mikesmullin/008721d4753d3e0d9a95cda617874736) but this one can print objects too.
//Mike's gist would print [object object] if an object was passed as a parameter.This one displays correctly the object.
const path = require('path');
function p11(s) {
const orig = Error.prepareStackTrace;
Error.prepareStackTrace = (_, stack) => stack;
const err = new Error();
Error.captureStackTrace(err, arguments.callee);
const callee = err.stack[0];
Error.prepareStackTrace = orig;
process.stdout.write(`${path.relative(process.cwd(), callee.getFileName())}:${callee.getLineNumber()}:`);
console.log(s);
}
module.exports = p11;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment