A Deep Dive into Console

Learn via video courses
Topics Covered

Overview

Console module in nodejs plays an important role in understanding the source code and debugging the application. Console module provides us with different methods for debugging similar to chrome dev tools. In this post, we will look deep into the console class in nodejs and its methods to see how to use them.

Introduction

The system console, computer console, operator console, or root console is the text entry and display device for system administration messages from the kernel or init system or the system logger. System consoles are generic to computer terminals, which are abstracted by terminal emulators and virtual consoles. Nowadays, contact with system consoles is generally done via the standard streams ( stdout, stdin, and stderr ); also, there can be system-specific interfaces.

The console is considerably most widely used in web development, starting from the basic HTML and CSS debugging in the browser to the console in Node js and v8’s d8 shell. The console is mainly used for debugging, like alert in the browser. Everyone has used alert during the start of their web development phase.

Difference between console in Nodejs and console in browser :

Browser consoleNodejs console
Browser has a predefined global object, windows that contains functions and attributes.Node has global which is a predefined global object that contains server-side functions.
Browser also has require is not pre-defined.In Nodejs require is pre-defined.
Location is also a pre-defined object in a browser that has info about urls.Node js doesn't have a location object

Example :

Output :

Node.js Console

Logging is one of the most crucial parts of understanding the entire life cycle of the node.js application. Starting from scratch to adding new features and debugging the errors, logs provide support by analyzing the data and also detecting the errors at a very early stage. The console module in node js provides a simple debugging console that is identical to the javascript console tool provided by web browsers like google chrome.

The Console Module in Node Js Exports Two Specific Components :

  • A console class that has methods like console.error(), console.log(), console.clear() and console.warn() that are used o write to any Node js streams.
  • A global console instance that is configured to write to process.stderr and process.stdout. The global console can be used without using the require method. require('node:console')

Example of console class :

Output :

Example of the global console :

Output :

Note :
The methods provided by the global console instance are neither consistently asynchronous like all Node.js streams, nor are they consistently synchronous like the browser APIs they resemble.

Advantages of Console in Node Js

  • The console helps in debugging an application.
  • The console helps in understanding the application source code working.
  • The console is initialized with a stream that helps in interacting and printing different messages to the users.

Console Class

The console class in node js can be used to create a simple logger with configurable output streams. Node.js gives a convenient setting to display the console logs. Nonetheless, you may want to modify these settings to fit your need without having to install any additional packages.

They can be accessed using either following ways :

In general, the console class is defined like this :

Description :

  • options : <Object>
    • stderr : <stream.Writable>
    • stdout : <stream.Writable>
    • ignoreErrors : <boolean> Defaut value is true. It Ignores errors when writing to the underlying streams.
    • colorMode : <boolean> | <string> Used to set color support for this Console instance. Setting colorMode to true enables coloring while inspecting and setting colorMode to false disables coloring. The default value is auto, which makes color support depend on the value of the isTTY property and the value by getColorDepth().
    • inspectOptions : <Object> Used to specify options that are passed along to util.inspect().
    • groupIndentation : <number> Used to set group indentation. The default value is two.

We simply write console.log to log simple things without importing any Console library or anything. It is just because the console instance has been initialized and is present in the process object. The console in node js is also initialized with a stream pointing to the terminal so that we can print to our terminal.

process.stderr is utilized for printing error messages to the screen, and process.stdout is utilized for printing to the screen in Nodejs. If stderr is not provided, stdout is used for stderr.

In the console API,

The first argument implies the stream where we want to print out logs, and this stream can either be a terminal or a file.

The process.stdout is a node js process object that is used to print to the screen. It is used below.

Output :

The write(...) method of process.stdout is called with the params containing what we want to print to the screen.

This is passed to the Console class in the following way :

And then, in the console class, it is implemented like this :

Explanation :

When we pass in process.stdout to Console (new Console(process.stdout)), its write method will be called in the Console.prototype.write method to print the params contained in whatToWrite to the screen.

Example :

Output :

Explanation :

  1. process.stdout is set to this.stdout in the console.
  2. On calling log.log with Hello Node js, whatToWrite becomes Hello Node js and this.write is called.
  3. In the write method, the parameter whatToWrite is Hello Node js and the stream becomes process.stdout.
  4. So stream.write(WhatToWrite) becomes process.stdout.write(“Hello Node js”)
  5. Output is printed on the terminal.

