home / documentation / v19 / util

Util

目录

Added in: v0.10.0

稳定性: 2 - Stable

The node:util module supports the needs of Node.js internal APIs. Many of the utilities are useful for application and module developers as well. To access it:

JS

M util.callbackify(original)

Added in: v8.2.0

Takes an async function (or a function that returns a Promise) and returns a function following the error-first callback style, i.e. taking an (err, value) => ... callback as the last argument. In the callback, the first argument will be the rejection reason (or null if the Promise resolved), and the second argument will be the resolved value.

JS

Will print:

TEXT

The callback is executed asynchronously, and will have a limited stack trace. If the callback throws, the process will emit an 'uncaughtException' event, and if not handled will exit.

Since null has a special meaning as the first argument to a callback, if a wrapped function rejects a Promise with a falsy value as a reason, the value is wrapped in an Error with the original value stored in a field named reason.

JS

M util.debuglog(section[, callback])

Added in: v0.11.3

  • section string A string identifying the portion of the application for which the debuglog function is being created.
  • callback Function A callback invoked the first time the logging function is called with a function argument that is a more optimized logging function.
  • Returns: Function The logging function

The util.debuglog() method is used to create a function that conditionally writes debug messages to stderr based on the existence of the NODE_DEBUG environment variable. If the section name appears within the value of that environment variable, then the returned function operates similar to console.error(). If not, then the returned function is a no-op.

JS

If this program is run with NODE_DEBUG=foo in the environment, then it will output something like:

BASH

where 3245 is the process id. If it is not run with that environment variable set, then it will not print anything.

The section supports wildcard also:

JS

if it is run with NODE_DEBUG=foo* in the environment, then it will output something like:

BASH

Multiple comma-separated section names may be specified in the NODE_DEBUG environment variable: NODE_DEBUG=fs,net,tls.

The optional callback argument can be used to replace the logging function with a different function that doesn't have any initialization or unnecessary wrapping.

JS

M debuglog().enabled

Added in: v14.9.0

The util.debuglog().enabled getter is used to create a test that can be used in conditionals based on the existence of the NODE_DEBUG environment variable. If the section name appears within the value of that environment variable, then the returned value will be true. If not, then the returned value will be false.

JS

If this program is run with NODE_DEBUG=foo in the environment, then it will output something like:

BASH

M util.debug(section)

Added in: v14.9.0

Alias for util.debuglog. Usage allows for readability of that doesn't imply logging when only using util.debuglog().enabled.

M util.deprecate(fn, msg[, code])

历史
版本更改
v10.0.0Deprecation warnings are only emitted once for each code.
v0.8.0Added in: v0.8.0
  • fn Function The function that is being deprecated.
  • msg string A warning message to display when the deprecated function is invoked.
  • code string A deprecation code. See the list of deprecated APIs for a list of codes.
  • Returns: Function The deprecated function wrapped to emit a warning.

The util.deprecate() method wraps fn (which may be a function or class) in such a way that it is marked as deprecated.

JS

When called, util.deprecate() will return a function that will emit a DeprecationWarning using the 'warning' event. The warning will be emitted and printed to stderr the first time the returned function is called. After the warning is emitted, the wrapped function is called without emitting a warning.

If the same optional code is supplied in multiple calls to util.deprecate(), the warning will be emitted only once for that code.

JS

If either the --no-deprecation or --no-warnings command-line flags are used, or if the process.noDeprecation property is set to true prior to the first deprecation warning, the util.deprecate() method does nothing.

If the --trace-deprecation or --trace-warnings command-line flags are set, or the process.traceDeprecation property is set to true, a warning and a stack trace are printed to stderr the first time the deprecated function is called.

If the --throw-deprecation command-line flag is set, or the process.throwDeprecation property is set to true, then an exception will be thrown when the deprecated function is called.

The --throw-deprecation command-line flag and process.throwDeprecation property take precedence over --trace-deprecation and process.traceDeprecation.

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

历史
版本更改
v12.11.0The `%c` specifier is ignored now.
v12.0.0The `format` argument is now only taken as such if it actually contains format specifiers.
v12.0.0If the `format` argument is not a format string, the output string's formatting is no longer dependent on the type of the first argument. This change removes previously present quotes from strings that were being output when the first argument was not a string.
v11.4.0The `%d`, `%f`, and `%i` specifiers now support Symbols properly.
v11.4.0The `%o` specifier's `depth` has default depth of 4 again.
v11.0.0The `%o` specifier's `depth` option will now fall back to the default depth.
v10.12.0The `%d` and `%i` specifiers now support BigInt.
v8.4.0The `%o` and `%O` specifiers are supported now.
v0.5.3Added in: v0.5.3
  • format string A printf-like format string.

The util.format() method returns a formatted string using the first argument as a printf-like format string which can contain zero or more format specifiers. Each specifier is replaced with the converted value from the corresponding argument. Supported specifiers are:

  • %s: String will be used to convert all values except BigInt, Object and -0. BigInt values will be represented with an n and Objects that have no user defined toString function are inspected using util.inspect() with options { depth: 0, colors: false, compact: 3 }.
  • %d: Number will be used to convert all values except BigInt and Symbol.
  • %i: parseInt(value, 10) is used for all values except BigInt and Symbol.
  • %f: parseFloat(value) is used for all values expect Symbol.
  • %j: JSON. Replaced with the string '[Circular]' if the argument contains circular references.
  • %o: Object. A string representation of an object with generic JavaScript object formatting. Similar to util.inspect() with options { showHidden: true, showProxy: true }. This will show the full object including non-enumerable properties and proxies.
  • %O: Object. A string representation of an object with generic JavaScript object formatting. Similar to util.inspect() without options. This will show the full object not including non-enumerable properties and proxies.
  • %c: CSS. This specifier is ignored and will skip any CSS passed in.
  • %%: single percent sign ('%'). This does not consume an argument.
  • Returns: string The formatted string

