Node.js Console

In node.js, console is a module which provides a simple debugging console to write or print a messages to node.js stream same like JavaScript console mechanism.

 

Generally, while working in JavaScript we will use 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 in different levels.

 

In node.js, the console module has exports two specific components, those are

 

  • A Console class with methods such as console.log(), console.error() and console.warn() to write a messages to node.js stream.
  • A global console instance to write a messages to stdout and stderror properties. In node.js, the global console object can be used in application without calling require(‘console’).

Now, we will learn how to use global console object and Console class in our node.js applications with examples.

Node.js Console Object Example

Following is the example of using 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.

consoleglobal.js

// It print welcome to tutlane, to stdout

console.log('Welcome to Tutlane');

// It print hello world, to stdout

console.log('hello %s', 'world');

// It print Error: Oops... something went wrong, to stderr

console.error(new Error('Oops... something went wrong'));

// It print Warning Suresh Dasari!, to stderr

const name = 'Suresh Dasari';

console.warn(`Warning ${name}! Warning!`);

If you observe above code, we are trying to write a messages to node.js stream by using global console object methods such as console.log(), console.error() and console.warn(). Here, we are accessing 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.

 

Node.js Global Console Object Example Result

 

If you observe result, we are able to write a required messages to node.js stream by using global console object to track the functionality of any action based on our requirements.

Node.js Console Class Example

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.

consoleclass.js

// 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 consoleclass.js script file in node.js command prompt by navigating to the folder where it exists like as shown below.

 

Node.js Console Class Example Result

 

The above node.js example will create a log files (stdout & stderr) in the folder where consoleclass.js file exists with required messages like as shown below.

 

Node.js console class log files in folder

 

This is how we can use global console object or Console class in node.js applications based on our requirements.

Node.js Console Methods

Apart from above three methods (console.log(), console.error(), console.warn()), few other following methods also available with node.js console object to write or print a messages in node.js stream.

 

MethodDescription
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 a 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 use util.inspect() on obj and prints the resulting string to stdout.

Node.js Console Methods Example

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.

consolemethods.js

// 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. 

 

Node.js execute console methods js in command prompt

 

Now your computer will work as 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.

 

Node.js Cosole Methods Example Result

 

Whenever we hit http://localhost:4200 url in browser, the log messages will be written into node.js stream like as shown following in node.js command prompt.

 

Node.js console methods writing log messages to node.js stream

 

This is how we can use console module in our node.js applications based on our requirements.

 

PREVIOUS

Node.js Basics
 

NEXT

Node.js Modules  
 

Topics Covered