What is util?
The 'util' package is a core Node.js module that provides utilities for programmatic use in JavaScript. It includes a collection of helper functions for various tasks such as formatting strings, inspecting objects, and using inheritance.
What are util's main functionalities?
format
Formats a string using placeholders and returns it. Similar to printf in C.
const util = require('util');
console.log(util.format('%s:%s', 'foo', 'bar', 'baz')); // 'foo:bar baz'
inspect
Returns a string representation of an object for debugging purposes, with options to show hidden properties and control the depth of inspection.
const util = require('util');
console.log(util.inspect({ foo: 'bar' }, { showHidden: false, depth: null }));
inherits
Allows one constructor to inherit the prototype methods from another, a utility for implementing object-oriented inheritance.
const util = require('util');
function Base() {}
function Derived() {}
util.inherits(Derived, Base);
promisify
Converts a callback-based function to a function that returns a promise, facilitating the use of async/await.
const util = require('util');
const fs = require('fs');
const readFileAsync = util.promisify(fs.readFile);
readFileAsync('example.txt', 'utf8').then(console.log).catch(console.error);
Other packages similar to util
lodash
Lodash is a utility library offering a wide range of methods for manipulating objects, arrays, strings, etc. It's more comprehensive than 'util' but doesn't include some of the Node.js-specific utilities like promisify.
underscore
Underscore.js is a utility library similar to Lodash, providing functional programming helpers without extending any built-in objects. It's less feature-rich compared to Lodash and doesn't include Node.js-specific utilities.
chalk
Chalk is a library for styling terminal strings. It doesn't offer the broad utility functions of 'util' but focuses on a specific area of string styling which 'util' doesn't cover.
bluebird
Bluebird is a library focused on providing advanced features for promises, such as cancellation, progress, and long stack traces. It complements 'util' by enhancing promise functionality beyond what 'util.promisify' offers.
util
node.js util module as a module
install via npm
npm install util
browser support
This module also works in modern browsers. If you need legacy browser support you will need to polyfill ES5 features.