Open In App

Node.js Utility Module

Last Updated : 09 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

The util module in Node.js provides a variety of utility functions that assist with tasks such as debugging, formatting, and inheritance. It includes methods for inspecting objects, formatting strings, and extending classes.

Node.js Utility Module

The util module offers essential utilities that are not included in other core modules. It enhances the functionality and flexibility of Node.js applications by providing tools for more effective programming and debugging. 

Syntax:

const util = require('util');

Example:

JavaScript
// Import util module
const util = require('util');

// Format a string
const formattedString = util.format('Hello %s!', 'world');
console.log(formattedString); // Output: Hello world!

// Inspect an object
const obj = { name: 'John', age: 30 };
console.log(util.inspect(obj, { showHidden: false, depth: null }));

Output
Hello world!
{ name: 'John', age: 30 }

Explore this Node.js Utility Module Complete Reference for concise explanations, advanced examples, and tips on mastering its features like object inspection, string formatting, and promisification to enhance your Node.js development.

There are various utility modules available in the node.js module library. The modules are extremely useful in developing node-based web applications. Various utility modules present in node.js are as follows:

 OS Module:

Operating System-based utility modules for node.js are provided by the OS module. 

Syntax:

const os = require('os');

Example: 

JavaScript
// Require operating System module
const os = require("os");

// Display operating System type
console.log('Operating System type : ' + os.type());

// Display operating System platform
console.log('platform : ' + os.platform());

// Display total memory
console.log('total memory : ' + os.totalmem() + " bytes.");

// Display available memory
console.log('Available memory : ' + os.availmem() + " bytes.");

Output: Path Module:

The path module in node.js is used for transforming and handling various file paths. 

Syntax:

const path = require('path');

Example: 

JavaScript
// Require path
const path = require('path');

// Display Resolve
console.log('resolve:' + path.resolve('paths.js'));

// Display Extension
console.log('extension:' + path.extname('paths.js'));

Output
resolve:/home/guest/sandbox/paths.js
extension:.js

Output: DNS Module:

DNS Module enables us to use the underlying Operating System name resolution functionalities. The actual DNS lookup is also performed by the DNS Module. This DNS Module provides an asynchronous network wrapper. The DNS Module can be imported using the below syntax. 

Syntax:

const dns = require('dns');

Example: 

JavaScript
// Require dns module
const dns = require('dns');

// Store the web address
const website = 'www.geeksforgeeks.org';

// Call lookup function of DNS
dns.lookup(website, (err, address, family) => {
    console.log('Address of %s is %j family: IPv%s',
        website, address, family);
});

Output
Address of www.geeksforgeeks.org is "3.163.24.37" family: IPv4

Output:

Address of www.geeksforgeeks.org is "203.92.39.72"
family: IPv4

Net Module

Net Module in node.js is used for the creation of both client and server. Similar to DNS Module this module also provides an asynchronous network wrapper. 

Syntax:

const net = require('net');

Example: This example contains the code for the server side. 

JavaScript
// Require net module
const net = require('net');

const server = net.createServer(function (connection) {
    console.log('client connected'); connection.on('end', function () {
        console.log('client disconnected');
    });
    connection.write('Hello World!\r\n'); connection.pipe(connection);
});

server.listen(8080, function () {
    console.log('server listening');
});

Output:

Server listening

Example: This example is containing the client side in the net Module. 

JavaScript
const net = require('net');

const client = net.connect(8124, function () {
    console.log('Client Connected');
    client.write('GeeksforGeeks\r\n');
});

client.on('data', function (data) {
    console.log(data.toString());
    client.end();
});

client.on('end', function () {
    console.log('Server Disconnected');
});

Output:

Client Connected 
GeeksforGeeks
Server Disconnected

Domain Module:

The domain module in node.js is used to intercept unhandled errors. The interception can be performed by either:

  • Internal Binding: Error emitter executes the code internally within the run method of a domain.
  • External Binding: Error emitter is added explicitly to the domain using the add method.

Syntax:

const domain = require('domain');

The domain class in the domain module provides a mechanism for routing the unhandled exceptions and errors to the active domain object. It is considered to be the child class of EventEmitter. 

Syntax:

const domain = require('domain');
const child = domain.create();

Example: 

JavaScript
const EventEmitter = require("events").EventEmitter;
const domain = require("domain");
const emit_a = new EventEmitter();
const dom_a = domain.create();

dom_a.on('error', function (err) {
    console.log("Error handled by dom_a (" + err.message + ")");
});

dom_a.add(emit_a);
emit_a.on('error', function (err) {
    console.log("listener handled this error (" + err.message + ")");
});

emit_a.emit('error', new Error('Listener handles this'));
emit_a.removeAllListeners('error');
emit_a.emit('error', new Error('Dom_a handles this'));
const dom_b = domain.create();

dom_b.on('error', function (err) {
    console.log("Error handled by dom_b (" + err.message + ")");
});

dom_b.run(function () {
    const emit_b = new EventEmitter();
    emit_b.emit('error', new Error('Dom_b handles this'));
});

dom_a.remove(emit_a);
emit_a.emit('error', new Error('Exception message...!'));

Output:

Benefits

  • Enhanced Debugging: Provides powerful tools for inspecting and debugging objects.
  • Simplified Async Handling: Makes it easier to work with asynchronous code by converting callback-based APIs to promise-based ones.
  • Flexible String Formatting: Allows dynamic and customizable string formatting.

Summary

The util module is an indispensable part of Node.js, offering a suite of utilities that simplify development tasks, enhance debugging capabilities, and make asynchronous programming more manageable. Whether you’re handling strings, objects, or asynchronous operations, util provides the tools needed to streamline your Node.js applications.



Similar Reads