Node.js util module

Java FileNode.js built-in modules


In Node.jsutilThe module is a core module that provides a series of utility functions. These functions are mainly used to help developers complete common programming tasks, such as type checking, inheritance implementation, debugging output, etc.utilThe module was originally designed to make up for the deficiencies of JavaScript's native features and provide developers with more convenience.

To useutilmodule, you just need to import it in your code:

const util = require('util');

Main features of the util module

1. Type checking utilities

utilThe module provides some functions for type checking, which are more precise and useful than JavaScript's nativetypeofoperators.

util.types.isArrayBuffer(value)

Check whether the given value is an ArrayBuffer instance.

Example

const arrBuffer = new ArrayBuffer(8);
console.log(util.types.isArrayBuffer(arrBuffer)); // true
console.log(util.types.isArrayBuffer([])); // false

util.types.isDate(value)

Check whether the given value is a Date instance.

Example

console.log(util.types.isDate(new Date())); // true
console.log(util.types.isDate('2023-01-01')); // false

2. Utility functions

util.format(format[, ...args])

Similar to the printfprintffunction in C language, used to format strings.

Example

const name = 'John';
const age = 30;
console.log(util.format('My name is %s and I am %d years old', name, age));
// Output: My name is John and I am 30 years old

util.inspect(object[, options])

Returns the string representation of an object, mainly for debugging. Options such as depth and colors can be configured.

Example

const obj = {
  name: 'Alice',
  details: {
    age: 25,
    hobbies: ['reading', 'coding']
  }
};

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

3. Callback style conversion

util.promisify(original)

Converts functions that follow the Node.js callback style into functions that return Promises.

Example

const fs = require('fs');
const readFile = util.promisify(fs.readFile);

async function readConfig() {
  try {
    const data = await readFile('config.json', 'utf8');
    console.log(data);
  } catch (err) {
    console.error('Error reading file:', err);
  }
}

readConfig();

util.callbackify(original)

andpromisifyConversely, converts functions that return Promises into callback-style functions.

Example

async function asyncFunc() {
  return 'Hello World';
}

const callbackFunc = util.callbackify(asyncFunc);

callbackFunc((err, result) => {
  if (err) throw err;
  console.log(result); // Hello World
});

4. Inheritance utilities

util.inherits(constructor, superConstructor)

Implements prototype inheritance (ES5 style). Note: In ES6, it is recommended to use theclassandextendskeyword.

Example

function Animal(name) {
  this.name = name;
}

Animal.prototype.speak = function() {
  console.log(this.name + ' makes a noise.');
};

function Dog(name) {
  Animal.call(this, name);
}

util.inherits(Dog, Animal);

Dog.prototype.speak = function() {
  console.log(this.name + ' barks.');
};

const d = new Dog('Rex');
d.speak(); // Rex barks.

Practical application scenarios of the util module

1. Debugging complex objects

When you need to print the structure of a complex object,util.inspectis more powerful than simpleconsole.logconsole.log:

Example

const complexObj = {
  date: new Date(),
  regex: /test/g,
  nested: {
    array: [1, 2, 3],
    fn: function() {}
  }
};

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

2. Modernizing old code

Convert old callback-style code to Promise style:

Example

// Old callback-style code
function oldStyleFunc(param, callback) {
  // Some asynchronous operations
  setTimeout(() => {
    callback(null, `Result for ${param}`);
  }, 100);
}

// Convert to Promise style
const newStyleFunc = util.promisify(oldStyleFunc);

async function useNewStyle() {
  const result = await newStyleFunc('test');
  console.log(result); // Result for test
}

useNewStyle();

3. Custom object inspection

You can customize the object'sinspectmethod to changeutil.inspectthe output of util.inspect:

Example

class CustomObject {
  constructor(value) {
    this.value = value;
  }
 
  [util.inspect.custom](depth, options) {
    return `CustomObject: ${this.value}`;
  }
}

const obj = new CustomObject('test');
console.log(util.inspect(obj)); // CustomObject: test

Notes

  1. Performance considerations:util.inspectFor large objects, there may be performance impact; use with caution in production environments.
  2. API stability: AlthoughutilThe module is a core module, but some APIs may still be marked as experimental features.
  3. Modern alternatives: Some features (such asutil.inherits) have better alternatives in modern JavaScript (such as theclasssyntax).
  4. Error handling: When usingpromisifymake sure to handle errors correctly to avoid unhandled Promise rejections.

Methods and Properties

