Node.js Common Utilities

utilThe module is a built-in module of Node.js, containing utility functions that support debugging, error handling, formatting, and other functions in JavaScript programming.

utilProvides a collection of commonly used functions to compensate for the overly simplistic functionality of core JavaScript.

utilThe functions in the module cover various aspects from object inspection, inheritance, to string formatting.

Import the util module

First, you need to import the util module:

const util = require('util');

Common methods:

MethodDescription
util.format(format, ...args)String formatting, supports%s、%d、%jplaceholders.
util.inspect(object[, options])Converts an object to a string for debugging.
util.promisify(function)Converts callback-style functions to functions returning Promise.
util.callbackify(fn)Converts Promise-returning functions to callback-style functions.
util.inherits(constructor, superConstructor)Makes a constructor inherit the prototype methods of another constructor.
util.deprecate(fn, message)Marks a function as deprecated, and prints a warning message when called.
util.typesA collection containing multiple type detection methods, such asisAnyArrayBuffer、isBigInt64Array。
util.isDeepStrictEqual(val1, val2)Determines whether two values are deeply equal, similar to deep comparison.
util.getSystemErrorName(err)Returns the system error name based on the error code.
util.inspect.customA Symbol that can define custominspectbehavior for debugging.

Type detection methods under util.types

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

MethodDescription
util.types.isAnyArrayBuffer(value)Checks whether the value isArrayBufferorSharedArrayBuffer。
util.types.isArrayBuffer(value)Checks whether the value isArrayBuffer。
util.types.isAsyncFunction(value)Checks whether the value is an async function.
util.types.isBigInt64Array(value)Checks whether the value isBigInt64Array。
util.types.isBigUint64Array(value)Checks whether the value isBigUint64Array。
util.types.isBooleanObject(value)Checks whether the value is a Boolean object.
util.types.isDataView(value)Checks whether the value isDataView。
util.types.isDate(value)Checks whether the value isDate。
util.types.isGeneratorFunction(value)Checks whether the value is a generator function.
util.types.isMap(value)Checks whether the value isMap。
util.types.isSet(value)Checks whether the value isSet。
util.types.isRegExp(value)Checks whether the value is a regular expression.
util.types.isSymbolObject(value)Checks whether the value is a Symbol object.

Application examples

util.format() - String formatting

util.format() is used to generate formatted strings, supporting placeholders such as %s, %d, and %j, representing strings, numbers, 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() - Convert callback functions to Promise

util.promisify() converts traditional callback-style functions into functions returning Promise, so they can be used with async/await.

Example

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

// Convert callback-style fs.readFile to a function returning 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() - Convert Promise to callback

util.callbackify() converts Promise-returning functions to callback-style functions, making them convenient for use in code environments that require callbacks.

util.callbackify(original)willasyncAn async function (or a function whose return value isPromisefunction) is converted into a callback-style function following the error-first convention, for example taking the(err, value) => ...callback as the last parameter.Promiseresolves, it isnull), 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 tracing. 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 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 boolean 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) => {
  // 当 Promise 被以 `null` 拒绝时,它被包装为 Error 并且原始值存储在 `reason` 中。
  err && err.hasOwnProperty('reason') && err.reason === null;  // true
});

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

util.deprecate() - Mark a function as deprecated

util.deprecate() is used to mark functions that are not recommended for use, and a warning message will be displayed when called.

Example

const util = require('util');

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

oldFunction();  // A warning is displayed 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, unlike the common class-based approach. JavaScript does not provide language-level features for object inheritance, but implements it through prototype copying.

Here we only introduce the usage of util.inherits, the example is as follows:

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 define 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 implemented through util.inherits. The running result is as follows:

base 
Hello base 
{ name: 'base', base: 1991, sayHello: [Function] } 
sub 
{ name: 'sub' }

Note:Sub only inherits the function defined by Base in the prototype, while the base property and sayHello function created inside the constructor are not inherited by Sub.

At the same time, properties defined in the prototype will not be output as object properties by console.log. If we remove the comment on 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 main method for implementing inheritance in Node.js. However, after ES6, it is recommended to use class and extends syntax, making the inheritance code more readable.

util.inspect() - Print object structure

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

util.inspect() converts an object to a string form, often used in debugging to view the detailed structure and properties of the 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, please visithttp://nodejs.org/api/util.htmlto learn more.

Other extensions