In node.js, console is a module that provides a simple debugging console to write or print messages to node.js stream same as JavaScript console mechanism.
Generally, while working in JavaScript we will use a console mechanism to write or print temporary messages in console to know about the functionality of particular action. Same way, in node.js we have a console module to track the functionality of particular action by printing messages at different levels.
In node.js, the console module has exports two specific components, those are
console.log()
, console.error()
and console.warn()
to write messages to node.js stream.stdout
and stderror
properties. In node.js, the global console object can be used in the application without calling require(‘console’)
.Now, we will learn how to use a global console object and Console class in our node.js applications with examples.
Following is the example of using a global console object in node.js applications to write or print messages to node.js stream. To use node.js global console instance, create a new folder wherever you want in your system, and in that create a file called consoleglobal.js and write the code like as shown below.
// It prints welcome to tutlane, to stdout
console.log('Welcome to Tutlane');
// It prints hello world, to stdout
console.log('hello %s', 'world');
// It prints Error: Oops... something went wrong, to stderr
console.error(new Error('Oops... something went wrong'));
// It prints Warning Suresh Dasari!, to stderr
const name = 'Suresh Dasari';
console.warn(`Warning ${name}! Warning!`);
If you observe above code, we are trying to write messages to node.js stream by using global console object methods such as console.log()
, console.error()
and console.warn()
. Here, we are accessing the global console object without importing it using require
directive.
Now, we will execute consoleglobal.js file, for that open a command prompt (cmd) and navigate to the folder that contains a consoleglobal.js file and write a command like node consoleglobal.js
and hit enter button like as shown below.
If you observe the result, we are able to write required messages to node.js stream by using the global console object to track the functionality of any action based on our requirements.
In node.js, the Console class can be used to create a simple logger with configurable output streams and can be accessed by using either require(‘console’).Console
or console.Console
.
Following is the example of using Console class in node.js applications to write or print a messages to node.js stream. To use Console class, create a js file called consoleclass.js and write the code like as shown following.
// create stream in file system
const {createWriteStream} = require('fs');
const out = createWriteStream('./stdout.log');
const err = createWriteStream('./stderr.log');
const logger = new console.Console(out, err);
// It print welcome to tutlane, to out
logger.log('Welcome to Tutlane');
// It print hello world, to out
logger.log('hello %s', 'world');
// It print Error: Oops... something went wrong, to err
logger.error(new Error('Oops... something went wrong'));
// It print Warning Suresh Dasari!, to err
const name = 'Suresh Dasari';
logger.warn(`Warning ${name}! Warning!`);
If you observe above example, we created a simple logger using Console class with configurable output streams and we created a Console class object by using console.Console
.
Now, we will execute a consoleclass.js script file in node.js command prompt by navigating to the folder where it exists like as shown below.
The above node.js example will create a log files (stdout & stderr) in the folder where the consoleclass.js file exists with required messages like as shown below.
This is how we can use the global console object or Console class in node.js applications based on our requirements.
Apart from the above three methods (console.log(), console.error(), console.warn()), few other following methods also available with node.js console object to write or print messages in node.js stream.
Method | Description |
---|---|
console.count() | It is useful to count the number of times the specific label has been called. |
console.clear() | It is useful to clear the console history. |
console.info() | It is useful to write messages to console and it's an alias of console.log() method. |
console.time() | It is used to get the starting time of an action. |
console.timeEnd() | It is used to get the end time of specific action. |
console.dir() | It uses util.inspect() on obj and prints the resulting string to stdout. |
Now, create a js file called consolemethods.js and write the code like as shown following to write a messages to node.js stream using different node.js console methods.
// import http module using require
var http = require('http');
// Creating/establish a server
http.createServer(function (req, res) {
var counter = 50;
console.count("Value of counter is =", counter);
// returns the marking time
console.time('MyTimer');
// Write response as Html(text)
res.writeHead(200, {'Content-Type': 'text/html'});
// Writing static text
res.end('Hello World');
// returns the marking end time
console.timeEnd('MyTimer');
// Server listening on port number 4200
}).listen(4200,
console.info("Server listeing on port 4200")
);
When we execute above consolemethods.js file in node.js command prompt, we will get the result like as shown below.
Now your computer will work as a server so if anyone tries to access your computer with http://localhost:4200 URL then in return, they will get a “Hello world” message like as shown below.
Whenever we hit http://localhost:4200 URL in the browser, the log messages will be written into node.js stream like as shown following in node.js command prompt.
This is how we can use the console module in our node.js applications based on our requirements.