If a specifier does not have a corresponding argument, it is not replaced:

JS

Values that are not part of the format string are formatted using util.inspect() if their type is not string.

If there are more arguments passed to the util.format() method than the number of specifiers, the extra arguments are concatenated to the returned string, separated by spaces:

JS

If the first argument does not contain a valid format specifier, util.format() returns a string that is the concatenation of all arguments separated by spaces:

JS

If only one argument is passed to util.format(), it is returned as it is without any formatting:

JS

util.format() is a synchronous method that is intended as a debugging tool. Some input values can have a significant performance overhead that can block the event loop. Use this function with care and never in a hot code path.

M util.formatWithOptions(inspectOptions, format[, ...args])

Added in: v10.0.0

This function is identical to util.format(), except in that it takes an inspectOptions argument which specifies options that are passed along to util.inspect().

JS

M util.getSystemErrorName(err)

Added in: v9.7.0

Returns the string name for a numeric error code that comes from a Node.js API. The mapping between error codes and error names is platform-dependent. See Common System Errors for the names of common errors.

JS

M util.getSystemErrorMap()

Added in: v16.0.0, v14.17.0

Returns a Map of all system error codes available from the Node.js API. The mapping between error codes and error names is platform-dependent. See Common System Errors for the names of common errors.

JS

M util.inherits(constructor, superConstructor)

历史
版本更改
v5.0.0The `constructor` parameter can refer to an ES6 class now.
v0.3.0Added in: v0.3.0
稳定性: 3 - Legacy: Use ES2015 class syntax and `extends` keyword instead.

Usage of util.inherits() is discouraged. Please use the ES6 class and extends keywords to get language level inheritance support. Also note that the two styles are semantically incompatible.

Inherit the prototype methods from one constructor into another. The prototype of constructor will be set to a new object created from superConstructor.

This mainly adds some input validation on top of Object.setPrototypeOf(constructor.prototype, superConstructor.prototype). As an additional convenience, superConstructor will be accessible through the constructor.super_ property.

JS

ES6 example using class and extends:

JS

M util.inspect(object[, options])

M util.inspect(object[, showHidden[, depth[, colors]]])

历史
版本更改
v17.3.0, v16.14.0The `numericSeparator` option is supported now.
v16.18.0add support for `maxArrayLength` when inspecting `Set` and `Map`.
v14.6.0, v12.19.0If `object` is from a different `vm.Context` now, a custom inspection function on it will not receive context-specific arguments anymore.
v13.13.0, v12.17.0The `maxStringLength` option is supported now.
v13.5.0, v12.16.0User defined prototype properties are inspected in case `showHidden` is `true`.
v13.0.0Circular references now include a marker to the reference.
v12.0.0The `compact` options default is changed to `3` and the `breakLength` options default is changed to `80`.
v12.0.0Internal properties no longer appear in the context argument of a custom inspection function.
v11.11.0The `compact` option accepts numbers for a new output mode.
v11.7.0ArrayBuffers now also show their binary contents.
v11.5.0The `getters` option is supported now.
v11.4.0The `depth` default changed back to `2`.
v11.0.0The `depth` default changed to `20`.
v11.0.0The inspection output is now limited to about 128 MiB. Data above that size will not be fully inspected.
v10.12.0The `sorted` option is supported now.
v10.6.0Inspecting linked lists and similar objects is now possible up to the maximum call stack size.
v10.0.0The `WeakMap` and `WeakSet` entries can now be inspected as well.
v9.9.0The `compact` option is supported now.
v6.6.0Custom inspection functions can now return `this`.
v6.3.0The `breakLength` option is supported now.
v6.1.0The `maxArrayLength` option is supported now; in particular, long arrays are truncated by default.
v6.1.0The `showProxy` option is supported now.
v0.3.0Added in: v0.3.0
  • object any Any JavaScript primitive or Object.
  • options Object
    • showHidden boolean If true, object's non-enumerable symbols and properties are included in the formatted result. WeakMap and WeakSet entries are also included as well as user defined prototype properties (excluding method properties). Default: false.
    • depth number Specifies the number of times to recurse while formatting object. This is useful for inspecting large objects. To recurse up to the maximum call stack size pass Infinity or null. Default: 2.
    • colors boolean If true, the output is styled with ANSI color codes. Colors are customizable. See Customizing util.inspect colors. Default: false.
    • customInspect boolean If false, [util.inspect.custom](depth, opts, inspect) functions are not invoked. Default: true.
    • showProxy boolean If true, Proxy inspection includes the target and handler objects. Default: false.
    • maxArrayLength integer Specifies the maximum number of Array, TypedArray, Map, Set, WeakMap, and WeakSet elements to include when formatting. Set to null or Infinity to show all elements. Set to 0 or negative to show no elements. Default: 100.
    • maxStringLength integer Specifies the maximum number of characters to include when formatting. Set to null or Infinity to show all elements. Set to 0 or negative to show no characters. Default: 10000.
    • breakLength integer The length at which input values are split across multiple lines. Set to Infinity to format the input as a single line (in combination with compact set to true or any number >= 1). Default: 80.
    • compact boolean | integer Setting this to false causes each object key to be displayed on a new line. It will break on new lines in text that is longer than breakLength. If set to a number, the most n inner elements are united on a single line as long as all properties fit into breakLength. Short array elements are also grouped together. For more information, see the example below. Default: 3.
    • sorted boolean | Function If set to true or a function, all properties of an object, and Set and Map entries are sorted in the resulting string. If set to true the default sort is used. If set to a function, it is used as a compare function.
    • getters boolean | string If set to true, getters are inspected. If set to 'get', only getters without a corresponding setter are inspected. If set to 'set', only getters with a corresponding setter are inspected. This might cause side effects depending on the getter function. Default: false.
    • numericSeparator boolean If set to true, an underscore is used to separate every three digits in all bigints and numbers. Default: false.
  • Returns: string The representation of object.

