Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Node.js util module

Node.js util module

Java FileNode.js Built-in Modules


In Node.js, the util The module is a core module that provides a series of utility functions. These functions are mainly used to help developers accomplish common programming tasks such as type checking, implementing inheritance, and debug output.util The module was originally designed to compensate for the shortcomings of JavaScript's native features and provide developers with more convenience.

To use util module, you only need to import it in your code:


const util = require('util');

Main functions of the util module

1. Type checking tools

util The module provides some functions for type checking, which are more precise and useful than JavaScript's native typeof operators.

util.types.isArrayBuffer(value)

Checks 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)

Checks 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 C language printf function, 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 used for debugging. Options such as depth and color 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 a function that follows the Node.js callback style into a function that returns a Promise.

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)

The difference between promisify Conversely, converts a function that returns a Promise into a callback-style function.

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 tools

util.inherits(constructor, superConstructor)

Implements prototypal inheritance (ES5 style). Note: In ES6, it is recommended to use class and extends The const keyword.

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. Debug complex objects

When you need to print the structure of a complex object,util.inspect it is more powerful than the simple console.log one:

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. Modernize legacy code

Convert legacy 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 an object's inspect method to change the util.inspect output:

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.inspect It may have a performance impact on large objects, so use it with caution in production environments.
  2. API stability: Although util The module is a core module, but some APIs may still be marked as experimental.
  3. Modern Alternatives: Some features (such as util.inherits) have better alternatives in modern JavaScript (such as class syntax).
  4. Error handling: When using promisify When using them, ensure errors are handled properly to avoid uncaught Promise rejections.

Methods and Properties

Method/attribute 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 logs messages only 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 name of the system error represented by the error code err 9.7.0
util.inherits(constructor, superConstructor) Inherits the prototype methods of one constructor into another (deprecated; ES6 class and extends are recommended) 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 and 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 An alias for the WHATWG standard TextDecoder implementation 8.3.0
util.TextEncoder An alias for the WHATWG standard TextEncoder implementation 8.3.0
util.types A utility object providing various Node.js type checks 10.0.0
util.aborted(err, signal) Checks whether an error was caused by an abort signal 18.18.0
util.parseArgs([config]) A 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 type
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's util The module provides many practical utility functions that help developers write code more efficiently. From type checking to async flow control, and then to debug output,util the module covers many common needs in development. Although modern JavaScript already provides many native solutions, util the module is still very useful in many scenarios, especially when dealing with legacy code or when specific utility functions are needed.

Mastering the util Using the module can make your Node.js development much easier, especially in terms of debugging and code conversion.

Java FileNode.js Built-in Modules