Node.js Common Utilities
util The module is a built-in module of Node.js that contains utility functions to support debugging, error handling, formatting, and other functions in JavaScript programming.
util It provides a collection of commonly used functions to compensate for the fact that core JavaScript is too minimal.
util The functions in the module cover many aspects, from object inspection and inheritance to string formatting.
Import 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, supporting %s、%d、%j placeholders. |
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) |
Lets one constructor inherit the prototype methods of another constructor. |
util.deprecate(fn, message) |
Marks a function as deprecated, printing a warning message when it is called. |
util.types |
A collection containing various type detection methods, such as isAnyArrayBuffer、isBigInt64Array。 |
util.isDeepStrictEqual(val1, val2) |
Determines whether two values are deeply equal, similar to a deep comparison. |
util.getSystemErrorName(err) |
Returns the system error name based on an error code. |
util.inspect.custom |
A Symbol that can define custom inspect behavior, used 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 whether a value is ArrayBuffer or SharedArrayBuffer。 |
util.types.isArrayBuffer(value) |
Checks whether a value is ArrayBuffer。 |
util.types.isAsyncFunction(value) |
Checks whether a value is an async function. |
util.types.isBigInt64Array(value) |
Checks whether a value is BigInt64Array。 |
util.types.isBigUint64Array(value) |
Checks whether a value is BigUint64Array。 |
util.types.isBooleanObject(value) |
Checks whether a value is a Boolean object. |
util.types.isDataView(value) |
Checks whether a value is DataView。 |
util.types.isDate(value) |
Checks whether a value is Date。 |
util.types.isGeneratorFunction(value) |
Checks whether a value is a generator function. |
util.types.isMap(value) |
Checks whether a value is Map。 |
util.types.isSet(value) |
Checks whether a value is Set。 |
util.types.isRegExp(value) |
Checks whether a value is a regular expression. |
util.types.isSymbolObject(value) |
Checks whether a value is a Symbol object. |
Application Example
util.format() - String formatting
util.format() is used to generate formatted strings, supporting placeholders such as %s, %d, and %j, which represent 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 a callback function to a Promise
util.promisify() converts traditional callback-style functions into functions that return a Promise, so they can be used with async/await.
Example
const
util
=
require
(
'util'
)
;
const
fs
=
require
(
'fs'
)
;
// Convert the callback-style fs.readFile into 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() - Convert a Promise to a callback
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 async function (or a function whose return value is a Promise Promise) into a callback-style function that follows the error-first convention, for example, passing the (err, value) => ... callback as the last argument. In the callback function, the first argument is the reason for rejection (if Promise resolved, it is nullnull), and the second argument 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 code above is:
hello world
The callback function is executed asynchronously and has exception stack trace. If the callback function throws an exception, the process triggers an 'uncaughtException' exception; if it is not caught, the process will exit.
null has a special meaning as an argument in a callback function. If the first argument of the callback is the reason for a Promise rejection and has a return value, and that value can be converted to the boolean false, the value will be wrapped in an Error object, which can be retrieved through the reason property.
function fn() {
return Promise.reject(null);
}
const callbackFunction = util.callbackify(fn);
callbackFunction((err, ret) => {
// When a 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() - Mark a function as deprecated
util.deprecate() is used to mark functions that are not recommended for use; a warning message is displayed when they are 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 prototypal inheritance between objects.
JavaScript's object-oriented features are prototype-based, unlike the common class-based approach. JavaScript does not provide a language-level feature for object inheritance; instead, it is implemented 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 define a base object Base and a Sub that inherits from Base. Base has three properties defined inside the constructor and one function defined on the prototype, and inheritance is implemented through util.inherits. The result is as follows:
base
Hello base
{ name: 'base', base: 1991, sayHello: [Function] }
sub
{ name: 'sub' }
** Note:** Sub only inherits the functions that Base defined on its prototype; the base property and the sayHello function created inside the constructor are not inherited by Sub.
At the same time, properties defined on 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 # has no method 'sayHello'
at Object. (/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 appeared, util.inherits was the main method for implementing inheritance in Node.js. However, after ES6, the class and extends syntax is recommended, which makes inheritance code more readable.
util.inspect() - Print object structure
util.inspect(object[, options]): Converts an object into a string representation for easy debugging.
util.inspect() converts an object into string form and is commonly used for debugging to view the detailed structure and properties of an object. The options parameter can be specified 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 argument "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 argument "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 argument "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 the details.