The util.inspect() method returns a string representation of object that is intended for debugging. The output of util.inspect may change at any time and should not be depended upon programmatically. Additional options may be passed that alter the result. util.inspect() will use the constructor's name and/or @@toStringTag to make an identifiable tag for an inspected value.

JS

Circular references point to their anchor by using a reference index:

JS

The following example inspects all properties of the util object:

JS

The following example highlights the effect of the compact option:

JS

The showHidden option allows WeakMap and WeakSet entries to be inspected. If there are more entries than maxArrayLength, there is no guarantee which entries are displayed. That means retrieving the same WeakSet entries twice may result in different output. Furthermore, entries with no remaining strong references may be garbage collected at any time.

JS

The sorted option ensures that an object's property insertion order does not impact the result of util.inspect().

JS

The numericSeparator option adds an underscore every three digits to all numbers.

JS

util.inspect() is a synchronous method intended for debugging. Its maximum output length is approximately 128 MiB. Inputs that result in longer output will be truncated.

Customizing util.inspect colors

Color output (if enabled) of util.inspect is customizable globally via the util.inspect.styles and util.inspect.colors properties.

util.inspect.styles is a map associating a style name to a color from util.inspect.colors.

The default styles and associated colors are:

  • bigint: yellow
  • boolean: yellow
  • date: magenta
  • module: underline
  • name: (no styling)
  • null: bold
  • number: yellow
  • regexp: red
  • special: cyan (e.g., Proxies)
  • string: green
  • symbol: green
  • undefined: grey

Color styling uses ANSI control codes that may not be supported on all terminals. To verify color support use tty.hasColors().

Predefined control codes are listed below (grouped as "Modifiers", "Foreground colors", and "Background colors").

Modifiers

Modifier support varies throughout different terminals. They will mostly be ignored, if not supported.

  • reset - Resets all (color) modifiers to their defaults
  • bold - Make text bold
  • italic - Make text italic
  • underline - Make text underlined
  • strikethrough - Puts a horizontal line through the center of the text (Alias: strikeThrough, crossedout, crossedOut)
  • hidden - Prints the text, but makes it invisible (Alias: conceal)
  • dim - Decreased color intensity (Alias: `faint`)
  • overlined - Make text overlined
  • blink - Hides and shows the text in an interval
  • inverse - Swap foreground and background colors (Alias: `swapcolors`, `swapColors`)
  • doubleunderline - Make text double underlined (Alias: `doubleUnderline`)
  • framed - Draw a frame around the text
Foreground colors
  • black
  • red
  • green
  • yellow
  • blue
  • magenta
  • cyan
  • white
  • gray (alias: grey, blackBright)
  • redBright
  • greenBright
  • yellowBright
  • blueBright
  • magentaBright
  • cyanBright
  • whiteBright
Background colors
  • bgBlack
  • bgRed
  • bgGreen
  • bgYellow
  • bgBlue
  • bgMagenta
  • bgCyan
  • bgWhite
  • bgGray (alias: bgGrey, bgBlackBright)
  • bgRedBright
  • bgGreenBright
  • bgYellowBright
  • bgBlueBright
  • bgMagentaBright
  • bgCyanBright
  • bgWhiteBright

Custom inspection functions on objects

历史
版本更改
v17.3.0, v16.14.0The inspect argument is added for more interoperability.
v0.1.97Added in: v0.1.97

Objects may also define their own [util.inspect.custom](depth, opts, inspect) function, which util.inspect() will invoke and use the result of when inspecting the object.

JS

Custom [util.inspect.custom](depth, opts, inspect) functions typically return a string but may return a value of any type that will be formatted accordingly by util.inspect().

JS

M util.inspect.custom

历史
版本更改
v10.12.0This is now defined as a shared symbol.
v6.6.0Added in: v6.6.0
  • symbol that can be used to declare custom inspect functions.

In addition to being accessible through util.inspect.custom, this symbol is registered globally and can be accessed in any environment as Symbol.for('nodejs.util.inspect.custom').

Using this allows code to be written in a portable fashion, so that the custom inspect function is used in an Node.js environment and ignored in the browser. The util.inspect() function itself is passed as third argument to the custom inspect function to allow further portability.

