Node.js Console
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
OR
const { Console } = require('console');
const { Console } = console;
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