Node.js – util Module

Subject: nodejs

Node.js – util Module

The util module in Node.js provides utility functions that simplify and support core Node.js features, especially in asynchronous programming and debugging. It’s a built-in module and doesn’t require installation.

This module includes commonly used helper functions like promisify, format, types, and inherits.


Why Use the util Module?

  • Convert callback-based functions to promises using util.promisify()
  • Format console messages easily for debugging
  • Inherit from one constructor to another (ES5-style classes)
  • Deeply inspect objects while debugging
  • Use built-in type-checking utilities

Importing the Util Module


1. util.promisify() – Convert Callback to Promise

Convert a Node-style callback function (error-first) into a promise-based one.

Example: Promisify fs.readFile()


2. util.format() – Format Strings Like printf

Output:


3. util.inherits() – Classical Inheritance (Pre-ES6)

Used when extending constructor functions before ES6 class syntax.


4. util.inspect() – Deep Object Inspection

Returns a string representation of an object (great for logging).


5. util.types – Type Checking Utilities


Real-World Use Cases

  • Promisifying fs, child_process, or dns modules
  • Formatting log messages for CLI or debug output
  • Prototype-based class inheritance in legacy code
  • Inspecting deeply nested objects while debugging
  • Type checking in custom runtime utilities

Key Takeaways

  • util provides utilities for debugging, formatting, inheritance, and async programming
  • util.promisify() helps bridge callback APIs to async/await
  • util.inspect() prints objects in developer-friendly formats
  • It’s especially helpful for writing CLI tools, libraries, and diagnostics scripts
Next : Node.js Readline Module