JS

See Custom inspection functions on Objects for more details.

M util.inspect.defaultOptions

Added in: v6.4.0

The defaultOptions value allows customization of the default options used by util.inspect. This is useful for functions like console.log or util.format which implicitly call into util.inspect. It shall be set to an object containing one or more valid util.inspect() options. Setting option properties directly is also supported.

JS

M util.isDeepStrictEqual(val1, val2)

Added in: v9.0.0

Returns true if there is deep strict equality between val1 and val2. Otherwise, returns false.

See assert.deepStrictEqual() for more information about deep strict equality.

C util.MIMEType

Added in: v19.1.0

稳定性: 1 - Experimental

An implementation of the MIMEType class.

In accordance with browser conventions, all properties of MIMEType objects are implemented as getters and setters on the class prototype, rather than as data properties on the object itself.

A MIME string is a structured string containing multiple meaningful components. When parsed, a MIMEType object is returned containing properties for each of these components.

Constructor: new MIMEType(input)

  • input string The input MIME to parse

Creates a new MIMEType object by parsing the input.

MJS
CJS

A TypeError will be thrown if the input is not a valid MIME. Note that an effort will be made to coerce the given values into strings. For instance:

MJS
CJS
M mime.type

Gets and sets the type portion of the MIME.

MJS
CJS
M mime.subtype

Gets and sets the subtype portion of the MIME.

MJS
CJS
M mime.essence

Gets the essence of the MIME. This property is read only. Use mime.type or mime.subtype to alter the MIME.

MJS
CJS
M mime.params
  • MIMEParams

Gets the MIMEParams object representing the parameters of the MIME. This property is read-only. See MIMEParams documentation for details.

M mime.toString()

The toString() method on the MIMEType object returns the serialized MIME.

Because of the need for standard compliance, this method does not allow users to customize the serialization process of the MIME.

M mime.toJSON()

Alias for mime.toString().

This method is automatically called when an MIMEType object is serialized with JSON.stringify().

MJS
CJS

C util.MIMEParams

Added in: v19.1.0

The MIMEParams API provides read and write access to the parameters of a MIMEType.

Constructor: new MIMEParams()

Creates a new MIMEParams object by with empty parameters

MJS
CJS
M mimeParams.delete(name)

Remove all name-value pairs whose name is name.

M mimeParams.entries()

Returns an iterator over each of the name-value pairs in the parameters. Each item of the iterator is a JavaScript Array. The first item of the array is the name, the second item of the array is the value.

M mimeParams.get(name)
  • name string
  • Returns: string or null if there is no name-value pair with the given name.

Returns the value of the first name-value pair whose name is name. If there are no such pairs, null is returned.

M mimeParams.has(name)

Returns true if there is at least one name-value pair whose name is name.

M mimeParams.keys()

Returns an iterator over the names of each name-value pair.

MJS
CJS
M mimeParams.set(name, value)

Sets the value in the MIMEParams object associated with name to value. If there are any pre-existing name-value pairs whose names are name, set the first such pair's value to value.

MJS
CJS
M mimeParams.values()

Returns an iterator over the values of each name-value pair.

M mimeParams[@@iterator]()

Alias for mimeParams.entries().

MJS
CJS

M util.parseArgs([config])

历史
版本更改
v18.11.0Add support for default values in input `config`.
v18.7.0, v16.17.0add support for returning detailed parse information using `tokens` in input `config` and returned properties.
v18.3.0, v16.17.0Added in: v18.3.0, v16.17.0
稳定性: 1 - Experimental
  • config Object Used to provide arguments for parsing and to configure the parser. config supports the following properties:

    • args string[] array of argument strings. Default: process.argv with execPath and filename removed.
    • options Object Used to describe arguments known to the parser. Keys of options are the long names of options and values are an Object accepting the following properties:
      • type string Type of argument, which must be either boolean or string.
      • multiple boolean Whether this option can be provided multiple times. If true, all values will be collected in an array. If false, values for the option are last-wins. Default: false.
      • short string A single character alias for the option.
      • default string | boolean The default option value when it is not set by args. It must be of the same type as the type property. When multiple is true, it must be an array.
    • strict boolean Should an error be thrown when unknown arguments are encountered, or when arguments are passed that do not match the type configured in options. Default: true.
    • allowPositionals boolean Whether this command accepts positional arguments. Default: false if strict is true, otherwise true.
    • tokens boolean Return the parsed tokens. This is useful for extending the built-in behavior, from adding additional checks through to reprocessing the tokens in different ways. Default: false.
  • Returns: Object The parsed command line arguments:

Provides a higher level API for command-line argument parsing than interacting with process.argv directly. Takes a specification for the expected arguments and returns a structured object with the parsed options and positionals.

MJS
CJS

util.parseArgs is experimental and behavior may change. Join the conversation in pkgjs/parseargs to contribute to the design.

M parseArgs tokens

Detailed parse information is available for adding custom behaviours by specifying tokens: true in the configuration. The returned tokens have properties describing:

  • all tokens
    • kind string One of 'option', 'positional', or 'option-terminator'.
    • index number Index of element in args containing token. So the source argument for a token is args[token.index].
  • option tokens
    • name string Long name of option.
    • rawName string How option used in args, like -f of --foo.
    • value string | undefined Option value specified in args. Undefined for boolean options.
    • inlineValue boolean | undefined Whether option value specified inline, like --foo=bar.
  • positional tokens
    • value string The value of the positional argument in args (i.e. args[index]).
  • option-terminator token

