arm1.ru

A simple console.log with file and line number output in Node.js

While coding in Node.js, I constantly need to print something to the console. Errors, for example. But for better information it is more convenient to know exactly where the output is coming from. Especially since when I was coding for iOS, I always had such a handy macro at hand, but with Node.js I had to google and dig around, because many examples from Stack Overflow simply crashed on the latest Node.js 5.10.0. They crashed because they used Error.captureStackTrace(err, arguments.callee), and now you need to use NFE.

In the end I made what I wanted. Leaving it here as a cheat sheet.

npm install colors --save

File logger.js:

'use strict';

let colors = require('colors');
colors.enabled = true;

exports.p = function logger(somethingForPrint) {
    somethingForPrint = somethingForPrint || '';
    const originalPrepareStackTrace = Error.prepareStackTrace;

    Error.prepareStackTrace = (error, stack) => { return stack; };

    let e = new Error;
    Error.captureStackTrace(e, logger);

    const stack = e.stack;
    const filename = stack[0].getFileName().split('/').reverse()[0];
    const trace = filename + ':' + stack[0].getLineNumber() + " " + colors.bold.black('%s') + "\n";

    Error.prepareStackTrace = originalPrepareStackTrace;

    console.log(trace, somethingForPrint);
}; 

Use:

const logger = require('../utils/logger');
logger.p('something happened');
// file.js:401 something happened 
keyboard_return