Thursday, April 23, 2020

Node.js Console

Node.js Console

nodejs console module


Debugging is the basic purpose of the ‘console’ module in Node.js. It works very much similar to the JavaScript console provided in “in-browser JavaScript”.

The module contains two primary components,

  • The Console class,
    This class provides methods like console.log(), console.error() and console.warn().These methods are applied to write to any Node.js stream.
  • A global console object
    This object is made available for process.stdout and process.stderr. We do not need to require('console') to make the global console instance available. It is used in a synchronous way when the destination is a file or a terminal and in the asynchronous way when the destination is a pipe.

The global console object can be directly used, for example

console.log('Welcome to Node.js');
//Prints: Welcome to Node.js, to stdout
console.log('Welcome to %s', 'Node.js');
//Prints: Welcome to Node.js, to stdout
console.error(new Error('Wait!!!, some error has occured'));
//Prints: [Error: Wait!!!, some error has occured], to stderr

const name = 'Mr. Programmer';
console.warn(`Warning!!! ${name}! Danger!`);

//Prints: Warning!!! Mr. Programmer! Danger!, to stderr

/*
Output:
Welcome to Node.js
Welcome to Node.js
Error: Wait!!!, some error has occured
    at Object.<anonymous> (C:\Users\my\Desktop\brackets\test.js:5:15)
    at Module._compile (internal/modules/cjs/loader.js:1158:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1178:10)
    at Module.load (internal/modules/cjs/loader.js:1002:32)
    at Function.Module._load (internal/modules/cjs/loader.js:901:14)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:74:12)
    at internal/main/run_main_module.js:18:47
Warning!!! Mr. Programmer! Danger!
*/

The Console class

The Console class is configurable with output streams. Simple logger activities can be produced by the Console class. To access this class we can use require(‘console’).

OR

const { Console } = require('console');
const {
Console } = console;

For example,
var fs=require('fs');
var con=require('console').Console;
// Two files stdout.log and stderr will be created
var output = fs.createWriteStream('./stdout.log');
var errorOut = fs.createWriteStream('./stderr.log');
// Custom simple logger
const logger = new con({ stdout: output, stderr: errorOut });
// use it like console
const count = 5;
logger.log('count: %d', count);
// In stdout.log: count 5

Class Console methods


console.assert(value[, ...message])

To verify whether the value is truthy. If it is not, Assertion failed is logged.

console.clear()

If the stdout is TTY, then the clear() method attempts to clear the TTY. Otherwise does nothing.

console.count([label])

Carries an internal counter particular to a label. The output to stdout is the number of times console.count() is executed for that label.

console.countReset([label])

To resets the internal counter for that particular label.

console.debug(data[, ...args])

An alias for console.log().

console.dir(object[, options])

This method applies to util.inspect() method at the object and prints the output string at stdout. custom inspect() functions are bypassed.

console.dirxml(...data)

Eventually invokes console.log() and supplies it the received arguments. No XML formatting produced.

console.error([data][, ...args])

It is used to print to stderr with a newline.

console.group([...label])

Expands the indentation of subsequent lines by two spaces.

console.groupCollapsed()

An alias for console.group().

console.groupEnd()

Reduces the indentation of subsequent lines by two spaces.

console.info([data][, ...args])

An alias for console.log().

console.log([data][, ...args])

Prints to stdout with a newline.

console.table(tabularData[, properties])

Tries to generate a table with the columns of the properties of tabular data (or use properties) and rows of tabular data and log it. Stays to the normal logger process if data can’t be parsed in tabular form.

console.time([label])

This method begins a timer that is used to compute the duration of an operation. Timers are identified by a unique label.

console.timeEnd([label])

Stops a timer started by console.time() method.

console.timeLog([label][, ...data])

Prints the elapsed time and other data arguments to stdout exhausted by console.time() method.

console.trace([message][, ...args])

Prints formatted message and stack trace to the current position in the code.

console.warn([data][, ...args])

An alias for console.error().