The returned tokens are in the order encountered in the input args. Options that appear more than once in args produce a token for each use. Short option groups like -xy expand to a token for each option. So -xxx produces three tokens.

For example to use the returned tokens to add support for a negated option like --no-color, the tokens can be reprocessed to change the value stored for the negated option.

MJS
CJS

Example usage showing negated options, and when an option is used multiple ways then last one wins.

BASH

M util.promisify(original)

Added in: v8.0.0

Takes a function following the common error-first callback style, i.e. taking an (err, value) => ... callback as the last argument, and returns a version that returns promises.

JS

Or, equivalently using async functions:

JS

If there is an original[util.promisify.custom] property present, promisify will return its value, see Custom promisified functions.

promisify() assumes that original is a function taking a callback as its final argument in all cases. If original is not a function, promisify() will throw an error. If original is a function but its last argument is not an error-first callback, it will still be passed an error-first callback as its last argument.

Using promisify() on class methods or other methods that use this may not work as expected unless handled specially:

JS

Custom promisified functions

Using the util.promisify.custom symbol one can override the return value of util.promisify():

JS

This can be useful for cases where the original function does not follow the standard format of taking an error-first callback as the last argument.

For example, with a function that takes in (foo, onSuccessCallback, onErrorCallback):

JS

If promisify.custom is defined but is not a function, promisify() will throw an error.

M util.promisify.custom

历史
版本更改
v13.12.0, v12.16.2This is now defined as a shared symbol.
v8.0.0Added in: v8.0.0

In addition to being accessible through util.promisify.custom, this symbol is registered globally and can be accessed in any environment as Symbol.for('nodejs.util.promisify.custom').

For example, with a function that takes in (foo, onSuccessCallback, onErrorCallback):

JS

M util.stripVTControlCharacters(str)

Added in: v16.11.0

Returns str with any ANSI escape codes removed.

JS

C util.TextDecoder

Added in: v8.3.0

An implementation of the WHATWG Encoding Standard TextDecoder API.

JS

WHATWG supported encodings

Per the WHATWG Encoding Standard, the encodings supported by the TextDecoder API are outlined in the tables below. For each encoding, one or more aliases may be used.

Different Node.js build configurations support different sets of encodings. (see Internationalization)

Encodings supported by default (with full ICU data)
EncodingAliases
'ibm866''866', 'cp866', 'csibm866'
'iso-8859-2''csisolatin2', 'iso-ir-101', 'iso8859-2', 'iso88592', 'iso_8859-2', 'iso_8859-2:1987', 'l2', 'latin2'
'iso-8859-3''csisolatin3', 'iso-ir-109', 'iso8859-3', 'iso88593', 'iso_8859-3', 'iso_8859-3:1988', 'l3', 'latin3'
'iso-8859-4''csisolatin4', 'iso-ir-110', 'iso8859-4', 'iso88594', 'iso_8859-4', 'iso_8859-4:1988', 'l4', 'latin4'
'iso-8859-5''csisolatincyrillic', 'cyrillic', 'iso-ir-144', 'iso8859-5', 'iso88595', 'iso_8859-5', 'iso_8859-5:1988'
'iso-8859-6''arabic', 'asmo-708', 'csiso88596e', 'csiso88596i', 'csisolatinarabic', 'ecma-114', 'iso-8859-6-e', 'iso-8859-6-i', 'iso-ir-127', 'iso8859-6', 'iso88596', 'iso_8859-6', 'iso_8859-6:1987'
'iso-8859-7''csisolatingreek', 'ecma-118', 'elot_928', 'greek', 'greek8', 'iso-ir-126', 'iso8859-7', 'iso88597', 'iso_8859-7', 'iso_8859-7:1987', 'sun_eu_greek'
'iso-8859-8''csiso88598e', 'csisolatinhebrew', 'hebrew', 'iso-8859-8-e', 'iso-ir-138', 'iso8859-8', 'iso88598', 'iso_8859-8', 'iso_8859-8:1988', 'visual'
'iso-8859-8-i''csiso88598i', 'logical'
'iso-8859-10''csisolatin6', 'iso-ir-157', 'iso8859-10', 'iso885910', 'l6', 'latin6'
'iso-8859-13''iso8859-13', 'iso885913'
'iso-8859-14''iso8859-14', 'iso885914'
'iso-8859-15''csisolatin9', 'iso8859-15', 'iso885915', 'iso_8859-15', 'l9'
'koi8-r''cskoi8r', 'koi', 'koi8', 'koi8_r'
'koi8-u''koi8-ru'
'macintosh''csmacintosh', 'mac', 'x-mac-roman'
'windows-874''dos-874', 'iso-8859-11', 'iso8859-11', 'iso885911', 'tis-620'
'windows-1250''cp1250', 'x-cp1250'
'windows-1251''cp1251', 'x-cp1251'
'windows-1252''ansi_x3.4-1968', 'ascii', 'cp1252', 'cp819', 'csisolatin1', 'ibm819', 'iso-8859-1', 'iso-ir-100', 'iso8859-1', 'iso88591', 'iso_8859-1', 'iso_8859-1:1987', 'l1', 'latin1', 'us-ascii', 'x-cp1252'
'windows-1253''cp1253', 'x-cp1253'
'windows-1254''cp1254', 'csisolatin5', 'iso-8859-9', 'iso-ir-148', 'iso8859-9', 'iso88599', 'iso_8859-9', 'iso_8859-9:1989', 'l5', 'latin5', 'x-cp1254'
'windows-1255''cp1255', 'x-cp1255'
'windows-1256''cp1256', 'x-cp1256'
'windows-1257''cp1257', 'x-cp1257'
'windows-1258''cp1258', 'x-cp1258'
'x-mac-cyrillic''x-mac-ukrainian'
'gbk''chinese', 'csgb2312', 'csiso58gb231280', 'gb2312', 'gb_2312', 'gb_2312-80', 'iso-ir-58', 'x-gbk'
'gb18030'
'big5''big5-hkscs', 'cn-big5', 'csbig5', 'x-x-big5'
'euc-jp''cseucpkdfmtjapanese', 'x-euc-jp'
'iso-2022-jp''csiso2022jp'
'shift_jis''csshiftjis', 'ms932', 'ms_kanji', 'shift-jis', 'sjis', 'windows-31j', 'x-sjis'
'euc-kr''cseuckr', 'csksc56011987', 'iso-ir-149', 'korean', 'ks_c_5601-1987', 'ks_c_5601-1989', 'ksc5601', 'ksc_5601', 'windows-949'
Encodings supported when Node.js is built with the small-icu option
EncodingAliases
'utf-8''unicode-1-1-utf-8', 'utf8'
'utf-16le''utf-16'
'utf-16be'
Encodings supported when ICU is disabled
EncodingAliases
'utf-8''unicode-1-1-utf-8', 'utf8'
'utf-16le''utf-16'