A file stream can be printed too. Let’s suppose we have a file we want to log our output to.

Example :

Output :

Global Console Class

The global console is a unique Console whose output is dispatched to process.stderr and process.stdout.

It is equivalent to calling :

Example :
Let us create a file with name console_global.js with the following code :

If you observe the above code, we are trying to print to node js streams using global console instance methods such as console.log(), console.error() and console.warn().

Here we can access the global console instance without importing or installing the global console instance through any other external packages.

Now, let us execute the above file. Open the command prompt and navigate to the directory that contains the console_global.js file. Now write the following command,

Output :

Console Methods

1. console.log() :

This function is provided by the console class of Node js and is generally used to print a message to the screen. This method uses stdout to display the message with a new line.

Syntax :

Description of the parameters :

  • data : <any>
  • ...args : <any> The parameters that need to be printed.
  • Return type : The function returns the passed parameters.

Example :

Output :

2. console.error() :

This function is provided by the console class of Node js and performs the same as .log() except that the output is sent to the stderr pipe instead of stdout. This function is used to print the errors in the terminal with a new line. The stderr is always written synchronously, which means the use of console.error() in node js will stop your process until the output has been written. Hence extreme use of console.error() can slow down the process significantly.

Syntax :

Description of the parameters :

  • data : <any>
  • ...args : <any> Numerous arguments can be passed to this function, with the first used as the immediate message and all other arguments used as substitution values.
  • Return type : The function returns the error message.

Example :

Output :

3. console.warn() :

This function is provided by the console class of Node js and is used to print warning messages to the terminal or console. This function prints to stderr with a newline. This function is also an alias for the console.error().

Syntax :

Description of the parameters :

  • data : <any>
  • ...args : <any> Numerous arguments can be passed to this function, with the first used as the immediate message and all other arguments used as substitution values.
  • Return type : The function returns the warning message.

Example :

Output :

4. console.count() :

This function is provided by the console class of Node js and is used to set the number of times a string tag/label is called. This function maintains an internal counter specific to the passed string tag/label and outputs to stdout the number of times that string is called with this method.

Syntax :

Description of the parameters :

  • label : <label> It is an optional parameter specified to the string label. The default value is a string default.
  • Return type : The function returns the count of this function called with the specified string label to the stdout.

Example :

Output :

Now if we pass the same string multiple times,

Example :

Output :

5. console.clear()

This function is provided by the console class of Node js and is used to clear your terminal. In case you have too many messages in your terminal, you can run console.clear() to remove those messages. When the stdout is a Teletype (TTY) that is a terminal, it will clear the TTY. When it is not a (TTY), this method does nothing.

The specific function of console.clear() can range across operating systems and terminal types. It is similar to running the cls command in Windows command prompt and clear in bash.

Syntax :

This function does not accept any arguments.

Example :

Output :

6. console.info()

This function is provided by the console class of Node js and is the same as console.log(). This method uses stdout to display the message with a new line.

Syntax :

Description of the parameters :

  • data : <any>
  • ...args : <any> The parameters that need to be printed.
  • Return type : The function returns the passed parameters.

Example :

Output :

7. console.time()

This function is provided by the console class of Node js and is used to start a timer which is used to compute the duration of a piece of code or function. Each timer must have unique labels. When the same label is used to call console.timeEnd(), it prints the duration of time that has passed since the process started. The timer can be correct to the sub-millisecond of code or function.

Syntax :

Description of the parameters :

  • label : <string> This function accepts a single parameter label. The default value is a string default.

Example :

Output :

8. console.timeEnd()

This function is provided by the console class of Node js and is used to stop the timer and output the elapsed time in milliseconds.

Syntax :

Description of the parameters :

  • label : <string> This function accepts a single parameter label. The default value is a string default.

Example :

Output :

Conclusion

  • System consoles are generic to computer terminals, which are abstracted by terminal emulators and virtual consoles.
  • The console module in node js exports two modules, which are the console class and global class instance.
  • The global console is a unique Console whose output is dispatched to process.stderr and process.stdout.
  • The console class in node js can be used to create a simple logger with configurable output streams.
  • Console class provides us with .log(), .error(), .warn(), .time() like methods.
  • console.log() is similar to console.log() and console.error() is similar to console.warn().
  • The stderr is always written synchronously which means it blocks the flow of code.
  • The console helps in debugging and understanding the source code of an application.
  • console.time() and console.timeEnd() are used to compute the duration of a piece of code or function.