Node.js new Console() Method
Last Updated :
03 Nov, 2021
The console module provides a simple debugging console that is provided by web browsers which export two specific components:
- A Console class that can be used to write to any Node.js stream. Example: console.log(), console.error(), etc.
- A global console that can be used without importing console. Example: process.stdout, process.stderr, etc.
The new Console() (Added in v8.0.0) method is an inbuilt application programming interface of the 'console' module which creates a new Console with single or multiple writable stream instances in which stdout is a writable stream and stderr is used for warning or error output. If stderr is not provided, stdout is used for stderr. It is a console whose output is sent to process.stdout and process.stderr.
Note: The global console methods are neither consistently synchronous nor consistently asynchronous.
Syntax:
new Console(options);
Arguments:
const options = {
stdout: writableStream,
stderr: writableStream,
ignoreErrors: true,
colorMode:true
};
In order to use this method, we need to create a console using (new Console()) method, and we need to import the ‘console’ and 'fs' module.
const console = require('console');
const fs = require('fs');
Parameters: This function accepts an object/list of parameters as mentioned above and described below:
options <Object>: It may have the following elements in the options object.
- stdout <stream.Writable>: It accepts the write stream which is imported from fs module.
- stderr <stream.Writable>: It also accepts the write stream which is imported from fs module.
- ignoreErrors <boolean>: The default value passed is true. It ignores the errors while writing to the underlying streams.
- colorMode <boolean> | <string>: The default value passed is 'auto'. It is used to set color which supports this Console instance only. It could be set true, false, or 'auto' according to set color mode.
- inspectOptions <Object>: It specifies the options that are passed along to util.inspect() method.
- groupIndentation <number>: The default value set is 2. It is used to set group indentation.
Return Value: Its output is sent to process.stdout and process.stderr files which are created by fs module through <stream.Writable>.
The Below examples illustrate the use of new Console(options) method in Node.js.
Example 1:Â Filename: index.js
javascript
// Node.js program to demonstrate the
// new Console() method
// Using require to access fs module
const fs = require('fs');
// Using require to access console module
const { Console } = require('console');
// Creating write Stream
const output = fs.createWriteStream('./out.log');
const errorOutput = fs.createWriteStream('./err.log');
//
const options = { stdout: output, stderr: errorOutput,
ignoreErrors: true, colorMode: false };
const logger = new Console(options);
const count = 5;
// Using like console
logger.log('count: %d', count);
console.log("Successfully created and logged via console...", )
Run index.js file using the following command:
node index.js
Output:
Note: The above node.js example will create log files (out & err) in the same folder where index.js file exists.
>> Successfully created and logged via console...
Example 2:Â Filename: index.js
javascript
// Node.js program to demonstrate the
// new Console() method
// Using require to access fs module
const fs = require('fs');
// Using require to access console module
const console = require('console');
const { Console } = console;
try {
// Creating write Stream
const output = fs.createWriteStream('./outputlog.txt');
const error = fs.createWriteStream('./errlog.txt');
// Creating new Console
const objLogger = new Console(
{ stdout: output, stderr: error,
ignoreErrors: true, colorMode: true }
);
// Custom write Stream
const outt = fs.createWriteStream('./output.log');
const err = fs.createWriteStream('./error.log');
// Another way to create console
// (default values are passed to options)
const logObject = new console.Console(outt, err);
// Creating family object
var family = {};
family.Head = 'Miss Sanno';
family.headDesignation = 'Teacher';
family.Member1 = 'Miss Sanchi';
family.member1Designation = 'Kid';
family.Member2 = 'Master Amit';
family.member2Designation = 'Student';
// Creating constant value count
const count = 25+75*5-5/2;
// Writing via console
objLogger.log('Family: %s', family);
// Printing Family Object to console
console.log('Family Stream Created: ', family);
// Writing via console
logObject.log('Count: %s', count);
// Printing count to console
console.log('Count Stream Created: ', count);
// console.log(logObject.family.error)
}
catch {
console.error(new Error(
'Oops, some error happened in family...'));
// Prints: [Error: Oops, some error
// happened in family...], to stderr
}
Run index.js file using the following command:
node index.js
Output:
Note: The above node.js example will create log files (output & error) in the same folder where index.js file exists.Â
Family Stream Created: {Â
Head: 'Miss Sanno',Â
headDesignation: 'Teacher',Â
Member1: 'Miss Sanchi',Â
member1Designation: 'Kid',Â
Member2: 'Master Amit',Â
member2Designation: 'Student'Â
}Â
Count Stream Created: Â 397.5Â
Â
Reference: https://nodejs.org/api/console.html#console_new_console_options
Similar Reads
Node.js console.assert() Method
The console.assert() method is an inbuilt application programming interface of the console module which is used to assert value passed to it as a parameter, i.e. it checks whether the value is true or not, and prints an error message, if provided and failed to assert the value. Syntax: console.asse
2 min read
Node.js console.clear() Method
The console.clear() method is used to clear the stdout, when stdout is a TTY (Teletype) i.e. terminal it will attempt to clear the TTY. When stdout is not a TTY, this method does nothing. The console.clear() will work differently across different operating systems and terminal types. For Linux opera
1 min read
Node.js console.count() Method
The console.count() method is an inbuilt application programming interface of the console module which is used to count label passed to it as a parameter, by maintaining an internal counter for that specific label. Syntax: console.count(label) Parameters: This method has one parameter as mentioned a
2 min read
Node.js console.countReset() Method
The console.countReset() method is an inbuilt application programming interface of the console module which is used to reset the count for the specific label passed to it as a parameter. Syntax: console.countReset( label ); Parameters: This method has one parameter as mentioned above and described b
2 min read
Node.js console.debug() Method
The console.debug() method is an inbuilt application programming interface of the console module which is used to print messages to stdout in a newline. Similar to the console.log() method. Syntax: console.debug(data, args); Parameters: This method has two parameters as mentioned above and described
2 min read
Node.js console.dir() Method
The console.dir() method is used to get the list of object properties of a specified object. These object properties also have child objects, from which you can inspect for further information. Syntax: console.dir( object ) Parameters: This method accepts single parameter which holds the object elem
1 min read
Node.js console.error() Function
The console.error() function from the console class of Node.js is used to display an error message on the console. It prints to stderr with a newline. Syntax:Â console.error([data][, ...args]) Parameter: This function can contain multiple parameters. The first parameter is used for the primary messa
1 min read
Node.js console.info() Method
The console.info() method is an inbuilt application programming interface of the console module which is used to print messages to stdout in a newline. It is similar to the console.log() method. Syntax: console.info(data, args); Parameters: This method has two parameters as mentioned above and descr
2 min read
Node.js console.timeLog() Method
The console.timeLog() method is an inbuilt function in Nodejs that is used to display the time for each execution. This function is proved to be effective when used in a loop. Syntax: console.log([label][, ...data]) Parameters: This function accepts two or more parameters. Return Value: This method
1 min read
Node.js console.time() Method
The console.time() method is the console class of Node.js. It is used to starts a timer that is used to compute the time taken by a piece of code or function. The method console.timeEnd() is used to stop the timer and output the elapsed time in milliseconds to stdout. The timer can be accurate to th
3 min read