The 'iso-8859-16' encoding listed in the WHATWG Encoding Standard is not supported.

M new TextDecoder([encoding[, options]])

历史
版本更改
v11.0.0The class is now available on the global object.
v8.3.0Added in: v8.3.0
  • encoding string Identifies the encoding that this TextDecoder instance supports. Default: 'utf-8'.
  • options Object
    • fatal boolean true if decoding failures are fatal. This option is not supported when ICU is disabled (see Internationalization). Default: false.
    • ignoreBOM boolean When true, the TextDecoder will include the byte order mark in the decoded result. When false, the byte order mark will be removed from the output. This option is only used when encoding is 'utf-8', 'utf-16be', or 'utf-16le'. Default: false.

Creates a new TextDecoder instance. The encoding may specify one of the supported encodings or an alias.

The TextDecoder class is also available on the global object.

M textDecoder.decode([input[, options]])

Decodes the input and returns a string. If options.stream is true, any incomplete byte sequences occurring at the end of the input are buffered internally and emitted after the next call to textDecoder.decode().

If textDecoder.fatal is true, decoding errors that occur will result in a TypeError being thrown.

M textDecoder.encoding

The encoding supported by the TextDecoder instance.

M textDecoder.fatal

The value will be true if decoding errors result in a TypeError being thrown.

M textDecoder.ignoreBOM

The value will be true if the decoding result will include the byte order mark.

C util.TextEncoder

历史
版本更改
v11.0.0The class is now available on the global object.
v8.3.0Added in: v8.3.0

An implementation of the WHATWG Encoding Standard TextEncoder API. All instances of TextEncoder only support UTF-8 encoding.

JS

The TextEncoder class is also available on the global object.

M textEncoder.encode([input])

UTF-8 encodes the input string and returns a Uint8Array containing the encoded bytes.

M textEncoder.encodeInto(src, dest)

  • src string The text to encode.
  • dest Uint8Array The array to hold the encode result.
  • Returns: Object
    • read number The read Unicode code units of src.
    • written number The written UTF-8 bytes of dest.

UTF-8 encodes the src string to the dest Uint8Array and returns an object containing the read Unicode code units and written UTF-8 bytes.

JS

M textEncoder.encoding

The encoding supported by the TextEncoder instance. Always set to 'utf-8'.

M util.toUSVString(string)

Added in: v16.8.0, v14.18.0

Returns the string after replacing any surrogate code points (or equivalently, any unpaired surrogate code units) with the Unicode "replacement character" U+FFFD.

M util.transferableAbortController()

Added in: v18.11.0

稳定性: 1 - Experimental

Creates and returns an AbortController instance whose AbortSignal is marked as transferable and can be used with structuredClone() or postMessage().

M util.transferableAbortSignal(signal)

Added in: v18.11.0

稳定性: 1 - Experimental

Marks the given AbortSignal as transferable so that it can be used with structuredClone() and postMessage().

JS

M util.types

历史
版本更改
v15.3.0Exposed as `require('util/types')`.
v10.0.0Added in: v10.0.0

util.types provides type checks for different kinds of built-in objects. Unlike instanceof or Object.prototype.toString.call(value), these checks do not inspect properties of the object that are accessible from JavaScript (like their prototype), and usually have the overhead of calling into C++.

The result generally does not make any guarantees about what kinds of properties or behavior a value exposes in JavaScript. They are primarily useful for addon developers who prefer to do type checking in JavaScript.

The API is accessible via require('node:util').types or require('node:util/types').

M util.types.isAnyArrayBuffer(value)

