Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • Software and Tools
    • School Learning
    • Practice Coding Problems
  • Go Premium
  • NodeJS Tutorial
  • NodeJS Exercises
  • NodeJS Assert
  • NodeJS Buffer
  • NodeJS Console
  • NodeJS Crypto
  • NodeJS DNS
  • NodeJS File System
  • NodeJS Globals
  • NodeJS HTTP
  • NodeJS HTTP2
  • NodeJS OS
  • NodeJS Path
  • NodeJS Process
  • NodeJS Query String
  • NodeJS Stream
  • NodeJS String Decoder
  • NodeJS Timers
  • NodeJS URL
  • NodeJS Interview Questions
  • NodeJS Questions
  • Web Technology
Open In App
Next Article:
Node.js util.callbackify() Method
Next article icon

Node.js Utility Module

Last Updated : 12 Jul, 2025
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.


Next Article
Node.js util.callbackify() Method

R

Ranzz
Improve
Article Tags :
  • Web Technologies
  • Node.js
  • Node.js-Basics

Similar Reads

    Node.js Utility Module
    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 ModuleThe util module offers essential utilities that are n
    4 min read
    Node.js util.callbackify() Method
    The util.callbackify() method is an inbuilt application programming interface of the util module which is used to run an asynchronous function and get a callback in the node.js.Syntax:   util.callbackify( async_function ) Parameters: This method accepts single parameter as mentioned above and descri
    2 min read
    Node.js util.debuglog() Method
    The “util” module provides ‘utility’ functions that are used for debugging purposes. For accessing those functions we need to call them (by ‘require(‘util’)‘). The util.debuglog() (Added in v0.11.3) method is an inbuilt application programming interface of the util module which is used to create a f
    3 min read
    Node.js util.format() Method
    The util.format() (Added in v0.5.3) method is an inbuilt application programming interface of the util module which is like printf format string and returns a formatted string using the first argument. The formatted string contains zero or more format specifiers in which the corresponding argument v
    5 min read
    Node.js util.inherits() Method
    The “util” module provides ‘utility’ functions that are used for debugging purposes. For accessing those functions we need to call them (by ‘require(‘util’)‘). The util.inherits() (Added in v0.3.0) method is an inbuilt application programming interface of the util module in which the constructor inh
    3 min read
    Node.js util.formatWithOptions() Method
    The util.formatWithOptions() (Added in v10.0.0) method is an inbuilt application programming interface of the util module which is like printf format string and returns a formatted string using the first argument. It is somewhat identical to util.format() method, the exception in this method is that
    4 min read
    Node.js util.inspect() Method
    The "util" module provides 'utility' functions that are used for debugging purposes. For accessing those functions we need to call them by 'require('util')'. The util.inspect() (Added in v0.3.0) method is an inbuilt application programming interface of the util module which is intended for debugging
    7 min read
    Node util.promisify() Method
    `util.promisify()` in Node.js converts callback-based methods to promise-based, aiding in managing asynchronous code more cleanly. This alleviates callback nesting issues, enhancing code readability, and simplifying asynchronous operations through promise chaining.Syntax:util.promisify(func)Paramete
    2 min read
    Node.js util.isDeepStrictEqual() Method
    The "util" module provides 'utility' functions that are used for debugging purposes. For accessing those functions we need to call them (by 'require('util')'). The util.isDeepStrictEqual() (Added in v9.0.0) method is an inbuilt application programming interface of the util module which is an exporte
    3 min read
    Node.js util.deprecate() Method
    The util.deprecate() (Added in v0.8.0_ method is an inbuilt application programming interface of the util module which wraps fn (which may be a function or class) in such a way that it is marked as deprecated. When util.deprecate() method is called, it returns a function that emits a DeprecationWarn
    3 min read
`; $(commentSectionTemplate).insertBefore(".article--recommended"); } loadComments(); }); }); function loadComments() { if ($("iframe[id*='discuss-iframe']").length top_of_element && top_of_screen articleRecommendedTop && top_of_screen articleRecommendedBottom)) { if (!isfollowingApiCall) { isfollowingApiCall = true; setTimeout(function(){ if (loginData && loginData.isLoggedIn) { if (loginData.userName !== $('#followAuthor').val()) { is_following(); } else { $('.profileCard-profile-picture').css('background-color', '#E7E7E7'); } } else { $('.follow-btn').removeClass('hideIt'); } }, 3000); } } }); } $(".accordion-header").click(function() { var arrowIcon = $(this).find('.bottom-arrow-icon'); arrowIcon.toggleClass('rotate180'); }); }); window.isReportArticle = false; function report_article(){ if (!loginData || !loginData.isLoggedIn) { const loginModalButton = $('.login-modal-btn') if (loginModalButton.length) { loginModalButton.click(); } return; } if(!window.isReportArticle){ //to add loader $('.report-loader').addClass('spinner'); jQuery('#report_modal_content').load(gfgSiteUrl+'wp-content/themes/iconic-one/report-modal.php', { PRACTICE_API_URL: practiceAPIURL, PRACTICE_URL:practiceURL },function(responseTxt, statusTxt, xhr){ if(statusTxt == "error"){ alert("Error: " + xhr.status + ": " + xhr.statusText); } }); }else{ window.scrollTo({ top: 0, behavior: 'smooth' }); $("#report_modal_content").show(); } } function closeShareModal() { const shareOption = document.querySelector('[data-gfg-action="share-article"]'); shareOption.classList.remove("hover_share_menu"); let shareModal = document.querySelector(".hover__share-modal-container"); shareModal && shareModal.remove(); } function openShareModal() { closeShareModal(); // Remove existing modal if any let shareModal = document.querySelector(".three_dot_dropdown_share"); shareModal.appendChild(Object.assign(document.createElement("div"), { className: "hover__share-modal-container" })); document.querySelector(".hover__share-modal-container").append( Object.assign(document.createElement('div'), { className: "share__modal" }), ); document.querySelector(".share__modal").append(Object.assign(document.createElement('h1'), { className: "share__modal-heading" }, { textContent: "Share to" })); const socialOptions = ["LinkedIn", "WhatsApp","Twitter", "Copy Link"]; socialOptions.forEach((socialOption) => { const socialContainer = Object.assign(document.createElement('div'), { className: "social__container" }); const icon = Object.assign(document.createElement("div"), { className: `share__icon share__${socialOption.split(" ").join("")}-icon` }); const socialText = Object.assign(document.createElement("span"), { className: "share__option-text" }, { textContent: `${socialOption}` }); const shareLink = (socialOption === "Copy Link") ? Object.assign(document.createElement('div'), { role: "button", className: "link-container CopyLink" }) : Object.assign(document.createElement('a'), { className: "link-container" }); if (socialOption === "LinkedIn") { shareLink.setAttribute('href', `https://www.linkedin.com/sharing/share-offsite/?url=${window.location.href}`); shareLink.setAttribute('target', '_blank'); } if (socialOption === "WhatsApp") { shareLink.setAttribute('href', `https://api.whatsapp.com/send?text=${window.location.href}`); shareLink.setAttribute('target', "_blank"); } if (socialOption === "Twitter") { shareLink.setAttribute('href', `https://twitter.com/intent/tweet?url=${window.location.href}`); shareLink.setAttribute('target', "_blank"); } shareLink.append(icon, socialText); socialContainer.append(shareLink); document.querySelector(".share__modal").appendChild(socialContainer); //adding copy url functionality if(socialOption === "Copy Link") { shareLink.addEventListener("click", function() { var tempInput = document.createElement("input"); tempInput.value = window.location.href; document.body.appendChild(tempInput); tempInput.select(); tempInput.setSelectionRange(0, 99999); // For mobile devices document.execCommand('copy'); document.body.removeChild(tempInput); this.querySelector(".share__option-text").textContent = "Copied" }) } }); // document.querySelector(".hover__share-modal-container").addEventListener("mouseover", () => document.querySelector('[data-gfg-action="share-article"]').classList.add("hover_share_menu")); } function toggleLikeElementVisibility(selector, show) { document.querySelector(`.${selector}`).style.display = show ? "block" : "none"; } function closeKebabMenu(){ document.getElementById("myDropdown").classList.toggle("show"); }
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences