Node.js – Console module – A simple debugging console

We have discussed in our previous article “Node.js – Modules – A brief discussion” that, Node.js provides core modules and one of the core modules is the Console module which provides a simple debugging console.

To use the core module functionality, we no need to import the module using require method. Core modules are built-in and an instance of the core module will be created at the global level; hence you can access the object of classes of the core module in your program directly. The global console object is created for a Console class in the Console module and it is configured to write to standard output (stdout) & standard error (stderr) streams.

stdout is a writable stream and stderr is used for error or warning outputs. We can also create our own instance of a Console class (using Console class constructor) with one or two writable stream instances; one is stdout stream and the other one is stderr stream. If stderr is not provided, stdout is used to write error output.

Console class has the methods; log() or info(), error() or warn() methods, used to write to any Node.js streams. These methods we can access using the global object, console. Actually, these methods internally use; process.stdout and process.stderr streams to write the output. process object (it is also a global object) is an instance of Process class which is in the Process module.

We can also use assertions in our code to verify whether the value of expression evaluates the truth value. For example, ensure to have the proper file handle before reading or writing to the file. If the assertion or validation fails, “Assertion failed” is logged. Console class provides, assert() method for a simple assertion test. Please note that this will not interrupt the execution of subsequent code; it simply logs the “Assertion failed” message.

Another interesting method the Console class provides is trace() method. This method is used to prints the call stack (or stack trace) information to the current position in the code. Usually, we need stack trace information, when an error occurred; hence it prints the details to stderr stream.

</> Michael

Node.js – Console module – A simple debugging console

Leave a Reply

Your email address will not be published.

Scroll to top