Added in: v10.0.0

Returns true if the value is a built-in ArrayBuffer or SharedArrayBuffer instance.

See also util.types.isArrayBuffer() and util.types.isSharedArrayBuffer().

JS

M util.types.isArrayBufferView(value)

Added in: v10.0.0

Returns true if the value is an instance of one of the ArrayBuffer views, such as typed array objects or DataView. Equivalent to ArrayBuffer.isView().

JS

M util.types.isArgumentsObject(value)

Added in: v10.0.0

Returns true if the value is an arguments object.

JS

M util.types.isArrayBuffer(value)

Added in: v10.0.0

Returns true if the value is a built-in ArrayBuffer instance. This does not include SharedArrayBuffer instances. Usually, it is desirable to test for both; See util.types.isAnyArrayBuffer() for that.

JS

M util.types.isAsyncFunction(value)

Added in: v10.0.0

Returns true if the value is an async function. This only reports back what the JavaScript engine is seeing; in particular, the return value may not match the original source code if a transpilation tool was used.

JS

M util.types.isBigInt64Array(value)

Added in: v10.0.0

Returns true if the value is a BigInt64Array instance.

JS

M util.types.isBigUint64Array(value)

Added in: v10.0.0

Returns true if the value is a BigUint64Array instance.

JS

M util.types.isBooleanObject(value)

Added in: v10.0.0

Returns true if the value is a boolean object, e.g. created by new Boolean().

JS

M util.types.isBoxedPrimitive(value)

Added in: v10.11.0

Returns true if the value is any boxed primitive object, e.g. created by new Boolean(), new String() or Object(Symbol()).

For example:

JS

M util.types.isCryptoKey(value)

Added in: v16.2.0

Returns true if value is a CryptoKey, false otherwise.

M util.types.isDataView(value)

Added in: v10.0.0

Returns true if the value is a built-in DataView instance.

JS

See also ArrayBuffer.isView().

M util.types.isDate(value)

Added in: v10.0.0

Returns true if the value is a built-in Date instance.

JS

M util.types.isExternal(value)

Added in: v10.0.0

Returns true if the value is a native External value.

A native External value is a special type of object that contains a raw C++ pointer (void*) for access from native code, and has no other properties. Such objects are created either by Node.js internals or native addons. In JavaScript, they are frozen objects with a null prototype.

C
JS

For further information on napi_create_external, refer to napi_create_external().

M util.types.isFloat32Array(value)

Added in: v10.0.0

Returns true if the value is a built-in Float32Array instance.

JS

M util.types.isFloat64Array(value)

Added in: v10.0.0

Returns true if the value is a built-in Float64Array instance.

JS

M util.types.isGeneratorFunction(value)

Added in: v10.0.0

Returns true if the value is a generator function. This only reports back what the JavaScript engine is seeing; in particular, the return value may not match the original source code if a transpilation tool was used.

JS

M util.types.isGeneratorObject(value)

Added in: v10.0.0

Returns true if the value is a generator object as returned from a built-in generator function. This only reports back what the JavaScript engine is seeing; in particular, the return value may not match the original source code if a transpilation tool was used.

JS

M util.types.isInt8Array(value)

Added in: v10.0.0

Returns true if the value is a built-in Int8Array instance.

JS

M util.types.isInt16Array(value)

Added in: v10.0.0

Returns true if the value is a built-in Int16Array instance.

JS

M util.types.isInt32Array(value)

Added in: v10.0.0

Returns true if the value is a built-in Int32Array instance.

JS

M util.types.isKeyObject(value)

Added in: v16.2.0

Returns true if value is a KeyObject, false otherwise.

M util.types.isMap(value)

Added in: v10.0.0

Returns true if the value is a built-in Map instance.

JS

M util.types.isMapIterator(value)

Added in: v10.0.0

Returns true if the value is an iterator returned for a built-in Map instance.

JS

M util.types.isModuleNamespaceObject(value)

Added in: v10.0.0

Returns true if the value is an instance of a Module Namespace Object.

JS

M util.types.isNativeError(value)

Added in: v10.0.0

Returns true if the value is an instance of a built-in Error type.

JS

M util.types.isNumberObject(value)

Added in: v10.0.0

Returns true if the value is a number object, e.g. created by new Number().

JS

M util.types.isPromise(value)

Added in: v10.0.0

Returns true if the value is a built-in Promise.

JS

M util.types.isProxy(value)

Added in: v10.0.0

Returns true if the value is a Proxy instance.

JS

M util.types.isRegExp(value)

Added in: v10.0.0

Returns true if the value is a regular expression object.

JS

M util.types.isSet(value)

Added in: v10.0.0

Returns true if the value is a built-in Set instance.

JS

M util.types.isSetIterator(value)

Added in: v10.0.0

Returns true if the value is an iterator returned for a built-in Set instance.

JS

M util.types.isSharedArrayBuffer(value)

Added in: v10.0.0

Returns true if the value is a built-in SharedArrayBuffer instance. This does not include ArrayBuffer instances. Usually, it is desirable to test for both; See util.types.isAnyArrayBuffer() for that.

JS

M util.types.isStringObject(value)

Added in: v10.0.0

Returns true if the value is a string object, e.g. created by new String().

JS

M util.types.isSymbolObject(value)

Added in: v10.0.0

