Util
目录
- util.callbackify(original)
- util.debuglog(section[, callback])
- util.debug(section)
- util.deprecate(fn, msg[, code])
- util.format(format[, ...args])
- util.formatWithOptions(inspectOptions, format[, ...args])
- util.getSystemErrorName(err)
- util.getSystemErrorMap()
- util.inherits(constructor, superConstructor)
- util.inspect(object[, options])
- util.inspect(object[, showHidden[, depth[, colors]]])
- util.isDeepStrictEqual(val1, val2)
- Class: util.MIMEType
- util.parseArgs([config])
- util.promisify(original)
- util.stripVTControlCharacters(str)
- Class: util.TextDecoder
- Class: util.TextEncoder
- util.toUSVString(string)
- util.transferableAbortController()
- util.transferableAbortSignal(signal)
- util.types
- util.types.isAnyArrayBuffer(value)
- util.types.isArrayBufferView(value)
- util.types.isArgumentsObject(value)
- util.types.isArrayBuffer(value)
- util.types.isAsyncFunction(value)
- util.types.isBigInt64Array(value)
- util.types.isBigUint64Array(value)
- util.types.isBooleanObject(value)
- util.types.isBoxedPrimitive(value)
- util.types.isCryptoKey(value)
- util.types.isDataView(value)
- util.types.isDate(value)
- util.types.isExternal(value)
- util.types.isFloat32Array(value)
- util.types.isFloat64Array(value)
- util.types.isGeneratorFunction(value)
- util.types.isGeneratorObject(value)
- util.types.isInt8Array(value)
- util.types.isInt16Array(value)
- util.types.isInt32Array(value)
- util.types.isKeyObject(value)
- util.types.isMap(value)
- util.types.isMapIterator(value)
- util.types.isModuleNamespaceObject(value)
- util.types.isNativeError(value)
- util.types.isNumberObject(value)
- util.types.isPromise(value)
- util.types.isProxy(value)
- util.types.isRegExp(value)
- util.types.isSet(value)
- util.types.isSetIterator(value)
- util.types.isSharedArrayBuffer(value)
- util.types.isStringObject(value)
- util.types.isSymbolObject(value)
- util.types.isTypedArray(value)
- util.types.isUint8Array(value)
- util.types.isUint8ClampedArray(value)
- util.types.isUint16Array(value)
- util.types.isUint32Array(value)
- util.types.isWeakMap(value)
- util.types.isWeakSet(value)
- util.types.isWebAssemblyCompiledModule(value)
- Deprecated APIs
- util._extend(target, source)
- util.isArray(object)
- util.isBoolean(object)
- util.isBuffer(object)
- util.isDate(object)
- util.isError(object)
- util.isFunction(object)
- util.isNull(object)
- util.isNullOrUndefined(object)
- util.isNumber(object)
- util.isObject(object)
- util.isPrimitive(object)
- util.isRegExp(object)
- util.isString(object)
- util.isSymbol(object)
- util.isUndefined(object)
- util.log(string)
Added in: v0.10.0
源代码: lib/util.js
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
sectionstringA string identifying the portion of the application for which thedebuglogfunction is being created.callbackFunctionA callback invoked the first time the logging function is called with a function argument that is a more optimized logging function.- Returns:
FunctionThe 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.0 | Deprecation warnings are only emitted once for each code. |
| v0.8.0 | Added in: v0.8.0 |
fnFunctionThe function that is being deprecated.msgstringA warning message to display when the deprecated function is invoked.codestringA deprecation code. See the list of deprecated APIs for a list of codes.- Returns:
FunctionThe 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.0 | The `%c` specifier is ignored now. |
| v12.0.0 | The `format` argument is now only taken as such if it actually contains format specifiers. |
| v12.0.0 | If 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.0 | The `%d`, `%f`, and `%i` specifiers now support Symbols properly. |
| v11.4.0 | The `%o` specifier's `depth` has default depth of 4 again. |
| v11.0.0 | The `%o` specifier's `depth` option will now fall back to the default depth. |
| v10.12.0 | The `%d` and `%i` specifiers now support BigInt. |
| v8.4.0 | The `%o` and `%O` specifiers are supported now. |
| v0.5.3 | Added in: v0.5.3 |
formatstringAprintf-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:Stringwill be used to convert all values exceptBigInt,Objectand-0.BigIntvalues will be represented with annand Objects that have no user definedtoStringfunction are inspected usingutil.inspect()with options{ depth: 0, colors: false, compact: 3 }.%d:Numberwill be used to convert all values exceptBigIntandSymbol.%i:parseInt(value, 10)is used for all values exceptBigIntandSymbol.%f:parseFloat(value)is used for all values expectSymbol.%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 toutil.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 toutil.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:
stringThe 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:
Map
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.0 | The `constructor` parameter can refer to an ES6 class now. |
| v0.3.0 | Added in: v0.3.0 |
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.0 | The `numericSeparator` option is supported now. |
| v16.18.0 | add support for `maxArrayLength` when inspecting `Set` and `Map`. |
| v14.6.0, v12.19.0 | If `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.0 | The `maxStringLength` option is supported now. |
| v13.5.0, v12.16.0 | User defined prototype properties are inspected in case `showHidden` is `true`. |
| v13.0.0 | Circular references now include a marker to the reference. |
| v12.0.0 | The `compact` options default is changed to `3` and the `breakLength` options default is changed to `80`. |
| v12.0.0 | Internal properties no longer appear in the context argument of a custom inspection function. |
| v11.11.0 | The `compact` option accepts numbers for a new output mode. |
| v11.7.0 | ArrayBuffers now also show their binary contents. |
| v11.5.0 | The `getters` option is supported now. |
| v11.4.0 | The `depth` default changed back to `2`. |
| v11.0.0 | The `depth` default changed to `20`. |
| v11.0.0 | The inspection output is now limited to about 128 MiB. Data above that size will not be fully inspected. |
| v10.12.0 | The `sorted` option is supported now. |
| v10.6.0 | Inspecting linked lists and similar objects is now possible up to the maximum call stack size. |
| v10.0.0 | The `WeakMap` and `WeakSet` entries can now be inspected as well. |
| v9.9.0 | The `compact` option is supported now. |
| v6.6.0 | Custom inspection functions can now return `this`. |
| v6.3.0 | The `breakLength` option is supported now. |
| v6.1.0 | The `maxArrayLength` option is supported now; in particular, long arrays are truncated by default. |
| v6.1.0 | The `showProxy` option is supported now. |
| v0.3.0 | Added in: v0.3.0 |
objectanyAny JavaScript primitive orObject.optionsObjectshowHiddenbooleanIftrue,object's non-enumerable symbols and properties are included in the formatted result.WeakMapandWeakSetentries are also included as well as user defined prototype properties (excluding method properties). Default:false.depthnumberSpecifies the number of times to recurse while formattingobject. This is useful for inspecting large objects. To recurse up to the maximum call stack size passInfinityornull. Default:2.colorsbooleanIftrue, the output is styled with ANSI color codes. Colors are customizable. See Customizingutil.inspectcolors. Default:false.customInspectbooleanIffalse,[util.inspect.custom](depth, opts, inspect)functions are not invoked. Default:true.showProxybooleanIftrue,Proxyinspection includes thetargetandhandlerobjects. Default:false.maxArrayLengthintegerSpecifies the maximum number ofArray,TypedArray,Map,Set,WeakMap, andWeakSetelements to include when formatting. Set tonullorInfinityto show all elements. Set to0or negative to show no elements. Default:100.maxStringLengthintegerSpecifies the maximum number of characters to include when formatting. Set tonullorInfinityto show all elements. Set to0or negative to show no characters. Default:10000.breakLengthintegerThe length at which input values are split across multiple lines. Set toInfinityto format the input as a single line (in combination withcompactset totrueor any number >=1). Default:80.compactboolean|integerSetting this tofalsecauses each object key to be displayed on a new line. It will break on new lines in text that is longer thanbreakLength. If set to a number, the mostninner elements are united on a single line as long as all properties fit intobreakLength. Short array elements are also grouped together. For more information, see the example below. Default:3.sortedboolean|FunctionIf set totrueor a function, all properties of an object, andSetandMapentries are sorted in the resulting string. If set totruethe default sort is used. If set to a function, it is used as a compare function.gettersboolean|stringIf set totrue, 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.numericSeparatorbooleanIf set totrue, an underscore is used to separate every three digits in all bigints and numbers. Default:false.
- Returns:
stringThe representation ofobject.
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:yellowboolean:yellowdate:magentamodule:underlinename: (no styling)null:boldnumber:yellowregexp:redspecial:cyan(e.g.,Proxies)string:greensymbol:greenundefined: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
blackredgreenyellowbluemagentacyanwhitegray(alias:grey,blackBright)redBrightgreenBrightyellowBrightblueBrightmagentaBrightcyanBrightwhiteBright
Background colors
bgBlackbgRedbgGreenbgYellowbgBluebgMagentabgCyanbgWhitebgGray(alias:bgGrey,bgBlackBright)bgRedBrightbgGreenBrightbgYellowBrightbgBlueBrightbgMagentaBrightbgCyanBrightbgWhiteBright
Custom inspection functions on objects
历史
| 版本 | 更改 |
|---|---|
| v17.3.0, v16.14.0 | The inspect argument is added for more interoperability. |
| v0.1.97 | Added 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.0 | This is now defined as a shared symbol. |
| v6.6.0 | Added in: v6.6.0 |
symbolthat 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
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)
inputstringThe 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()
- Returns:
string
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()
- Returns:
string
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)
namestring
Remove all name-value pairs whose name is name.
M mimeParams.entries()
- Returns:
Iterator
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)
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:
Iterator
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:
Iterator
Returns an iterator over the values of each name-value pair.
M mimeParams[@@iterator]()
- Returns:
Iterator
Alias for mimeParams.entries().
MJS
CJS
M util.parseArgs([config])
历史
| 版本 | 更改 |
|---|---|
| v18.11.0 | Add support for default values in input `config`. |
| v18.7.0, v16.17.0 | add support for returning detailed parse information using `tokens` in input `config` and returned properties. |
| v18.3.0, v16.17.0 | Added in: v18.3.0, v16.17.0 |
configObjectUsed to provide arguments for parsing and to configure the parser.configsupports the following properties:argsstring[] array of argument strings. Default:process.argvwithexecPathandfilenameremoved.optionsObjectUsed to describe arguments known to the parser. Keys ofoptionsare the long names of options and values are anObjectaccepting the following properties:typestringType of argument, which must be eitherbooleanorstring.multiplebooleanWhether this option can be provided multiple times. Iftrue, all values will be collected in an array. Iffalse, values for the option are last-wins. Default:false.shortstringA single character alias for the option.defaultstring|booleanThe default option value when it is not set by args. It must be of the same type as thetypeproperty. Whenmultipleistrue, it must be an array.
strictbooleanShould an error be thrown when unknown arguments are encountered, or when arguments are passed that do not match thetypeconfigured inoptions. Default:true.allowPositionalsbooleanWhether this command accepts positional arguments. Default:falseifstrictistrue, otherwisetrue.tokensbooleanReturn 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:
ObjectThe parsed command line arguments:valuesObjectA mapping of parsed option names with theirstringorbooleanvalues.positionalsstring[] Positional arguments.tokensundefinedSee parseArgs tokens section. Only returned ifconfigincludestokens: true.
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
- option tokens
- positional tokens
valuestringThe 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.2 | This is now defined as a shared symbol. |
| v8.0.0 | Added in: v8.0.0 |
symbolthat can be used to declare custom promisified variants of functions, see Custom promisified functions.
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)
| Encoding | Aliases |
|---|---|
'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
| Encoding | Aliases |
|---|---|
'utf-8' | 'unicode-1-1-utf-8', 'utf8' |
'utf-16le' | 'utf-16' |
'utf-16be' |
Encodings supported when ICU is disabled
| Encoding | Aliases |
|---|---|
'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.0 | The class is now available on the global object. |
| v8.3.0 | Added in: v8.3.0 |
encodingstringIdentifies theencodingthat thisTextDecoderinstance supports. Default:'utf-8'.optionsObjectfatalbooleantrueif decoding failures are fatal. This option is not supported when ICU is disabled (see Internationalization). Default:false.ignoreBOMbooleanWhentrue, theTextDecoderwill include the byte order mark in the decoded result. Whenfalse, the byte order mark will be removed from the output. This option is only used whenencodingis'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]])
inputArrayBuffer|DataView|TypedArrayAnArrayBuffer,DataView, orTypedArrayinstance containing the encoded data.optionsObjectstreambooleantrueif additional chunks of data are expected. Default:false.
- Returns:
string
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.0 | The class is now available on the global object. |
| v8.3.0 | Added 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])
inputstringThe text to encode. Default: an empty string.- Returns:
Uint8Array
UTF-8 encodes the input string and returns a Uint8Array containing the
encoded bytes.
M textEncoder.encodeInto(src, dest)
srcstringThe text to encode.destUint8ArrayThe array to hold the encode result.- Returns:
Object
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
stringstring
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
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
signalAbortSignal- Returns:
AbortSignal
Marks the given AbortSignal as transferable so that it can be used with
structuredClone() and postMessage().
JS
M util.types
历史
| 版本 | 更改 |
|---|---|
| v15.3.0 | Exposed as `require('util/types')`. |
| v10.0.0 | Added 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
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
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
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
Returns true if the given object is a Boolean. Otherwise, returns false.
JS
M util.isBuffer(object)
Deprecated in: v4.0.0
Returns true if the given object is a Buffer. Otherwise, returns false.
JS
M util.isDate(object)
Deprecated in: v4.0.0
Returns true if the given object is a Date. Otherwise, returns false.
JS
M util.isError(object)
Deprecated in: v4.0.0
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
Returns true if the given object is a Function. Otherwise, returns
false.
JS
M util.isNull(object)
Deprecated in: v4.0.0
Returns true if the given object is strictly null. Otherwise, returns
false.
JS
M util.isNullOrUndefined(object)
Deprecated in: v4.0.0
Returns true if the given object is null or undefined. Otherwise,
returns false.
JS
M util.isNumber(object)
Deprecated in: v4.0.0
Returns true if the given object is a Number. Otherwise, returns false.
JS
M util.isObject(object)
Deprecated in: v4.0.0
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
Returns true if the given object is a primitive type. Otherwise, returns
false.
JS
M util.isRegExp(object)
Deprecated in: v4.0.0
Returns true if the given object is a RegExp. Otherwise, returns false.
JS
M util.isString(object)
Deprecated in: v4.0.0
Returns true if the given object is a string. Otherwise, returns false.
JS
M util.isSymbol(object)
Deprecated in: v4.0.0
Returns true if the given object is a Symbol. Otherwise, returns false.
JS
M util.isUndefined(object)
Deprecated in: v4.0.0
Returns true if the given object is undefined. Otherwise, returns false.
JS
M util.log(string)
Deprecated in: v6.0.0
stringstring
The util.log() method prints the given string to stdout with an included
timestamp.
JS