web-development top banner

Playing With Nodejs Console

Read it in 10 Mins

Last updated on
31st Dec, 2021
Published
31st Dec, 2021
Views
9,573
Playing With Nodejs Console

Node.js is FUN

Many of the readers might already aware/heard of Node.js but for ones who wanted to get a quick refresher of Node.js, following along. 

Node.js is associated with the following words: 

  • Open-Source and Cross-platform JavaScript runtime environment. 
  • Runs V8 JavaScript engine – core of google chrome. 
  • Is a single process but supports async I/O primitives. 
  • Helps in building applications which very performant and scalable. 
  • Handles thousands of concurrent connections with single server 
  • Helps in transiting front-end developers to back-end with ease. 
  • Supports ECMAScript standards. 
  • Support For Real-Time Applications. 
  • Unified Database Queries. 
  • Easy & Fast Coding i.e., Fast Development Cycle 
  • And many more. 

Shorter definition of Node.js is - it is an open-sourcecross-platform JavaScript run-time environment (Google Chrome's V8 Engine) that executes JavaScript code outside of a browser. Let’s developers use JavaScript to write command line tools and for server-side scripting—running scripts server-side to produce dynamic web page content before the page is sent to the user's web browser. 

Usage of NodeJS

Node.js is majorly used for the following scenarios: 

  • Backend and Servers  
  • Microservices 
  • Development of API 
  • Front end 
  • Script and automation 

With all the advantages mentioned, Node.js is great in prototyping and agile developments, building superfast and highly scalable services. Are there any real time users who gained from Node.js? Yes, in fact there are hundreds of companies using and few to mention are 

  • Netflix heavily uses data streaming which is complex and requires uninterrupted streaming of data by different devices and sources. 
  • In wireless connectivity, one of the major challenges is bandwidth consumption. A reliable source that collects data and sends it to the rightful destination can be a challenge. GoDaddy use node.js for building their back-end infrastructure to increase its uptime and provide a non-blocking service handling multiple requests. 
  • Ebay is using node.js for pushing and to collect real-time data. 
  • Walmart is another company which uses node.js heavily. 
  • Infact, paypal has rebuild one of their applications in node.js which improved their efficiency with 33% fewer lines of code and 2X request/sec & 35% faster response time. 

May be now with the proven record of node.js usage, is everyone using it for the above advantages majorly or there are any other simple command line apps and utilities? Yes, there are many and let’s list down few of them which might be useful in day-to-day work. 

Pre-requisites:

  • Create a folder by name ConsoleModuleExamples. 
  • Navigate to the folder in the terminal and create a node project as described below: 
  • Enter the command `npm init`. 
  • Expect few details to fill like PackageName etc, go with defaults wherever possible.  
  • For other inputs, fill the required data. 
  • On prompt, if everything is Okay. Enter yes to confirm. 
  • Package.json file should be created with main pointing to index.js file. 
{ 
  "name": "consolemoduleexamples", 
  "version": "1.0.0", 
  "description": "", 
  "main": "index.js", 
  "scripts": { 
    "test": "echo \"Error: no test specified\" && exit 1" 
  }, 
  “type”: “module”, 
  "author": "", 
  "license": "ISC" 
} 
  • Create an index.js file and add the below content. 

console.log('Hello world'); 

  • Run node index.js to see the ‘Hello world’ response in terminal. 

Note: For the below examples, make sure to install the specific module before running the example like npm install npm-name. Also, if there is a warning related to ES module, set "type": "module" in the package.json or use the .mjs extension. 

List of Command Line Apps more often used

  • npm-name' is used for checking if there is any package available in npm or not.  
    • Copy the below code and replace the content in index.js. 
    • Run node index.js in terminal. 
import npmName from 'npm-name'; 
// Check a package name 
console.log(await npmName('npm-name')); // returns false 
// Check an organization name 
console.log(await npmName('@consolemoduleexamples')); // returns true 
  • 'Speed-test’ is used for testing internet connection and ping via speedtest.net website but from command line interface. 
  • ‘ESLint’ is for linting – a node.js command line app 
  • 'cpy’ is another simple command line app for copying files in a fast and user friendly manner. 
import cpy from 'cpy'; 
await cpy(['src/*.png''!src/liger.png'], 'dist'); 
console.log('files copied successfully!'); 

Note: To verify this code, make sure to create two folders inside the project with name src and dist. With src containing files namely tiger.png, lion.png and liger.png. Post execution, tiger.png and lion.png files should be copied to dist as shown below. 

Playing With Nodejs Console

  • empty-trash’ for cleaning up the Trash. 

import emptyTrash from 'empty-trash'; 
await emptyTrash(); 
console.log('Trash cleaned!'); 
  • ‘http-server’ that is powerful to serve static files. Also useful for learning, testing and local development. 
  • ‘jsinspect’ is another command line app for maintaing code quality without duplicate code. Also helps in extracting boilerplate or logical snippet of code. 
  • ‘browser-run’ helps in running automation test suites within the environment of our browser. 
  • ‘wifi-password’ - people like me who forget passwords can use this to figure out the password. Very handy
import wifiPassword from 'wifi-password'; 
const password = await wifiPassword(); 
console.log(password); 

Note: When executing this code, OS will request for access permissions. 

  • And many more... 

List of Command Line utilities more often used

  • get-stdin’ - this utility helps in simplifying work with stdin by getting it as a string or buffer. 

 import getStdin from 'get-stdin'; 
const str = await getStdin(); 
console.log(str); 
  • 'Chalk’ is a string styling utility for clean, focused and alternative to colors.js by eliminating some common problems with colors.js. 
  • ‘update-notifier’ is a utility tool tonotify the updates of the dependent packages in a non-intrusive way. 
  • ’configstore’ is used for loading and persisting configurations. 
  • ‘figures’ helps in getting unicode symbols with windows CMD fallbacks. 
  • ‘string-width’ helps in identifying the string width in different languages. Helps in validating. 
import stringWidth from 'string-width';  
console.log(stringWidth('平仮名')); // 6  
console.log(stringWidth('a')); // 1 
  • 'cli-table’ helps in displaying the data in table format with customizable characters, background styling, column width customization etc. 
  • ‘multispinner’ is one of the tools majorly used in displaying the progress of multiple actions with each one controlled separately but executed simultaneously.

Playing With Nodejs Console

  • ‘ansi-escapers’ is used for ANSI escape codes in the terminal and simplifies our daily work. 
  • And many more... 

With Node.js, we can build and use lot of command line apps and utilities which can make us productive and its lot fun to work with them.

Console Module

Node.js comes up with lot of global objects in global namespace which are available in all modules. Few to name are Console, global, process etc and we would be covering in detail about one such module called Console.  

Node.js version comes up with two version one is Console class and another is global console instance which is pre-configured to process.stdout and process.stderr. 

NoteConsole object is similar javascript console mechanism provided by web browsers. But they are not consistently synchronous like browser APs and at same time they are not asynchronous like node.js streams. They depend on the system I.e. Windows or POSIX. Reference - https://nodejs.org/api/process.html#a-note-on-process-io. 

Few of the methods available in console are captured below in browser console window: 

Playing With Nodejs Console

Below is an example of global console object which can be used in a node file (index.js in previous examples): 

console.log('hello world'); 
// Prints: hello world, to stdout as we are using the global console 
console.log('hello %s''world'); 
// Prints: hello world, to stdout with an argument 
const greeting = 'hello'; 
console.log(`${greeting} world`); 
// Prints: hello world, to stdout with an external variable 
console.warn(`Warning! Invalid format.`); 
// Prints the warning message in warning color 
console.info('Info - Logged info successfully.') 
// Prints the info, similar to log. 
console.error('Error occured while processing.'); 
// Print the error with the given error message. 

Console Instance instead of global Console

Similar to global console object, we can create the instance of Console class and log the same information. (replace below content in index.js file) 

import { stdinstdout } from 'process'; 
const myConsole = new console.Console(stdoutstdin); 
myConsole.log('hello world'); 
// Prints: hello world, to stdout as we are using the global console 
myConsole.log('hello %s''world'); 
// Prints: hello world, to stdout with an argument 
const greeting = 'hello'; 
myConsole.log(`${greeting} world`); 
// Prints: hello world, to stdout with a external variable 

The global console and the new console instance use the same output i.e., process.stdout and process.stderr. In case if you are wondering why we have two approaches then here is the reason. 

Console instance with different stream instance other than default

The parameters passed to the Console class we have one or two writable stream instances. First argument stdout is used by log or info methods and the second argument stderr is used for warning or error output. And more importantly we can configure the stream to be other stream instance like file system as shown below. 

Steps: 

  • Hope we are in sample folder consolemodules in terminal. 
  • Install fs module using npm i.e., npm install fs 
  • Copy the below snippet of code to index.js file. 
  • Run node index.js from terminal. 
  • Post execution, there should be two files created with names stdout.log and stderr.log containing log and warn message respectively. 
import fs from 'fs'; 
const output = fs.createWriteStream('./stdout.log'); 
const errorOutput = fs.createWriteStream('./stderr.log'); 
// Custom simple logger 
const logger = new console.Console({ stdout: outputstderr: errorOutput }); 
// use it like console 
logger.log('hello world'); 
// it is written to stdout.log file 
logger.warn('Warning message'); 
// it is written to stderr.log file 

Note: Debug, Info are alias for log method whereas warn is an alias for error method. Internally they use the util.format() for formatting the message. 

Overview of API’s 

Method(s): time, timeLog and timeEnd. 

Console module is associated with timer to compute the duration of an operation. It exposes the below methods: 

  • time – takes a label to which the timer to be associated. 
  • timeEnd – takes a label which is used for time method as well to end the timer. 
  • timeLog – takes a label which is used for time method and prints the elapsed time and additional data. 

Example - Replace the content of index.js with below code and execute node index.js in terminal: 

console.time('process'); // starts the timer and associate with label process. 
const value = 42// imagine a expensive operation. 
console.timeLog('process'value); 
// prints the time elapsed. 
console.timeEnd('process'); 
// prints the total time taken from call to time to timeEnd. 

Method(s): group, groupCollapsed and groupEnd. 

Another set of methods related to indentation are group, groupCollapsed(alias of group) and groupEnd. 

Below is a snap in browser console. 

Playing With Nodejs Console

Method(s): count 

Console maintains an internal counter based on label to count with count method. And for resetting the counter there is another method countReset. 

Below is a snap in browser console. 

Playing With Nodejs Console

Method(s): dir 

To log information to a stdout, we can use log method but to capture the entire object and display an interactive list of properties we can rely on ‘console.dir’. 

Below is a snap in browser console. 

Playing With Nodejs Console

Method(s): table 

Another useful method to display the array of objects in tabular form is ‘console.table’ with an optional argument of properties to be displayed in tabular form. 

Below is a snap in browser console. 

Playing With Nodejs Console

Building a Custom logger with file stream H2 

  • Install fs and util modules using npm if they aren’t installed. (Continuation of previous examples) 
  • Replace the content of index.js file with the below example code. 
  • Execute node index.js to see the logger working. 
  • Post-execution, stdout.log should contain all the logs as shown below in output section with color coding. 

Custom logger built using file stream: 

import util from 'util'; 
import fs from 'fs'; 
 
const output = fs.createWriteStream('./stdout.log');  
const errorOutput = fs.createWriteStream('./stderr.log');  
 
// Simple logger  
const logger = new console.Console({stdout: output,  
stderr: errorOutput,  
inspectOptions: {  
// Maximum number of Array elements to include when formatting.  
maxArrayLength: 3,  
// Maximum number of characters to include when formatting.  
maxStringLength: 10,  
// If properties of an object are sorted  
sorted: true,  
// Remember to enable the color mode. Default is false.  
colors: true  
}}  
);  
// display first 10 characters  
logger.log('log: object', {attr: 'string content a b c d e f g h i j k'});  
// log: object { attr: ‘string content a b c’… 16 more characters }  
 
// display first 3 items  
logger.log('log: array', ['array_value1''array_value2''array_value3''array_value4''array_value5']);  
// log: array [ ‘array_value1’, ‘array_value2’, ‘array_value3’, … 2 more items ]  
// sorted array is displayed  
logger.log('log: set'new Set([31254]));  
// log: set Set(5) { 1, 2, 3, 4, 5 }  
 
// number styling is changed to blue  
util.inspect.styles.number = 'blue';  
// numbers are shown in blue  
 
logger.log('log: set'new Set([3010205040]));  
// log: set Set { 10, 20, 30, 40, 50 } 

Output:

Playing With Nodejs Console

All the things one can do with NodeJS 

The Console class can be used to create a logger with configurable output streams and for the basic usage we can rely on the global console which has predefined configuration of Process.stdin and process.stderr.  

Based on the configurable output stream and the platform, they can be synchronous or asynchronous which helps the processing/logging to be offloaded. 

Profile

Sumanth Reddy

Author

Full stack,UI Architect having 14+ Years of experience in web, desktop and mobile application development with strong Javascript/.Net programming skills .Strong experience in microsoft tech stack and Certified in OCI associate. Go-to-guy on integration of applications, building a mobile app by zeroing on tech stack. Majorily experienced on engineering based IIOT products and Marekting Automation products deployed on premise and on-cloud.