Returns true if the value is a symbol object, created by calling Object() on a Symbol primitive.

JS

M util.types.isTypedArray(value)

Added in: v10.0.0

Returns true if the value is a built-in TypedArray instance.

JS

See also ArrayBuffer.isView().

M util.types.isUint8Array(value)

Added in: v10.0.0

Returns true if the value is a built-in Uint8Array instance.

JS

M util.types.isUint8ClampedArray(value)

Added in: v10.0.0

Returns true if the value is a built-in Uint8ClampedArray instance.

JS

M util.types.isUint16Array(value)

Added in: v10.0.0

Returns true if the value is a built-in Uint16Array instance.

JS

M util.types.isUint32Array(value)

Added in: v10.0.0

Returns true if the value is a built-in Uint32Array instance.

JS

M util.types.isWeakMap(value)

Added in: v10.0.0

Returns true if the value is a built-in WeakMap instance.

JS

M util.types.isWeakSet(value)

Added in: v10.0.0

Returns true if the value is a built-in WeakSet instance.

JS

M util.types.isWebAssemblyCompiledModule(value)

Deprecated in: v14.0.0

稳定性: 0 - Deprecated: Use `value instanceof WebAssembly.Module` instead.

Returns true if the value is a built-in WebAssembly.Module instance.

JS

Deprecated APIs

The following APIs are deprecated and should no longer be used. Existing applications and modules should be updated to find alternative approaches.

M util._extend(target, source)

Deprecated in: v6.0.0

稳定性: 0 - Deprecated: Use `Object.assign()` instead.

The util._extend() method was never intended to be used outside of internal Node.js modules. The community found and used it anyway.

It is deprecated and should not be used in new code. JavaScript comes with very similar built-in functionality through Object.assign().

M util.isArray(object)

Deprecated in: v4.0.0

稳定性: 0 - Deprecated: Use `Array.isArray()` instead.

Alias for Array.isArray().

Returns true if the given object is an Array. Otherwise, returns false.

JS

M util.isBoolean(object)

Deprecated in: v4.0.0

稳定性: 0 - Deprecated: Use `typeof value === 'boolean'` instead.

Returns true if the given object is a Boolean. Otherwise, returns false.

JS

M util.isBuffer(object)

Deprecated in: v4.0.0

稳定性: 0 - Deprecated: Use `Buffer.isBuffer()` instead.

Returns true if the given object is a Buffer. Otherwise, returns false.

JS

M util.isDate(object)

Deprecated in: v4.0.0

稳定性: 0 - Deprecated: Use `util.types.isDate()` instead.

Returns true if the given object is a Date. Otherwise, returns false.

JS

M util.isError(object)

Deprecated in: v4.0.0

稳定性: 0 - Deprecated: Use `util.types.isNativeError()` instead.

Returns true if the given object is an Error. Otherwise, returns false.

JS

This method relies on Object.prototype.toString() behavior. It is possible to obtain an incorrect result when the object argument manipulates @@toStringTag.

JS

M util.isFunction(object)

Deprecated in: v4.0.0

稳定性: 0 - Deprecated: Use `typeof value === 'function'` instead.

Returns true if the given object is a Function. Otherwise, returns false.

JS

M util.isNull(object)

Deprecated in: v4.0.0

稳定性: 0 - Deprecated: Use `value === null` instead.

Returns true if the given object is strictly null. Otherwise, returns false.

JS

M util.isNullOrUndefined(object)

Deprecated in: v4.0.0

稳定性: 0 - Deprecated: Use `value === undefined || value === null` instead.

Returns true if the given object is null or undefined. Otherwise, returns false.

JS

M util.isNumber(object)

Deprecated in: v4.0.0

稳定性: 0 - Deprecated: Use `typeof value === 'number'` instead.

Returns true if the given object is a Number. Otherwise, returns false.

JS

M util.isObject(object)

Deprecated in: v4.0.0

稳定性: 0 - Deprecated: Use `value !== null && typeof value === 'object'` instead.

Returns true if the given object is strictly an Object and not a Function (even though functions are objects in JavaScript). Otherwise, returns false.

JS

M util.isPrimitive(object)

Deprecated in: v4.0.0

稳定性: 0 - Deprecated: Use `(typeof value !== 'object' && typeof value !== 'function') || value === null` > instead.

Returns true if the given object is a primitive type. Otherwise, returns false.

JS

M util.isRegExp(object)

Deprecated in: v4.0.0

稳定性: 0 - Deprecated

Returns true if the given object is a RegExp. Otherwise, returns false.

JS

M util.isString(object)

Deprecated in: v4.0.0

稳定性: 0 - Deprecated: Use `typeof value === 'string'` instead.

Returns true if the given object is a string. Otherwise, returns false.

JS

M util.isSymbol(object)

Deprecated in: v4.0.0

稳定性: 0 - Deprecated: Use `typeof value === 'symbol'` instead.

Returns true if the given object is a Symbol. Otherwise, returns false.

JS

M util.isUndefined(object)

Deprecated in: v4.0.0

稳定性: 0 - Deprecated: Use `value === undefined` instead.

Returns true if the given object is undefined. Otherwise, returns false.

JS

M util.log(string)

Deprecated in: v6.0.0

稳定性: 0 - Deprecated: Use a third party module instead.

The util.log() method prints the given string to stdout with an included timestamp.

JS