YouTip LogoYouTip

Nodejs Util

Node.js Common Utilities

The util module is a built-in module in Node.js that contains utility functions to support debugging, error handling, formatting, and other aspects of JavaScript programming.

util provides a collection of commonly used functions to compensate for the limited functionality of core JavaScript.

The features in the util module cover a wide range of aspects, from object inspection and inheritance to string formatting.

Importing the util Module

First, you need to import the util module:

const util = require('util');

Common Methods:

Method Description
util.format(format, ...args) String formatting, supports placeholders like %s, %d, %j.
util.inspect(object[, options]) Converts an object to a string for debugging.
util.promisify(function) Converts a callback-style function into a function that returns a Promise.
util.callbackify(fn) Converts a function that returns a Promise into a callback-style function.
util.inherits(constructor, superConstructor) Makes a constructor inherit the prototype methods of another constructor.
util.deprecate(fn, message) Marks a function as deprecated; calling it will print a warning message.
util.types A collection containing various type detection methods, such as isAnyArrayBuffer, isBigInt64Array.
util.isDeepStrictEqual(val1, val2) Determines if two values are deeply strictly equal, similar to deep comparison.
util.getSystemErrorName(err) Returns the system error name based on the error code.
util.inspect.custom A Symbol that can define custom inspect behavior for debugging.

Type Detection Methods under util.types

util.types is a collection containing many type detection methods, extending JavaScript's typeof and instanceof.

Method Description
util.types.isAnyArrayBuffer(value) Checks if the value is an ArrayBuffer or SharedArrayBuffer.
util.types.isArrayBuffer(value) Checks if the value is an ArrayBuffer.
util.types.isAsyncFunction(value) Checks if the value is an async function.
util.types.isBigInt64Array(value) Checks if the value is a BigInt64Array.
util.types.isBigUint64Array(value) Checks if the value is a BigUint64Array.
util.types.isBooleanObject(value) Checks if the value is a Boolean object.
util.types.isDataView(value) Checks if the value is a DataView.
util.types.isDate(value) Checks if the value is a Date.
util.types.isGeneratorFunction(value) Checks if the value is a generator function.
util.types.isMap(value) Checks if the value is a Map.
util.types.isSet(value) Checks if the value is a Set.
util.types.isRegExp(value) Checks if the value is a regular expression.
util.types.isSymbolObject(value) Checks if the value is a Symbol object.

Application Examples

util.format() - String Formatting

util.format() is used to generate formatted strings, supporting placeholders like %s, %d, and %j, which represent string, number, and JSON respectively.

Example

const util = require('util');

const name = 'Alice';
const age = 25;

console.log(util.format('Name: %s, Age: %d', name, age));
// Output: Name: Alice, Age: 25

util.promisify() - Converting Callback Functions to Promises

util.promisify() converts a traditional callback-style function into a function that returns a Promise, allowing it to be used with async/await.

Example

const util = require('util');
const fs = require('fs');

// Convert callback-style fs.readFile to a function that returns a Promise
const readFileAsync = util.promisify(fs.readFile);

(async () => {
  try {
    const data = await readFileAsync('example.txt', 'utf8');
    console.log(data);
  } catch (err) {
    console.error(err);
  }
})();

util.callbackify() - Converting Promises to Callbacks

util.callbackify() converts a function that returns a Promise into a callback-style function, making it easier to use in code environments that require callbacks.

util.callbackify(original) converts an async function (or a function that returns a Promise) into a function following the error-first callback style, for example, with a callback like (err, value) => ... as the last argument. In the callback function, the first parameter is the reason for rejection (or null if the Promise resolved), and the second parameter is the resolved value.

Example

const util = require('util');

async function fn() {
  return 'hello world';
}

const callbackFunction = util.callbackify(fn);

callbackFunction((err, ret) => {
  if (err) throw err;
  console.log(ret);
});

The output of the above code is:

hello world

The callback function is executed asynchronously and has exception stack error tracking. If the callback function throws an exception, the process will trigger an 'uncaughtException' exception. If it is not caught, the process will exit.

null has a special meaning as a parameter in the callback function. If the first parameter of the callback function is the reason for Promise rejection and has a return value, and the value can be converted to the boolean value false, this value will be wrapped in an Error object and can be accessed via the reason property.

