util
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:
import util from 'node:util';
Usage in Deno
import * as mod from "node:util";
Classes
An implementation of the WHATWG Encoding Standard TextDecoder API.
An implementation of the WHATWG Encoding Standard TextEncoder API. All
instances of TextEncoder only support UTF-8 encoding.
Functions
Listens to abort event on the provided signal and returns a promise that resolves when the signal is aborted.
If resource is provided, it weakly references the operation's associated object,
so if resource is garbage collected before the signal aborts,
then returned promise shall remain pending.
This prevents memory leaks in long-running or non-cancelable operations.
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.
The util.debuglog() method is used to create a function that conditionally
writes debug messages to stderr based on the existence of the NODE_DEBUGenvironment 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.
The util.deprecate() method wraps fn (which may be a function or class) in
such a way that it is marked as deprecated.
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:
Returns the string message for a numeric error code that comes from a Node.js API. The mapping between error codes and string messages is platform-dependent.
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.
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.
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.
Returns true if there is deep strict equality between val1 and val2.
Otherwise, returns false.
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.
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.
Returns the string after replacing any surrogate code points
(or equivalently, any unpaired surrogate code units) with the
Unicode "replacement character" U+FFFD.
Returns true if the value is a built-in ArrayBuffer or
SharedArrayBuffer instance.
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.
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().
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.
Returns true if the value is a BigInt object, e.g. created
by Object(BigInt(123)).
Returns true if the value is any boxed primitive object, e.g. created
by new Boolean(), new String() or Object(Symbol()).
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.
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.
Returns true if the value was returned by the constructor of a built-in Error type.
Returns true if the value is a symbol object, created
by calling Object() on a Symbol primitive.
Returns true if the given object is strictly an Objectand not aFunction (even though functions are objects in JavaScript).
Otherwise, returns false.
Interfaces
Namespaces
Type Aliases
Variables
class MIMEParams
Usage in Deno
import { MIMEParams } from "node:util";
This symbol is currently not supported.
The MIMEParams API provides read and write access to the parameters of a MIMEType.
Methods #
#[Symbol.iterator](): Iterator<[string, string]> Returns an iterator over each of the name-value pairs in the parameters.
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.
Returns the value of the first name-value pair whose name is name. If there
are no such pairs, null is returned.
Returns true if there is at least one name-value pair whose name is name.
Returns an iterator over the names of each name-value pair.
import { MIMEType } from 'node:util';
const { params } = new MIMEType('text/plain;foo=0;bar=1');
for (const name of params.keys()) {
console.log(name);
}
// Prints:
// foo
// bar
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.
import { MIMEType } from 'node:util';
const { params } = new MIMEType('text/plain;foo=0;bar=1');
params.set('foo', 'def');
params.set('baz', 'xyz');
console.log(params.toString());
// Prints: foo=def;bar=1;baz=xyz
class MIMEType
Usage in Deno
import { MIMEType } from "node:util";
This symbol is currently not supported.
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.
Constructors #
#MIMEType(input: string | { toString: () => string; }) Creates a new MIMEType object by parsing the input.
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.
Properties #
Gets the essence of the MIME. This property is read only.
Use mime.type or mime.subtype to alter the MIME.
import { MIMEType } from 'node:util';
const myMIME = new MIMEType('text/javascript;key=value');
console.log(myMIME.essence);
// Prints: text/javascript
myMIME.type = 'application';
console.log(myMIME.essence);
// Prints: application/javascript
console.log(String(myMIME));
// Prints: application/javascript;key=value
#params: MIMEParams Gets the MIMEParams object representing the
parameters of the MIME. This property is read-only. See MIMEParams documentation for details.
Gets and sets the subtype portion of the MIME.
import { MIMEType } from 'node:util';
const myMIME = new MIMEType('text/ecmascript');
console.log(myMIME.subtype);
// Prints: ecmascript
myMIME.subtype = 'javascript';
console.log(myMIME.subtype);
// Prints: javascript
console.log(String(myMIME));
// Prints: text/javascript
Gets and sets the type portion of the MIME.
import { MIMEType } from 'node:util';
const myMIME = new MIMEType('text/javascript');
console.log(myMIME.type);
// Prints: text
myMIME.type = 'application';
console.log(myMIME.type);
// Prints: application
console.log(String(myMIME));
// Prints: application/javascript
Methods #
class TextDecoder
Usage in Deno
import { TextDecoder } from "node:util";
An implementation of the WHATWG Encoding Standard TextDecoder API.
const decoder = new TextDecoder();
const u8arr = new Uint8Array([72, 101, 108, 108, 111]);
console.log(decoder.decode(u8arr)); // Hello
Constructors #
#TextDecoder(encoding?: string,options?: { fatal?: boolean | undefined; ignoreBOM?: boolean | undefined; },) Properties #
Methods #
#decode(input?: ArrayBufferView
| ArrayBuffer
| null,options?: { stream?: boolean | undefined; },): 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.
variable TextDecoder
TextDecoder class is a global reference for import { TextDecoder } from 'node:util'
https://nodejs.org/api/globals.html#textdecoder
Type #
globalThis extends { onmessage: any; TextDecoder: infer TextDecoder; } ? TextDecoder : _TextDecoder class TextEncoder
Usage in Deno
import { TextEncoder } from "node:util";
An implementation of the WHATWG Encoding Standard TextEncoder API. All
instances of TextEncoder only support UTF-8 encoding.
const encoder = new TextEncoder();
const uint8array = encoder.encode('this is some data');
The TextEncoder class is also available on the global object.
Properties #
Methods #
UTF-8 encodes the input string and returns a Uint8Array containing the
encoded bytes.
#encodeInto(src: string,dest: Uint8Array,): EncodeIntoResult 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.
const encoder = new TextEncoder();
const src = 'this is some data';
const dest = new Uint8Array(10);
const { read, written } = encoder.encodeInto(src, dest);
variable TextEncoder
TextEncoder class is a global reference for import { TextEncoder } from 'node:util'
https://nodejs.org/api/globals.html#textencoder
Type #
globalThis extends { onmessage: any; TextEncoder: infer TextEncoder; } ? TextEncoder : _TextEncoder function aborted
Usage in Deno
import { aborted } from "node:util";
#aborted(signal: AbortSignal,resource: any,): Promise<void>Listens to abort event on the provided signal and returns a promise that resolves when the signal is aborted.
If resource is provided, it weakly references the operation's associated object,
so if resource is garbage collected before the signal aborts,
then returned promise shall remain pending.
This prevents memory leaks in long-running or non-cancelable operations.
import { aborted } from 'node:util';
// Obtain an object with an abortable signal, like a custom resource or operation.
const dependent = obtainSomethingAbortable();
// Pass `dependent` as the resource, indicating the promise should only resolve
// if `dependent` is still in memory when the signal is aborted.
aborted(dependent.signal, dependent).then(() => {
// This code runs when `dependent` is aborted.
console.log('Dependent resource was aborted.');
});
// Simulate an event that triggers the abort.
dependent.on('event', () => {
dependent.abort(); // This will cause the `aborted` promise to resolve.
});
Parameters #
#signal: AbortSignal #resource: any Any non-null object tied to the abortable operation and held weakly.
If resource is garbage collected before the signal aborts, the promise remains pending,
allowing Node.js to stop tracking it.
This helps prevent memory leaks in long-running or non-cancelable operations.
Return Type #
Promise<void> function callbackify
Usage in Deno
import { callbackify } from "node:util";
Overload 1
#callbackify(fn: () => Promise<void>): (callback: (err: ErrnoException) => void) => voidTakes 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.
import util from 'node:util';
async function fn() {
return 'hello world';
}
const callbackFunction = util.callbackify(fn);
callbackFunction((err, ret) => {
if (err) throw err;
console.log(ret);
});
Will print:
hello world
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.
function fn() {
return Promise.reject(null);
}
const callbackFunction = util.callbackify(fn);
callbackFunction((err, ret) => {
// When the Promise was rejected with `null` it is wrapped with an Error and
// the original value is stored in `reason`.
err && Object.hasOwn(err, 'reason') && err.reason === null; // true
});
Parameters #
#fn: () => Promise<void> An async function
Return Type #
(callback: (err: ErrnoException) => void) => void a callback style function
Overload 2
#callbackify<TResult>(fn: () => Promise<TResult>): (callback: (err: ErrnoException,result: TResult,) => void) => voidOverload 3
#callbackify<T1>(fn: (arg1: T1) => Promise<void>): (arg1: T1,callback: (err: ErrnoException) => void,) => voidOverload 4
#callbackify<T1,TResult,>(fn: (arg1: T1) => Promise<TResult>): (arg1: T1,callback: (err: ErrnoException,result: TResult,) => void,) => voidOverload 5
#callbackify<T1,T2,>(fn: (arg1: T1,arg2: T2,) => Promise<void>): (arg1: T1,arg2: T2,callback: (err: ErrnoException) => void,) => voidOverload 6
#callbackify<T1,T2,TResult,>(fn: (arg1: T1,arg2: T2,) => Promise<TResult>): (arg1: T1,arg2: T2,callback: (err: ErrnoException | null,result: TResult,) => void,) => voidOverload 7
#callbackify<T1,T2,T3,>(fn: (arg1: T1,arg2: T2,arg3: T3,) => Promise<void>): (arg1: T1,arg2: T2,arg3: T3,callback: (err: ErrnoException) => void,) => voidOverload 8
#callbackify<T1,T2,T3,TResult,>(fn: (arg1: T1,arg2: T2,arg3: T3,) => Promise<TResult>): (arg1: T1,arg2: T2,arg3: T3,callback: (err: ErrnoException | null,result: TResult,) => void,) => voidOverload 9
#callbackify<T1,T2,T3,T4,>(fn: (arg1: T1,arg2: T2,arg3: T3,arg4: T4,) => Promise<void>): (arg1: T1,arg2: T2,arg3: T3,arg4: T4,callback: (err: ErrnoException) => void,) => voidOverload 10
#callbackify<T1,T2,T3,T4,TResult,>(fn: (arg1: T1,arg2: T2,arg3: T3,arg4: T4,) => Promise<TResult>): (arg1: T1,arg2: T2,arg3: T3,arg4: T4,callback: (err: ErrnoException | null,result: TResult,) => void,) => voidOverload 11
#callbackify<T1,T2,T3,T4,T5,>(fn: (arg1: T1,arg2: T2,arg3: T3,arg4: T4,arg5: T5,) => Promise<void>): (arg1: T1,arg2: T2,arg3: T3,arg4: T4,arg5: T5,callback: (err: ErrnoException) => void,) => voidOverload 12
#callbackify<T1,T2,T3,T4,T5,TResult,>(fn: (arg1: T1,arg2: T2,arg3: T3,arg4: T4,arg5: T5,) => Promise<TResult>): (arg1: T1,arg2: T2,arg3: T3,arg4: T4,arg5: T5,callback: (err: ErrnoException | null,result: TResult,) => void,) => voidOverload 13
#callbackify<T1,T2,T3,T4,T5,T6,>(fn: (arg1: T1,arg2: T2,arg3: T3,arg4: T4,arg5: T5,arg6: T6,) => Promise<void>): (arg1: T1,arg2: T2,arg3: T3,arg4: T4,arg5: T5,arg6: T6,callback: (err: ErrnoException) => void,) => voidOverload 14
#callbackify<T1,T2,T3,T4,T5,T6,TResult,>(fn: (arg1: T1,arg2: T2,arg3: T3,arg4: T4,arg5: T5,arg6: T6,) => Promise<TResult>): (arg1: T1,arg2: T2,arg3: T3,arg4: T4,arg5: T5,arg6: T6,callback: (err: ErrnoException | null,result: TResult,) => void,) => voidfunction debuglog
Usage in Deno
import { debuglog } from "node:util";
#debuglog(section: string,callback?: (fn: DebugLoggerFunction) => void,): DebugLoggerThe util.debuglog() method is used to create a function that conditionally
writes debug messages to stderr based on the existence of the NODE_DEBUGenvironment 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.
import util from 'node:util';
const debuglog = util.debuglog('foo');
debuglog('hello from foo [%d]', 123);
If this program is run with NODE_DEBUG=foo in the environment, then
it will output something like:
FOO 3245: hello from foo [123]
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:
import util from 'node:util';
const debuglog = util.debuglog('foo-bar');
debuglog('hi there, it\'s foo-bar [%d]', 2333);
if it is run with NODE_DEBUG=foo* in the environment, then it will output
something like:
FOO-BAR 3257: hi there, it's foo-bar [2333]
Multiple comma-separated section names may be specified in the NODE_DEBUGenvironment 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.
import util from 'node:util';
let debuglog = util.debuglog('internals', (debug) => {
// Replace with a logging function that optimizes out
// testing if the section is enabled
debuglog = debug;
});
Parameters #
#section: string A string identifying the portion of the application for which the debuglog function is being created.
#callback: (fn: DebugLoggerFunction) => void A callback invoked the first time the logging function is called with a function argument that is a more optimized logging function.
Return Type #
The logging function
function deprecate
Usage in Deno
import { deprecate } from "node:util";
#deprecate<T extends Function>(fn: T,msg: string,code?: string,): TThe util.deprecate() method wraps fn (which may be a function or class) in
such a way that it is marked as deprecated.
import util from 'node:util';
exports.obsoleteFunction = util.deprecate(() => {
// Do something here.
}, 'obsoleteFunction() is deprecated. Use newShinyFunction() instead.');
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.
import util from 'node:util';
const fn1 = util.deprecate(someFunction, someMessage, 'DEP0001');
const fn2 = util.deprecate(someOtherFunction, someOtherMessage, 'DEP0001');
fn1(); // Emits a deprecation warning with code DEP0001
fn2(); // Does not emit a deprecation warning because it has the same code
If either the --no-deprecation or --no-warnings command-line flags are
used, or if the process.noDeprecation property is set to trueprior 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.
Type Parameters #
#T extends Function Parameters #
Return Type #
The deprecated function wrapped to emit a warning.
function format
Usage in Deno
import { format } from "node:util";
#format(format?: any,...param: any[],): stringThe 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:
If a specifier does not have a corresponding argument, it is not replaced:
util.format('%s:%s', 'foo');
// Returns: 'foo:%s'
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:
util.format('%s:%s', 'foo', 'bar', 'baz');
// Returns: 'foo:bar baz'
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:
util.format(1, 2, 3);
// Returns: '1 2 3'
If only one argument is passed to util.format(), it is returned as it is
without any formatting:
util.format('%% %s');
// Returns: '%% %s'
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.
Parameters #
Return Type #
string function formatWithOptions
Usage in Deno
import { formatWithOptions } from "node:util";
#formatWithOptions(): stringThis function is identical to format, except in that it takes
an inspectOptions argument which specifies options that are passed along to inspect.
util.formatWithOptions({ colors: true }, 'See object %O', { foo: 42 });
// Returns 'See object { foo: 42 }', where `42` is colored as a number
// when printed to a terminal.
Parameters #
Return Type #
string function getCallSites
Usage in Deno
import { getCallSites } from "node:util";
Overload 1
#getCallSites(frameCount?: number,options?: GetCallSitesOptions,): CallSiteObject[]Returns an array of call site objects containing the stack of the caller function.
const util = require('node:util');
function exampleFunction() {
const callSites = util.getCallSites();
console.log('Call Sites:');
callSites.forEach((callSite, index) => {
console.log(`CallSite ${index + 1}:`);
console.log(`Function Name: ${callSite.functionName}`);
console.log(`Script Name: ${callSite.scriptName}`);
console.log(`Line Number: ${callSite.lineNumber}`);
console.log(`Column Number: ${callSite.column}`);
});
// CallSite 1:
// Function Name: exampleFunction
// Script Name: /home/example.js
// Line Number: 5
// Column Number: 26
// CallSite 2:
// Function Name: anotherFunction
// Script Name: /home/example.js
// Line Number: 22
// Column Number: 3
// ...
}
// A function to simulate another stack layer
function anotherFunction() {
exampleFunction();
}
anotherFunction();
It is possible to reconstruct the original locations by setting the option sourceMap to true.
If the source map is not available, the original location will be the same as the current location.
When the --enable-source-maps flag is enabled, for example when using --experimental-transform-types,
sourceMap will be true by default.
import util from 'node:util';
interface Foo {
foo: string;
}
const callSites = util.getCallSites({ sourceMap: true });
// With sourceMap:
// Function Name: ''
// Script Name: example.js
// Line Number: 7
// Column Number: 26
// Without sourceMap:
// Function Name: ''
// Script Name: example.js
// Line Number: 2
// Column Number: 26
Parameters #
#frameCount: number Number of frames to capture as call site objects.
Default: 10. Allowable range is between 1 and 200.
#options: GetCallSitesOptions Return Type #
An array of call site objects
Overload 2
#getCallSites(options: GetCallSitesOptions): CallSiteObject[]Parameters #
#options: GetCallSitesOptions Return Type #
function getSystemErrorMap
Usage in Deno
import { getSystemErrorMap } from "node:util";
#getSystemErrorMap(): Map<number, [string, string]>
This symbol is currently not supported.
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.
fs.access('file/that/does/not/exist', (err) => {
const errorMap = util.getSystemErrorMap();
const name = errorMap.get(err.errno);
console.error(name); // ENOENT
});
Return Type #
Map<number, [string, string]> function getSystemErrorMessage
Usage in Deno
import { getSystemErrorMessage } from "node:util";
#getSystemErrorMessage(err: number): stringReturns the string message for a numeric error code that comes from a Node.js API. The mapping between error codes and string messages is platform-dependent.
fs.access('file/that/does/not/exist', (err) => {
const name = util.getSystemErrorMessage(err.errno);
console.error(name); // no such file or directory
});
Parameters #
#err: number Return Type #
string function getSystemErrorName
Usage in Deno
import { getSystemErrorName } from "node:util";
#getSystemErrorName(err: number): stringReturns 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.
fs.access('file/that/does/not/exist', (err) => {
const name = util.getSystemErrorName(err.errno);
console.error(name); // ENOENT
});
Parameters #
#err: number Return Type #
string function inherits
Usage in Deno
import { inherits } from "node:util";
#inherits(constructor: unknown,superConstructor: unknown,): voidUsage 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 ofObject.setPrototypeOf(constructor.prototype, superConstructor.prototype).
As an additional convenience, superConstructor will be accessible
through the constructor.super_ property.
import util from 'node:util';
import EventEmitter from 'node:events';
function MyStream() {
EventEmitter.call(this);
}
util.inherits(MyStream, EventEmitter);
MyStream.prototype.write = function(data) {
this.emit('data', data);
};
const stream = new MyStream();
console.log(stream instanceof EventEmitter); // true
console.log(MyStream.super_ === EventEmitter); // true
stream.on('data', (data) => {
console.log(`Received data: "${data}"`);
});
stream.write('It works!'); // Received data: "It works!"
ES6 example using class and extends:
import EventEmitter from 'node:events';
class MyStream extends EventEmitter {
write(data) {
this.emit('data', data);
}
}
const stream = new MyStream();
stream.on('data', (data) => {
console.log(`Received data: "${data}"`);
});
stream.write('With ES6');
Parameters #
Return Type #
void function inspect
Usage in Deno
import { inspect } from "node:util";
Overload 1
#inspect(object: any,showHidden?: boolean,depth?: number | null,color?: boolean,): stringThe 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.
class Foo {
get [Symbol.toStringTag]() {
return 'bar';
}
}
class Bar {}
const baz = Object.create(null, { [Symbol.toStringTag]: { value: 'foo' } });
util.inspect(new Foo()); // 'Foo [bar] {}'
util.inspect(new Bar()); // 'Bar {}'
util.inspect(baz); // '[foo] {}'
Circular references point to their anchor by using a reference index:
import { inspect } from 'node:util';
const obj = {};
obj.a = [obj];
obj.b = {};
obj.b.inner = obj.b;
obj.b.obj = obj;
console.log(inspect(obj));
// <ref *1> {
// a: [ [Circular *1] ],
// b: <ref *2> { inner: [Circular *2], obj: [Circular *1] }
// }
The following example inspects all properties of the util object:
import util from 'node:util';
console.log(util.inspect(util, { showHidden: true, depth: null }));
The following example highlights the effect of the compact option:
import util from 'node:util';
const o = {
a: [1, 2, [[
'Lorem ipsum dolor sit amet,\nconsectetur adipiscing elit, sed do ' +
'eiusmod \ntempor incididunt ut labore et dolore magna aliqua.',
'test',
'foo']], 4],
b: new Map([['za', 1], ['zb', 'test']]),
};
console.log(util.inspect(o, { compact: true, depth: 5, breakLength: 80 }));
// { a:
// [ 1,
// 2,
// [ [ 'Lorem ipsum dolor sit amet,\nconsectetur [...]', // A long line
// 'test',
// 'foo' ] ],
// 4 ],
// b: Map(2) { 'za' => 1, 'zb' => 'test' } }
// Setting `compact` to false or an integer creates more reader friendly output.
console.log(util.inspect(o, { compact: false, depth: 5, breakLength: 80 }));
// {
// a: [
// 1,
// 2,
// [
// [
// 'Lorem ipsum dolor sit amet,\n' +
// 'consectetur adipiscing elit, sed do eiusmod \n' +
// 'tempor incididunt ut labore et dolore magna aliqua.',
// 'test',
// 'foo'
// ]
// ],
// 4
// ],
// b: Map(2) {
// 'za' => 1,
// 'zb' => 'test'
// }
// }
// Setting `breakLength` to e.g. 150 will print the "Lorem ipsum" text in a
// single line.
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.
import { inspect } from 'node:util';
const obj = { a: 1 };
const obj2 = { b: 2 };
const weakSet = new WeakSet([obj, obj2]);
console.log(inspect(weakSet, { showHidden: true }));
// WeakSet { { a: 1 }, { b: 2 } }
The sorted option ensures that an object's property insertion order does not
impact the result of util.inspect().
import { inspect } from 'node:util';
import assert from 'node:assert';
const o1 = {
b: [2, 3, 1],
a: '`a` comes before `b`',
c: new Set([2, 3, 1]),
};
console.log(inspect(o1, { sorted: true }));
// { a: '`a` comes before `b`', b: [ 2, 3, 1 ], c: Set(3) { 1, 2, 3 } }
console.log(inspect(o1, { sorted: (a, b) => b.localeCompare(a) }));
// { c: Set(3) { 3, 2, 1 }, b: [ 2, 3, 1 ], a: '`a` comes before `b`' }
const o2 = {
c: new Set([2, 1, 3]),
a: '`a` comes before `b`',
b: [2, 3, 1],
};
assert.strict.equal(
inspect(o1, { sorted: true }),
inspect(o2, { sorted: true }),
);
The numericSeparator option adds an underscore every three digits to all
numbers.
import { inspect } from 'node:util';
const thousand = 1_000;
const million = 1_000_000;
const bigNumber = 123_456_789n;
const bigDecimal = 1_234.123_45;
console.log(inspect(thousand, { numericSeparator: true }));
// 1_000
console.log(inspect(million, { numericSeparator: true }));
// 1_000_000
console.log(inspect(bigNumber, { numericSeparator: true }));
// 123_456_789n
console.log(inspect(bigDecimal, { numericSeparator: true }));
// 1_234.123_45
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.
Parameters #
Return Type #
string The representation of object.
Overload 2
#inspect(object: any,options?: InspectOptions,): stringParameters #
#object: any #options: InspectOptions Return Type #
string function isDeepStrictEqual
Usage in Deno
import { isDeepStrictEqual } from "node:util";
function parseArgs
Usage in Deno
import { parseArgs } from "node:util";
#parseArgs<T extends ParseArgsConfig>(config?: T): ParsedResults<T>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.
import { parseArgs } from 'node:util';
const args = ['-f', '--bar', 'b'];
const options = {
foo: {
type: 'boolean',
short: 'f',
},
bar: {
type: 'string',
},
};
const {
values,
positionals,
} = parseArgs({ args, options });
console.log(values, positionals);
// Prints: [Object: null prototype] { foo: true, bar: 'b' } []
Type Parameters #
#T extends ParseArgsConfig Parameters #
Return Type #
The parsed command line arguments:
function parseEnv
Usage in Deno
import { parseEnv } from "node:util";
function promisify
Usage in Deno
import { promisify } from "node:util";
Overload 1
#promisify<TCustom extends Function>(fn: CustomPromisify<TCustom>): TCustomTakes 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.
import util from 'node:util';
import fs from 'node:fs';
const stat = util.promisify(fs.stat);
stat('.').then((stats) => {
// Do something with `stats`
}).catch((error) => {
// Handle the error.
});
Or, equivalently using async functions:
import util from 'node:util';
import fs from 'node:fs';
const stat = util.promisify(fs.stat);
async function callStat() {
const stats = await stat('.');
console.log(`This directory is owned by ${stats.uid}`);
}
callStat();
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:
import util from 'node:util';
class Foo {
constructor() {
this.a = 42;
}
bar(callback) {
callback(null, this.a);
}
}
const foo = new Foo();
const naiveBar = util.promisify(foo.bar);
// TypeError: Cannot read property 'a' of undefined
// naiveBar().then(a => console.log(a));
naiveBar.call(foo).then((a) => console.log(a)); // '42'
const bindBar = naiveBar.bind(foo);
bindBar().then((a) => console.log(a)); // '42'
Type Parameters #
#TCustom extends Function Parameters #
#fn: CustomPromisify<TCustom> Return Type #
Overload 2
#promisify<TResult>(fn: (callback: (err: any,result: TResult,) => void) => void): () => Promise<TResult>Overload 3
#promisify(fn: (callback: (err?: any) => void) => void): () => Promise<void>Overload 4
#promisify<T1,TResult,>(fn: (arg1: T1,callback: (err: any,result: TResult,) => void,) => void): (arg1: T1) => Promise<TResult>Overload 5
#promisify<T1>(fn: (arg1: T1,callback: (err?: any) => void,) => void): (arg1: T1) => Promise<void>Overload 6
#promisify<T1,T2,TResult,>(fn: (arg1: T1,arg2: T2,callback: (err: any,result: TResult,) => void,) => void): (arg1: T1,arg2: T2,) => Promise<TResult>Overload 7
#promisify<T1,T2,>(fn: (arg1: T1,arg2: T2,callback: (err?: any) => void,) => void): (arg1: T1,arg2: T2,) => Promise<void>Overload 8
#promisify<T1,T2,T3,TResult,>(fn: (arg1: T1,arg2: T2,arg3: T3,callback: (err: any,result: TResult,) => void,) => void): (arg1: T1,arg2: T2,arg3: T3,) => Promise<TResult>Overload 9
#promisify<T1,T2,T3,>(fn: (arg1: T1,arg2: T2,arg3: T3,callback: (err?: any) => void,) => void): (arg1: T1,arg2: T2,arg3: T3,) => Promise<void>Overload 10
#promisify<T1,T2,T3,T4,TResult,>(fn: (arg1: T1,arg2: T2,arg3: T3,arg4: T4,callback: (err: any,result: TResult,) => void,) => void): (arg1: T1,arg2: T2,arg3: T3,arg4: T4,) => Promise<TResult>Overload 11
#promisify<T1,T2,T3,T4,>(fn: (arg1: T1,arg2: T2,arg3: T3,arg4: T4,callback: (err?: any) => void,) => void): (arg1: T1,arg2: T2,arg3: T3,arg4: T4,) => Promise<void>Overload 12
#promisify<T1,T2,T3,T4,T5,TResult,>(fn: (arg1: T1,arg2: T2,arg3: T3,arg4: T4,arg5: T5,callback: (err: any,result: TResult,) => void,) => void): (arg1: T1,arg2: T2,arg3: T3,arg4: T4,arg5: T5,) => Promise<TResult>Overload 13
#promisify<T1,T2,T3,T4,T5,>(fn: (arg1: T1,arg2: T2,arg3: T3,arg4: T4,arg5: T5,callback: (err?: any) => void,) => void): (arg1: T1,arg2: T2,arg3: T3,arg4: T4,arg5: T5,) => Promise<void>Overload 14
function stripVTControlCharacters
Usage in Deno
import { stripVTControlCharacters } from "node:util";
function styleText
Usage in Deno
import { styleText } from "node:util";
#styleText(format: ,text: string,): stringThis function returns a formatted text considering the format passed.
import { styleText } from 'node:util';
const errorMessage = styleText('red', 'Error! Error!');
console.log(errorMessage);
util.inspect.colors also provides text formats such as italic, and underline and you can combine both:
console.log(
util.styleText(['underline', 'italic'], 'My italic underlined message'),
);
When passing an array of formats, the order of the format applied is left to right so the following style might overwrite the previous one.
console.log(
util.styleText(['red', 'green'], 'text'), // green
);
The full list of formats can be found in modifiers.
Parameters #
#format: A text format or an Array of text formats defined in util.inspect.colors.
#text: string The text to to be formatted.
Return Type #
string function toUSVString
Usage in Deno
import { toUSVString } from "node:util";
function transferableAbortController
Usage in Deno
import { transferableAbortController } from "node:util";
#transferableAbortController(): AbortController
This symbol is currently not supported.
Creates and returns an AbortController instance whose AbortSignal is marked
as transferable and can be used with structuredClone() or postMessage().
Return Type #
AbortController A transferable AbortController
function transferableAbortSignal
Usage in Deno
import { transferableAbortSignal } from "node:util";
#transferableAbortSignal(signal: AbortSignal): AbortSignal
This symbol is currently not supported.
Marks the given AbortSignal as transferable so that it can be used withstructuredClone() and postMessage().
const signal = transferableAbortSignal(AbortSignal.timeout(100));
const channel = new MessageChannel();
channel.port2.postMessage(signal, [signal]);
Parameters #
#signal: AbortSignal The AbortSignal
Return Type #
AbortSignal The same AbortSignal
function types.isAnyArrayBuffer
Usage in Deno
import { types } from "node:util";
const { isAnyArrayBuffer } = types;
#isAnyArrayBuffer(object: unknown): object is ArrayBufferLikeReturns true if the value is a built-in ArrayBuffer or
SharedArrayBuffer instance.
See also util.types.isArrayBuffer() and util.types.isSharedArrayBuffer().
util.types.isAnyArrayBuffer(new ArrayBuffer()); // Returns true
util.types.isAnyArrayBuffer(new SharedArrayBuffer()); // Returns true
Parameters #
#object: unknown Return Type #
object is ArrayBufferLike function types.isArgumentsObject
Usage in Deno
import { types } from "node:util";
const { isArgumentsObject } = types;
function types.isArrayBuffer
Usage in Deno
import { types } from "node:util";
const { isArrayBuffer } = types;
#isArrayBuffer(object: unknown): object is ArrayBufferReturns 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.
util.types.isArrayBuffer(new ArrayBuffer()); // Returns true
util.types.isArrayBuffer(new SharedArrayBuffer()); // Returns false
Parameters #
#object: unknown Return Type #
object is ArrayBuffer function types.isArrayBufferView
Usage in Deno
import { types } from "node:util";
const { isArrayBufferView } = types;
#isArrayBufferView(object: unknown): object is ArrayBufferViewReturns true if the value is an instance of one of the ArrayBuffer views, such as typed
array objects or DataView. Equivalent to
ArrayBuffer.isView().
util.types.isArrayBufferView(new Int8Array()); // true
util.types.isArrayBufferView(Buffer.from('hello world')); // true
util.types.isArrayBufferView(new DataView(new ArrayBuffer(16))); // true
util.types.isArrayBufferView(new ArrayBuffer()); // false
Parameters #
#object: unknown Return Type #
object is ArrayBufferView function types.isAsyncFunction
Usage in Deno
import { types } from "node:util";
const { isAsyncFunction } = types;
#isAsyncFunction(object: unknown): booleanReturns 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.
util.types.isAsyncFunction(function foo() {}); // Returns false
util.types.isAsyncFunction(async function foo() {}); // Returns true
Parameters #
#object: unknown Return Type #
boolean function types.isBigInt64Array
Usage in Deno
import { types } from "node:util";
const { isBigInt64Array } = types;
#isBigInt64Array(value: unknown): value is BigInt64Arrayfunction types.isBigIntObject
Usage in Deno
import { types } from "node:util";
const { isBigIntObject } = types;
#isBigIntObject(object: unknown): object is BigIntReturns true if the value is a BigInt object, e.g. created
by Object(BigInt(123)).
util.types.isBigIntObject(Object(BigInt(123))); // Returns true
util.types.isBigIntObject(BigInt(123)); // Returns false
util.types.isBigIntObject(123); // Returns false
Parameters #
#object: unknown Return Type #
object is BigInt function types.isBigUint64Array
Usage in Deno
import { types } from "node:util";
const { isBigUint64Array } = types;
#isBigUint64Array(value: unknown): value is BigUint64Arrayfunction types.isBooleanObject
Usage in Deno
import { types } from "node:util";
const { isBooleanObject } = types;
#isBooleanObject(object: unknown): object is BooleanReturns true if the value is a boolean object, e.g. created
by new Boolean().
util.types.isBooleanObject(false); // Returns false
util.types.isBooleanObject(true); // Returns false
util.types.isBooleanObject(new Boolean(false)); // Returns true
util.types.isBooleanObject(new Boolean(true)); // Returns true
util.types.isBooleanObject(Boolean(false)); // Returns false
util.types.isBooleanObject(Boolean(true)); // Returns false
Parameters #
#object: unknown Return Type #
object is Boolean function types.isBoxedPrimitive
Usage in Deno
import { types } from "node:util";
const { isBoxedPrimitive } = types;
#isBoxedPrimitive(object: unknown): object is String
| Number
| BigInt
| Boolean
| SymbolReturns true if the value is any boxed primitive object, e.g. created
by new Boolean(), new String() or Object(Symbol()).
For example:
util.types.isBoxedPrimitive(false); // Returns false
util.types.isBoxedPrimitive(new Boolean(false)); // Returns true
util.types.isBoxedPrimitive(Symbol('foo')); // Returns false
util.types.isBoxedPrimitive(Object(Symbol('foo'))); // Returns true
util.types.isBoxedPrimitive(Object(BigInt(5))); // Returns true
Parameters #
#object: unknown Return Type #
object is String
| Number
| BigInt
| Boolean
| Symbol function types.isCryptoKey
Usage in Deno
import { types } from "node:util";
const { isCryptoKey } = types;
function types.isDataView
Usage in Deno
import { types } from "node:util";
const { isDataView } = types;
#isDataView(object: unknown): object is DataViewReturns true if the value is a built-in DataView instance.
const ab = new ArrayBuffer(20);
util.types.isDataView(new DataView(ab)); // Returns true
util.types.isDataView(new Float64Array()); // Returns false
See also ArrayBuffer.isView().
Parameters #
#object: unknown Return Type #
object is DataView function types.isExternal
Usage in Deno
import { types } from "node:util";
const { isExternal } = types;
#isExternal(object: unknown): booleanReturns 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 anull prototype.
#include <js_native_api.h>
#include <stdlib.h>
napi_value result;
static napi_value MyNapi(napi_env env, napi_callback_info info) {
int* raw = (int*) malloc(1024);
napi_status status = napi_create_external(env, (void*) raw, NULL, NULL, &result);
if (status != napi_ok) {
napi_throw_error(env, NULL, "napi_create_external failed");
return NULL;
}
return result;
}
...
DECLARE_NAPI_PROPERTY("myNapi", MyNapi)
...
const native = require('napi_addon.node');
const data = native.myNapi();
util.types.isExternal(data); // returns true
util.types.isExternal(0); // returns false
util.types.isExternal(new String('foo')); // returns false
For further information on napi_create_external, refer to napi_create_external().
Parameters #
#object: unknown Return Type #
boolean function types.isFloat32Array
Usage in Deno
import { types } from "node:util";
const { isFloat32Array } = types;
#isFloat32Array(object: unknown): object is Float32ArrayReturns true if the value is a built-in Float32Array instance.
util.types.isFloat32Array(new ArrayBuffer()); // Returns false
util.types.isFloat32Array(new Float32Array()); // Returns true
util.types.isFloat32Array(new Float64Array()); // Returns false
Parameters #
#object: unknown Return Type #
object is Float32Array function types.isFloat64Array
Usage in Deno
import { types } from "node:util";
const { isFloat64Array } = types;
#isFloat64Array(object: unknown): object is Float64ArrayReturns true if the value is a built-in Float64Array instance.
util.types.isFloat64Array(new ArrayBuffer()); // Returns false
util.types.isFloat64Array(new Uint8Array()); // Returns false
util.types.isFloat64Array(new Float64Array()); // Returns true
Parameters #
#object: unknown Return Type #
object is Float64Array function types.isGeneratorFunction
Usage in Deno
import { types } from "node:util";
const { isGeneratorFunction } = types;
#isGeneratorFunction(object: unknown): object is GeneratorFunctionReturns 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.
util.types.isGeneratorFunction(function foo() {}); // Returns false
util.types.isGeneratorFunction(function* foo() {}); // Returns true
Parameters #
#object: unknown Return Type #
object is GeneratorFunction function types.isGeneratorObject
Usage in Deno
import { types } from "node:util";
const { isGeneratorObject } = types;
#isGeneratorObject(object: unknown): object is GeneratorReturns 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.
function* foo() {}
const generator = foo();
util.types.isGeneratorObject(generator); // Returns true
Parameters #
#object: unknown Return Type #
object is Generator function types.isInt16Array
Usage in Deno
import { types } from "node:util";
const { isInt16Array } = types;
#isInt16Array(object: unknown): object is Int16ArrayReturns true if the value is a built-in Int16Array instance.
util.types.isInt16Array(new ArrayBuffer()); // Returns false
util.types.isInt16Array(new Int16Array()); // Returns true
util.types.isInt16Array(new Float64Array()); // Returns false
Parameters #
#object: unknown Return Type #
object is Int16Array function types.isInt32Array
Usage in Deno
import { types } from "node:util";
const { isInt32Array } = types;
#isInt32Array(object: unknown): object is Int32ArrayReturns true if the value is a built-in Int32Array instance.
util.types.isInt32Array(new ArrayBuffer()); // Returns false
util.types.isInt32Array(new Int32Array()); // Returns true
util.types.isInt32Array(new Float64Array()); // Returns false
Parameters #
#object: unknown Return Type #
object is Int32Array function types.isInt8Array
Usage in Deno
import { types } from "node:util";
const { isInt8Array } = types;
#isInt8Array(object: unknown): object is Int8Arrayfunction types.isKeyObject
Usage in Deno
import { types } from "node:util";
const { isKeyObject } = types;
function types.isMap
Usage in Deno
import { types } from "node:util";
const { isMap } = types;
#isMap<T>(object: T | { }): object is T extends ReadonlyMap<any, any> ? (unknown extends T ? never : ReadonlyMap<any, any>) : Map<unknown, unknown>function types.isMapIterator
Usage in Deno
import { types } from "node:util";
const { isMapIterator } = types;
#isMapIterator(object: unknown): booleanReturns true if the value is an iterator returned for a built-in Map instance.
const map = new Map();
util.types.isMapIterator(map.keys()); // Returns true
util.types.isMapIterator(map.values()); // Returns true
util.types.isMapIterator(map.entries()); // Returns true
util.types.isMapIterator(map[Symbol.iterator]()); // Returns true
Parameters #
#object: unknown Return Type #
boolean function types.isModuleNamespaceObject
Usage in Deno
import { types } from "node:util";
const { isModuleNamespaceObject } = types;
#isModuleNamespaceObject(value: unknown): booleanReturns true if the value is an instance of a Module Namespace Object.
import * as ns from './a.js';
util.types.isModuleNamespaceObject(ns); // Returns true
Parameters #
#value: unknown Return Type #
boolean function types.isNativeError
Usage in Deno
import { types } from "node:util";
const { isNativeError } = types;
#isNativeError(object: unknown): object is ErrorReturns true if the value was returned by the constructor of a built-in Error type.
console.log(util.types.isNativeError(new Error())); // true
console.log(util.types.isNativeError(new TypeError())); // true
console.log(util.types.isNativeError(new RangeError())); // true
Subclasses of the native error types are also native errors:
class MyError extends Error {}
console.log(util.types.isNativeError(new MyError())); // true
A value being instanceof a native error class is not equivalent to isNativeError() returning true for that value. isNativeError() returns true for errors
which come from a different realm while instanceof Error returns false for these errors:
import vm from 'node:vm';
const context = vm.createContext({});
const myError = vm.runInContext('new Error()', context);
console.log(util.types.isNativeError(myError)); // true
console.log(myError instanceof Error); // false
Conversely, isNativeError() returns false for all objects which were not
returned by the constructor of a native error. That includes values
which are instanceof native errors:
const myError = { __proto__: Error.prototype };
console.log(util.types.isNativeError(myError)); // false
console.log(myError instanceof Error); // true
Parameters #
#object: unknown Return Type #
object is Error function types.isNumberObject
Usage in Deno
import { types } from "node:util";
const { isNumberObject } = types;
function types.isPromise
Usage in Deno
import { types } from "node:util";
const { isPromise } = types;
function types.isProxy
Usage in Deno
import { types } from "node:util";
const { isProxy } = types;
function types.isRegExp
Usage in Deno
import { types } from "node:util";
const { isRegExp } = types;
function types.isSet
Usage in Deno
import { types } from "node:util";
const { isSet } = types;
#isSet<T>(object: T | { }): object is T extends ReadonlySet<any> ? (unknown extends T ? never : ReadonlySet<any>) : Set<unknown>function types.isSetIterator
Usage in Deno
import { types } from "node:util";
const { isSetIterator } = types;
#isSetIterator(object: unknown): booleanReturns true if the value is an iterator returned for a built-in Set instance.
const set = new Set();
util.types.isSetIterator(set.keys()); // Returns true
util.types.isSetIterator(set.values()); // Returns true
util.types.isSetIterator(set.entries()); // Returns true
util.types.isSetIterator(set[Symbol.iterator]()); // Returns true
Parameters #
#object: unknown Return Type #
boolean function types.isSharedArrayBuffer
Usage in Deno
import { types } from "node:util";
const { isSharedArrayBuffer } = types;
function types.isStringObject
Usage in Deno
import { types } from "node:util";
const { isStringObject } = types;
function types.isSymbolObject
Usage in Deno
import { types } from "node:util";
const { isSymbolObject } = types;
#isSymbolObject(object: unknown): object is Symbolfunction types.isTypedArray
Usage in Deno
import { types } from "node:util";
const { isTypedArray } = types;
#isTypedArray(object: unknown): object is TypedArrayReturns true if the value is a built-in TypedArray instance.
util.types.isTypedArray(new ArrayBuffer()); // Returns false
util.types.isTypedArray(new Uint8Array()); // Returns true
util.types.isTypedArray(new Float64Array()); // Returns true
See also ArrayBuffer.isView().
Parameters #
#object: unknown Return Type #
object is TypedArray function types.isUint16Array
Usage in Deno
import { types } from "node:util";
const { isUint16Array } = types;
#isUint16Array(object: unknown): object is Uint16ArrayReturns true if the value is a built-in Uint16Array instance.
util.types.isUint16Array(new ArrayBuffer()); // Returns false
util.types.isUint16Array(new Uint16Array()); // Returns true
util.types.isUint16Array(new Float64Array()); // Returns false
Parameters #
#object: unknown Return Type #
object is Uint16Array function types.isUint32Array
Usage in Deno
import { types } from "node:util";
const { isUint32Array } = types;
#isUint32Array(object: unknown): object is Uint32ArrayReturns true if the value is a built-in Uint32Array instance.
util.types.isUint32Array(new ArrayBuffer()); // Returns false
util.types.isUint32Array(new Uint32Array()); // Returns true
util.types.isUint32Array(new Float64Array()); // Returns false
Parameters #
#object: unknown Return Type #
object is Uint32Array function types.isUint8Array
Usage in Deno
import { types } from "node:util";
const { isUint8Array } = types;
#isUint8Array(object: unknown): object is Uint8ArrayReturns true if the value is a built-in Uint8Array instance.
util.types.isUint8Array(new ArrayBuffer()); // Returns false
util.types.isUint8Array(new Uint8Array()); // Returns true
util.types.isUint8Array(new Float64Array()); // Returns false
Parameters #
#object: unknown Return Type #
object is Uint8Array function types.isUint8ClampedArray
Usage in Deno
import { types } from "node:util";
const { isUint8ClampedArray } = types;
#isUint8ClampedArray(object: unknown): object is Uint8ClampedArrayReturns true if the value is a built-in Uint8ClampedArray instance.
util.types.isUint8ClampedArray(new ArrayBuffer()); // Returns false
util.types.isUint8ClampedArray(new Uint8ClampedArray()); // Returns true
util.types.isUint8ClampedArray(new Float64Array()); // Returns false
Parameters #
#object: unknown Return Type #
object is Uint8ClampedArray function types.isWeakMap
Usage in Deno
import { types } from "node:util";
const { isWeakMap } = types;
function types.isWeakSet
Usage in Deno
import { types } from "node:util";
const { isWeakSet } = types;
function isArray
Usage in Deno
import { isArray } from "node:util";
#isArray(object: unknown): object is unknown[]Alias for Array.isArray().
Returns true if the given object is an Array. Otherwise, returns false.
import util from 'node:util';
util.isArray([]);
// Returns: true
util.isArray(new Array());
// Returns: true
util.isArray({});
// Returns: false
Parameters #
#object: unknown Return Type #
object is unknown[] function isBuffer
Usage in Deno
import { isBuffer } from "node:util";
#isBuffer(object: unknown): object is BufferReturns true if the given object is a Buffer. Otherwise, returns false.
import util from 'node:util';
util.isBuffer({ length: 0 });
// Returns: false
util.isBuffer([]);
// Returns: false
util.isBuffer(Buffer.from('hello world'));
// Returns: true
Parameters #
#object: unknown Return Type #
object is Buffer function isError
Usage in Deno
import { isError } from "node:util";
#isError(object: unknown): object is ErrorReturns true if the given object is an Error. Otherwise, returns false.
import util from 'node:util';
util.isError(new Error());
// Returns: true
util.isError(new TypeError());
// Returns: true
util.isError({ name: 'Error', message: 'an error occurred' });
// Returns: false
This method relies on Object.prototype.toString() behavior. It is
possible to obtain an incorrect result when the object argument manipulates @@toStringTag.
import util from 'node:util';
const obj = { name: 'Error', message: 'an error occurred' };
util.isError(obj);
// Returns: false
obj[Symbol.toStringTag] = 'Error';
util.isError(obj);
// Returns: true
Parameters #
#object: unknown Return Type #
object is Error function isFunction
Usage in Deno
import { isFunction } from "node:util";
#isFunction(object: unknown): booleanReturns true if the given object is a Function. Otherwise, returns false.
import util from 'node:util';
function Foo() {}
const Bar = () => {};
util.isFunction({});
// Returns: false
util.isFunction(Foo);
// Returns: true
util.isFunction(Bar);
// Returns: true
Parameters #
#object: unknown Return Type #
boolean function isNullOrUndefined
Usage in Deno
import { isNullOrUndefined } from "node:util";
#isNullOrUndefined(object: unknown): object is null | undefinedReturns true if the given object is null or undefined. Otherwise,
returns false.
import util from 'node:util';
util.isNullOrUndefined(0);
// Returns: false
util.isNullOrUndefined(undefined);
// Returns: true
util.isNullOrUndefined(null);
// Returns: true
Parameters #
#object: unknown Return Type #
object is null | undefined function isNumber
Usage in Deno
import { isNumber } from "node:util";
#isNumber(object: unknown): object is numberReturns true if the given object is a Number. Otherwise, returns false.
import util from 'node:util';
util.isNumber(false);
// Returns: false
util.isNumber(Infinity);
// Returns: true
util.isNumber(0);
// Returns: true
util.isNumber(NaN);
// Returns: true
Parameters #
#object: unknown Return Type #
object is number function isObject
Usage in Deno
import { isObject } from "node:util";
#isObject(object: unknown): booleanReturns true if the given object is strictly an Objectand not aFunction (even though functions are objects in JavaScript).
Otherwise, returns false.
import util from 'node:util';
util.isObject(5);
// Returns: false
util.isObject(null);
// Returns: false
util.isObject({});
// Returns: true
util.isObject(() => {});
// Returns: false
Parameters #
#object: unknown Return Type #
boolean function isPrimitive
Usage in Deno
import { isPrimitive } from "node:util";
#isPrimitive(object: unknown): booleanReturns true if the given object is a primitive type. Otherwise, returnsfalse.
import util from 'node:util';
util.isPrimitive(5);
// Returns: true
util.isPrimitive('foo');
// Returns: true
util.isPrimitive(false);
// Returns: true
util.isPrimitive(null);
// Returns: true
util.isPrimitive(undefined);
// Returns: true
util.isPrimitive({});
// Returns: false
util.isPrimitive(() => {});
// Returns: false
util.isPrimitive(/^$/);
// Returns: false
util.isPrimitive(new Date());
// Returns: false
Parameters #
#object: unknown Return Type #
boolean function isRegExp
Usage in Deno
import { isRegExp } from "node:util";
#isRegExp(object: unknown): object is RegExpReturns true if the given object is a RegExp. Otherwise, returns false.
import util from 'node:util';
util.isRegExp(/some regexp/);
// Returns: true
util.isRegExp(new RegExp('another regexp'));
// Returns: true
util.isRegExp({});
// Returns: false
Parameters #
#object: unknown Return Type #
object is RegExp function isString
Usage in Deno
import { isString } from "node:util";
#isString(object: unknown): object is stringReturns true if the given object is a string. Otherwise, returns false.
import util from 'node:util';
util.isString('');
// Returns: true
util.isString('foo');
// Returns: true
util.isString(String('foo'));
// Returns: true
util.isString(5);
// Returns: false
Parameters #
#object: unknown Return Type #
object is string function isUndefined
Usage in Deno
import { isUndefined } from "node:util";
#isUndefined(object: unknown): object is undefinedReturns true if the given object is undefined. Otherwise, returns false.
import util from 'node:util';
const foo = undefined;
util.isUndefined(5);
// Returns: false
util.isUndefined(foo);
// Returns: true
util.isUndefined(null);
// Returns: false
Parameters #
#object: unknown Return Type #
object is undefined interface CallSiteObject
Usage in Deno
import { type CallSiteObject } from "node:util";
Properties #
#functionName: string Returns the name of the function associated with this call site.
#scriptName: string Returns the name of the resource that contains the script for the function for this call site.
Returns the unique id of the script, as in Chrome DevTools protocol
Runtime.ScriptId.
#lineNumber: number Returns the number, 1-based, of the line for the associate function call.
#columnNumber: number Returns the 1-based column offset on the line for the associated function call.
interface CustomPromisifyLegacy
Usage in Deno
import { type CustomPromisifyLegacy } from "node:util";
interface CustomPromisifySymbol
Usage in Deno
import { type CustomPromisifySymbol } from "node:util";
interface DebugLogger
Usage in Deno
import { type DebugLogger } from "node:util";
interface GetCallSitesOptions
Usage in Deno
import { type GetCallSitesOptions } from "node:util";
interface InspectOptions
Usage in Deno
import { type InspectOptions } from "node:util";
Properties #
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.
If true, the output is styled with ANSI color codes. Colors are customizable.
#customInspect: boolean | undefined If false, [util.inspect.custom](depth, opts, inspect) functions are not invoked.
If true, Proxy inspection includes the target and handler objects.
#maxArrayLength: number
| null
| undefined Specifies the maximum number of Array, TypedArray, 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.
#maxStringLength: number
| null
| undefined 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.
#breakLength: number | undefined 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).
Setting this to false causes each object key
to be displayed on a new line. It will also add new lines to 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. Note that no
text will be reduced below 16 characters, no matter the breakLength size.
For more information, see the example below.
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.
If set to true, getters are going to be
inspected as well. If set to 'get' only getters without setter are going
to be inspected. If set to 'set' only getters having a corresponding
setter are going to be inspected. This might cause side effects depending on
the getter function.
#numericSeparator: boolean | undefined If set to true, an underscore is used to separate every three digits in all bigints and numbers.
interface InspectOptionsStylized
Usage in Deno
import { type InspectOptionsStylized } from "node:util";
interface ParseArgsConfig
Usage in Deno
import { type ParseArgsConfig } from "node:util";
Properties #
#options: ParseArgsOptionsConfig | undefined Used to describe arguments known to the parser.
Should an error be thrown when unknown arguments are encountered,
or when arguments are passed that do not match the type configured in options.
#allowPositionals: boolean | undefined Whether this command accepts positional arguments.
#allowNegative: boolean | undefined If true, allows explicitly setting boolean options to false by prefixing the option name with --no-.
interface ParseArgsOptionDescriptor
Usage in Deno
import { type ParseArgsOptionDescriptor } from "node:util";
Properties #
Type of argument.
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.
interface ParseArgsOptionsConfig
Usage in Deno
import { type ParseArgsOptionsConfig } from "node:util";
Index Signatures #
namespace types
Usage in Deno
import { types } from "node:util";
Functions #
Returns true if the value is a built-in ArrayBuffer or
SharedArrayBuffer instance.
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.
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().
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.
Returns true if the value is a BigInt object, e.g. created
by Object(BigInt(123)).
Returns true if the value is any boxed primitive object, e.g. created
by new Boolean(), new String() or Object(Symbol()).
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.
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.
Returns true if the value was returned by the constructor of a built-in Error type.
Returns true if the value is a symbol object, created
by calling Object() on a Symbol primitive.
type alias ApplyOptionalModifiers
Usage in Deno
import { type ApplyOptionalModifiers } from "node:util";
Type Parameters #
#O extends ParseArgsOptionsConfig Definition #
type alias BackgroundColors
Usage in Deno
import { type BackgroundColors } from "node:util";
Definition #
"bgBlack"
| "bgBlackBright"
| "bgBlue"
| "bgBlueBright"
| "bgCyan"
| "bgCyanBright"
| "bgGray"
| "bgGreen"
| "bgGreenBright"
| "bgGrey"
| "bgMagenta"
| "bgMagentaBright"
| "bgRed"
| "bgRedBright"
| "bgWhite"
| "bgWhiteBright"
| "bgYellow"
| "bgYellowBright" type alias CustomInspectFunction
Usage in Deno
import { type CustomInspectFunction } from "node:util";
Definition #
(depth: number,options: InspectOptionsStylized,) => any type alias CustomPromisify
Usage in Deno
import { type CustomPromisify } from "node:util";
type alias DebugLoggerFunction
Usage in Deno
import { type DebugLoggerFunction } from "node:util";
Definition #
(msg: string,...param: unknown[],) => void type alias ExtractOptionValue
Usage in Deno
import { type ExtractOptionValue } from "node:util";
Type Parameters #
#T extends ParseArgsConfig #O extends ParseArgsOptionDescriptor Definition #
IfDefaultsTrue<T["strict"], O["type"] extends "string" ? string : O["type"] extends "boolean" ? boolean : string | boolean, string | boolean> type alias ForegroundColors
Usage in Deno
import { type ForegroundColors } from "node:util";
Definition #
"black"
| "blackBright"
| "blue"
| "blueBright"
| "cyan"
| "cyanBright"
| "gray"
| "green"
| "greenBright"
| "grey"
| "magenta"
| "magentaBright"
| "red"
| "redBright"
| "white"
| "whiteBright"
| "yellow"
| "yellowBright" type alias OptionToken
Usage in Deno
import { type OptionToken } from "node:util";
Definition #
{ kind: "option"; index: number; name: string; rawName: string; value: string; inlineValue: boolean; } | { kind: "option"; index: number; name: string; rawName: string; value: undefined; inlineValue: undefined; } type alias ParseArgsOptionsType
Usage in Deno
import { type ParseArgsOptionsType } from "node:util";
type alias ParsedOptionToken
Usage in Deno
import { type ParsedOptionToken } from "node:util";
Type Parameters #
#T extends ParseArgsConfig Definition #
IfDefaultsTrue<T["strict"], TokenForOptions<T>, OptionToken> type alias ParsedPositionals
Usage in Deno
import { type ParsedPositionals } from "node:util";
Type Parameters #
#T extends ParseArgsConfig Definition #
IfDefaultsTrue<T["strict"], IfDefaultsFalse<T["allowPositionals"], string[], []>, IfDefaultsTrue<T["allowPositionals"], string[], []>> type alias ParsedPositionalToken
Usage in Deno
import { type ParsedPositionalToken } from "node:util";
Type Parameters #
#T extends ParseArgsConfig Definition #
IfDefaultsTrue<T["strict"], IfDefaultsFalse<T["allowPositionals"], { kind: "positional"; index: number; value: string; }, never>, IfDefaultsTrue<T["allowPositionals"], { kind: "positional"; index: number; value: string; }, never>> type alias ParsedResults
Usage in Deno
import { type ParsedResults } from "node:util";
Type Parameters #
#T extends ParseArgsConfig Definition #
ParseArgsConfig extends T ? { values: { [longOption: string]: undefined
| string
| boolean
| Array<string | boolean>; }; positionals: string[]; tokens?: Token[]; } : PreciseParsedResults<T> type alias ParsedTokens
Usage in Deno
import { type ParsedTokens } from "node:util";
Type Parameters #
#T extends ParseArgsConfig Definition #
Array<> type alias ParsedValues
Usage in Deno
import { type ParsedValues } from "node:util";
Type Parameters #
#T extends ParseArgsConfig Definition #
IfDefaultsTrue<T["strict"], unknown, { [longOption: string]: undefined
| string
| boolean; }> & (T["options"] extends ParseArgsOptionsConfig ? ApplyOptionalModifiers<T["options"], [LongOption in keyof T["options"]]: IfDefaultsFalse<T["options"][LongOption]["multiple"], Array<ExtractOptionValue<T, T["options"][LongOption]>>, ExtractOptionValue<T, T["options"][LongOption]>>> : { }) type alias PreciseParsedResults
Usage in Deno
import { type PreciseParsedResults } from "node:util";
Type Parameters #
#T extends ParseArgsConfig Definition #
IfDefaultsFalse<T["tokens"], { values: ParsedValues<T>; positionals: ParsedPositionals<T>; tokens: ParsedTokens<T>; }, { values: ParsedValues<T>; positionals: ParsedPositionals<T>; }> type alias PreciseTokenForOptions
Usage in Deno
import { type PreciseTokenForOptions } from "node:util";
Type Parameters #
#K extends string #O extends ParseArgsOptionDescriptor Definition #
type alias Token
Usage in Deno
import { type Token } from "node:util";
Definition #
OptionToken
| { kind: "positional"; index: number; value: string; }
| { kind: "option-terminator"; index: number; } type alias TokenForOptions
Usage in Deno
import { type TokenForOptions } from "node:util";
Type Parameters #
#T extends ParseArgsConfig Definition #
K extends unknown ? T["options"] extends ParseArgsOptionsConfig ? PreciseTokenForOptions<K & string, T["options"][K]> : OptionToken : never variable inspect.colors
Usage in Deno
import { inspect } from "node:util";
Type #
Dict<[number, number]> variable inspect.custom
Usage in Deno
import { inspect } from "node:util";
That can be used to declare custom inspect functions.
Type #
unique symbol variable inspect.replDefaults
Usage in Deno
import { inspect } from "node:util";
Allows changing inspect settings from the repl.
Type #
variable promisify.custom
Usage in Deno
import { promisify } from "node:util";
That can be used to declare custom promisified variants of functions.
Type #
unique symbol