Method/Property Description Version introduced
util.callbackify(original) Converts an async function that returns a Promise into a callback-style function. 8.2.0
util.debuglog(section) Creates a function that only logs messages when the NODE_DEBUG environment variable contains the specified section. 0.11.3
util.deprecate(fn, msg[, code]) Wraps a function so that it emits a deprecation warning when called. 0.8.0
util.format(format[, ...args]) Formats a string using the first argument as a printf-like format string. 0.5.3
util.formatWithOptions(inspectOptions, format[, ...args]) Similar to util.format(), but accepts inspect options. 10.0.0
util.getSystemErrorName(err) Returns the system error name represented by the error code err. 9.7.0
util.inherits(constructor, superConstructor) Inherits the prototype methods of one constructor to another constructor (deprecated; it is recommended to use ES6 class and extends). 0.3.0
util.inspect(object[, options]) Returns the string representation of object, used for debugging. 0.3.0
util.isDeepStrictEqual(val1, val2) Tests whether two values are deeply strictly equal. 9.0.0
util.promisify(original) Converts a callback-style function into a function that returns a Promise. 8.0.0
util.stripVTControlCharacters(str) Strips ANSI escape codes from a string. 16.11.0
util.TextDecoder Alias for the WHATWG standard TextDecoder implementation. 8.3.0
util.TextEncoder Alias for the WHATWG standard TextEncoder implementation. 8.3.0
util.types Provides a utility object for various Node.js type checks. 10.0.0
util.aborted(err, signal) Checks whether an error is caused by an abort signal. 18.18.0
util.parseArgs([config]) Utility function for parsing command-line arguments. 18.3.0

Methods provided by util.types

Method Description
util.types.isAnyArrayBuffer(value) Checks whether it is an AnyArrayBuffer instance.
util.types.isArrayBuffer(value) Checks whether it is an ArrayBuffer instance.
util.types.isAsyncFunction(value) Checks whether it is an async function.
util.types.isBigInt64Array(value) Checks whether it is a BigInt64Array instance.
util.types.isBigUint64Array(value) Checks whether it is a BigUint64Array instance.
util.types.isBooleanObject(value) Checks whether it is a Boolean object.
util.types.isBoxedPrimitive(value) Checks whether it is a boxed primitive.
util.types.isCryptoKey(value) Checks whether it is a CryptoKey instance.
util.types.isDataView(value) Checks whether it is a DataView instance.
util.types.isDate(value) Checks whether it is a Date instance.
util.types.isExternal(value) Checks whether it is an external native value.
util.types.isFloat32Array(value) Checks whether it is a Float32Array instance.
util.types.isFloat64Array(value) Checks whether it is a Float64Array instance.
util.types.isGeneratorFunction(value) Checks whether it is a generator function.
util.types.isGeneratorObject(value) Checks whether it is a generator object.
util.types.isInt8Array(value) Checks whether it is an Int8Array instance.
util.types.isInt16Array(value) Checks whether it is an Int16Array instance.
util.types.isInt32Array(value) Checks whether it is an Int32Array instance.
util.types.isMap(value) Checks whether it is a Map instance.
util.types.isMapIterator(value) Checks whether it is a Map iterator.
util.types.isModuleNamespaceObject(value) Checks whether it is a module namespace object.
util.types.isNativeError(value) Checks whether it is a native error object.
util.types.isNumberObject(value) Checks whether it is a Number object.
util.types.isPromise(value) Checks whether it is a Promise.
util.types.isProxy(value) Checks whether it is a Proxy object.
util.types.isRegExp(value) Checks whether it is a RegExp object.
util.types.isSet(value) Checks whether it is a Set instance.
util.types.isSetIterator(value) Checks whether it is a Set iterator.
util.types.isSharedArrayBuffer(value) Checks whether it is a SharedArrayBuffer instance.
util.types.isStringObject(value) Checks whether it is a String object.
util.types.isSymbolObject(value) Checks whether it is a Symbol object.
util.types.isTypedArray(value) Checks whether it is a TypedArray instance.
util.types.isUint8Array(value) Checks whether it is a Uint8Array instance.
util.types.isUint8ClampedArray(value) Checks whether it is a Uint8ClampedArray instance.
util.types.isUint16Array(value) Checks whether it is a Uint16Array instance.
util.types.isUint32Array(value) Checks whether it is a Uint32Array instance.
util.types.isWeakMap(value) Checks whether it is a WeakMap instance.
util.types.isWeakSet(value) Checks whether it is a WeakSet instance.

Summary

Node.js'sutilThe module provides many practical utility functions that can help developers write code more efficiently. From type checking to asynchronous flow control to debugging output,utilThe module covers many common development needs. Although modern JavaScript already provides many native solutions,utilThe module is still very useful in many scenarios, especially when dealing with legacy code or when specific utility functions are needed.

MasteringutilThe use of the module can make your Node.js development more comfortable and efficient, especially in debugging and code conversion.

Java FileNode.js built-in modules