function fn() { return Promise.reject(null); }
const callbackFunction = util.callbackify(fn);
callbackFunction((err, ret) => {
  // When the Promise is rejected with `null`, it is wrapped as an Error and the original value is stored in `reason`.
  err && err.hasOwnProperty('reason') && err.reason === null; // true
});

original is an async function. This function returns a traditional callback function.

util.deprecate() - Marking a Function as Deprecated

util.deprecate() is used to mark a function as deprecated. Calling it will display a warning message.

Example

const util = require('util');

const oldFunction = util.deprecate(() => {
  console.log('This function is deprecated');
}, 'oldFunction is deprecated. Use newFunction instead.');

oldFunction(); // Displays a warning when called

util.types - Data Type Detection

util.types provides a set of methods to detect specific data types, extending the functionality of typeof and instanceof.

Example

const util = require('util');

console.log(util.types.isDate(new Date())); // true
console.log(util.types.isMap(new Map())); // true

util.inherits

util.inherits(constructor, superConstructor) is a function that implements prototype inheritance between objects.

JavaScript's object-oriented features are based on prototypes, which is different from common class-based inheritance. JavaScript does not provide language-level features for object inheritance but achieves it through prototype copying.

Here we only introduce the usage of util.inherits, with the following example:

var util = require('util');

function Base() {
  this.name = 'base';
  this.base = 1991;
  this.sayHello = function() {
    console.log('Hello ' + this.name);
  };
}

Base.prototype.showName = function() {
  console.log(this.name);
};

function Sub() {
  this.name = 'sub';
}

util.inherits(Sub, Base);

var objBase = new Base();
objBase.showName();
objBase.sayHello();
console.log(objBase);

var objSub = new Sub();
objSub.showName();
//objSub.sayHello();
console.log(objSub);

We defined a base object Base and a Sub that inherits from Base. Base has three properties defined inside the constructor and one function defined in the prototype. Inheritance is achieved through util.inherits. The results are as follows:

base
Hello base
{ name: 'base', base: 1991, sayHello:  }
sub
{ name: 'sub' }

Note: Sub only inherits the function defined in the prototype of Base. The properties and functions created inside the constructor, like base and sayHello, are not inherited by Sub.

Also, properties defined in the prototype are not output by console.log as object properties. If we uncomment the line objSub.sayHello();, we will see:

node.js:201
throw e; // process.nextTick error, or 'error' event on first tick
^
TypeError: Object #<Sub> has no method 'sayHello'
    at Object.<anonymous> (/home/byvoid/utilinherits.js:29:8)
    at Module._compile (module.js:441:26)
    at Object..js (module.js:459:10)
    at Module.load (module.js:348:31)
    at Function._load (module.js:308:12)
    at Array.0 (module.js:479:10)
    at EventEmitter._tickCallback (node.js:192:40)

Note: Before ES6, util.inherits was the primary method for implementing inheritance in Node.js. However, after ES6, it is recommended to use class and extends syntax, which makes the inheritance code more readable.

util.inspect() - Printing Object Structure

util.inspect(object[, options]): Converts an object to a string representation for debugging.

util.inspect() converts an object to a string form, commonly used for debugging to view the detailed structure and properties of an object. You can specify the options parameter to control the output format.

Example

const obj = { a: 1, b: 2, c: { d: 3 } };

console.log(util.inspect(obj, { showHidden: false, depth: null, colors: true }));

util.isArray(object)

Returns true if the given parameter "object" is an array, otherwise returns false.

var util = require('util');
util.isArray([]) // true
util.isArray(new Array) // true
util.isArray({}) // false

util.isRegExp(object)

Returns true if the given parameter "object" is a regular expression, otherwise returns false.

var util = require('util');
util.isRegExp(/some regexp/) // true
util.isRegExp(new RegExp('another regexp')) // true
util.isRegExp({}) // false

util.isDate(object)

Returns true if the given parameter "object" is a date, otherwise returns false.

var util = require('util');
util.isDate(new Date()) // true
util.isDate(Date()) // false (without 'new' returns a String)
util.isDate({}) // false

For more details, you can visit http://nodejs.org/api/util.html to learn more.

← Nodejs FsNodejs Global Object β†’