Node.js Console Example


The console module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers.

The module exports two specific components:
  • A Console class with methods such as console.log(), console.error() and console.warn() that can be used to write to any Node.js stream.
  • A global console instance configured to write to stdout and stderr. Because this object is global, it can be used without calling require('console').
Example using the global console:
console.log('hello world');
  // Prints: hello world, to stdout
console.log('hello %s', 'world');
  // Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
  // Prints: [Error: Whoops, something bad happened], to stderr

const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
  // Prints: Danger Will Robinson! Danger!, to stderr

Example using the Console class:
const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);

myConsole.log('hello world');
  // Prints: hello world, to out
myConsole.log('hello %s', 'world');
  // Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
  // Prints: [Error: Whoops, something bad happened], to err

const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
  // Prints: Danger Will Robinson! Danger!, to err

While the API for the Console class is designed fundamentally around the browser console object, the Console in Node.js is not intended to duplicate the browser's functionality exactly.

Console log level

  • console.info([data][, ...]): The console.info() function is an alias for console.log().
  • console.error([data][, ...]): Prints to stderr with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to printf(3) (the arguments are all passed to util.format()).
  • console.log([data][, ...]): Prints to stdout with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to printf(3) (the arguments are all passed to util.format()).
  • console.trace(message[, ...]): Prints to stderr the string 'Trace :', followed by the util.format() formatted message and stack trace to the current position in the code.
  • console.warn([data][, ...]): The console.warn() function is an alias for console.error().

Other than levels we have one more console method to find out the execution time.

console.time(label): Starts a timer that can be used to compute the duration of an operation. Timers are identified by a unique label. Use the same label when you call console.timeEnd() to stop the timer and output the elapsed time in milliseconds to stdout. Timer durations are accurate to the sub-millisecond.

console.timeEnd(label): Stops a timer that was previously started by calling console.time() and prints the result to stdout.

console.time('100-elements');
for (var i = 0; i < 100; i++) {
  ;
}
console.timeEnd('100-elements');
// prints 100-elements: 225.438ms

Note: As of Node.js v6.0.0, console.timeEnd() deletes the timer to avoid leaking it. On older versions, the timer persisted. This allowed console.timeEnd() to be called multiple times for the same label. This functionality was unintended and is no longer supported.

How to capture the logs in File using NodeJs Console

require('console');

const Console = require('console').Console;
const fs = require('fs');
const output = fs.createWriteStream('./stdout.log');
const errorOutput = fs.createWriteStream('./stderr.log');
// custom simple logger
const logger = new Console(output, errorOutput);
// use it like console
var count = 5;
logger.log('count: %d', count);

Asynchronous vs Synchronous Consoles

The console functions are usually asynchronous unless the destination is a file. Disks are fast and operating systems normally employ write-back caching; it should be a very rare occurrence indeed that a write blocks, but it is possible.

Additionally, console functions are blocking when outputting to TTYs (terminals) on OS X as a workaround for the OS's very small, 1kb buffer size. This is to prevent interleaving between stdout and stderr.