Skip to content

Node.js Utility Modules

Node.js provides a rich set of built-in modules that offer essential utilities frequently needed in application development. These modules don’t require installation via npm; you can use them directly with require().

S.N.Module NameDescriptionExample Usage Snippet
1os ModuleProvides methods and properties related to the underlying operating system. Useful for getting information like OS type, platform, CPU architecture, memory usage, network interfaces, etc.const os = require('os');
console.log('Platform:', os.platform()); // e.g., 'win32', 'linux', 'darwin'
console.log('Free Memory:', os.freemem());
2path ModuleProvides utilities for working with file and directory paths in a cross-platform manner. Essential for constructing, parsing, and normalizing paths.const path = require('path');
const fullPath = path.join(__dirname, 'data', 'file.txt');
console.log('File Extension:', path.extname(fullPath)); // '.txt'
console.log('Directory Name:', path.dirname(fullPath));
3url ModuleProvides utilities for URL resolution and parsing. Useful for breaking down URLs into components (protocol, hostname, path, query parameters) or constructing URLs.const url = require('url');
const myURL = new URL('https://example.com/path?query=value#hash');
console.log('Hostname:', myURL.hostname); // 'example.com'
console.log('Search Params:', myURL.searchParams.get('query')); // 'value'
4util ModuleProvides various utility functions, including util.promisify (for converting callback-based functions to Promise-based ones), util.inspect (for detailed object inspection), and functions for type checking.const util = require('util');
const fs = require('fs');
const readFilePromise = util.promisify(fs.readFile);
async function read() { const data = await readFilePromise('file.txt', 'utf8'); }
5querystring ModuleProvides utilities for parsing and formatting URL query strings (e.g., ?key1=value1&key2=value2). Often used with the http module or when dealing with URL-encoded data.const querystring = require('querystring');
const parsed = querystring.parse('name=Alice&city=Wonderland');
console.log(parsed.city); // 'Wonderland'
const stringified = querystring.stringify({ a: 1, b: 'two' }); // 'a=1&b=two'
6assert ModuleProvides a set of assertion functions primarily used for writing unit tests. If an assertion fails, it throws an AssertionError.const assert = require('assert');
assert.strictEqual(1 + 1, 2, 'Math failure!');
// assert.strictEqual(1 + 1, 3); // This would throw an error

Other important core modules covered in separate sections include fs (File System), http (HTTP Networking), https (HTTPS Networking), events (Event Emitter), stream (Data Streams), and child_process (Child Processes).

Note: The domain module, previously used for error handling across multiple I/O operations, is now deprecated and should generally be avoided. Modern error handling patterns, Promises, and potentially AsyncLocalStorage offer better alternatives.