assert
The node:assert module provides a set of assertion functions for verifying
invariants.
An alias of ok.
Indicates the failure of an assertion. All errors thrown by the node:assertmodule will be instances of the AssertionError class.
Strict assertion mode
Tests for deep equality between the actual and expected parameters.
"Deep" equality means that the enumerable "own" properties of child objects
are recursively evaluated also by the following rules.
Expects the string input not to match the regular expression.
Awaits the asyncFn promise or, if asyncFn is a function, immediately
calls the function and awaits the returned promise to complete. It will then
check that the promise is not rejected.
Asserts that the function fn does not throw an error.
Strict assertion mode
Throws an AssertionError with the provided error message or a default
error message. If the message parameter is an instance of an Error then
it will be thrown instead of the AssertionError.
Throws value if value is not undefined or null. This is useful when
testing the error argument in callbacks. The stack trace contains all frames
from the error passed to ifError() including the potential new frames forifError() itself.
Expects the string input to match the regular expression.
Strict assertion mode
Tests for deep strict inequality. Opposite of deepStrictEqual.
Strict assertion mode
Tests strict inequality between the actual and expected parameters as
determined by Object.is().
Tests if value is truthy. It is equivalent toassert.equal(!!value, true, message).
Awaits the asyncFn promise or, if asyncFn is a function, immediately
calls the function and awaits the returned promise to complete. It will then
check that the promise is rejected.
In strict assertion mode, non-strict methods behave like their corresponding strict methods. For example, deepEqual will behave like deepStrictEqual.
Tests strict equality between the actual and expected parameters as
determined by Object.is().
Expects the function fn to throw an error.
This feature is deprecated and will be removed in a future version.
Please consider using alternatives such as the mock helper function.
async_hooks
We strongly discourage the use of the async_hooks API.
Other APIs that can cover most of its use cases include:
This class creates stores that stay coherent through asynchronous operations.
The class AsyncResource is designed to be extended by the embedder's async
resources. Using this, users can easily trigger the lifetime events of their
own resources.
Registers functions to be called for different lifetime events of each async operation.
Resource objects returned by executionAsyncResource() are most often internal
Node.js handle objects with undocumented APIs. Using any functions or properties
on the object is likely to crash your application and should be avoided.
buffer
Buffer objects are used to represent a fixed-length sequence of bytes. Many
Node.js APIs support Buffers.
Decodes a string of Base64-encoded data into bytes, and encodes those bytes into a string using Latin-1 (ISO-8859-1).
Decodes a string into bytes using Latin-1 (ISO-8859), and encodes those bytes into a string using Base64.
Raw data is stored in instances of the Buffer class. A Buffer is similar to an array of integers but corresponds to a raw memory allocation outside the V8 heap. A Buffer cannot be resized. Valid string encodings: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'base64url'|'binary'(deprecated)|'hex'
This function returns true if input contains only valid ASCII-encoded data,
including the case in which input is empty.
This function returns true if input contains only valid UTF-8-encoded data,
including the case in which input is empty.
Resolves a 'blob:nodedata:...' an associated Blob object registered using
a prior call to URL.createObjectURL().
Re-encodes the given Buffer or Uint8Array instance from one character
encoding to another. Returns a new Buffer instance.
child_process
The node:child_process module provides the ability to spawn subprocesses in
a manner that is similar, but not identical, to popen(3). This capability
is primarily provided by the spawn function:
Instances of the ChildProcess represent spawned child processes.
The child_process.execFile() function is similar to exec except that it does not spawn a shell by default. Rather, the specified
executable file is spawned directly as a new process making it slightly more
efficient than exec.
The child_process.execFileSync() method is generally identical to execFile with the exception that the method will not
return until the child process has fully closed. When a timeout has been
encountered and killSignal is sent, the method won't return until the process
has completely exited.
The child_process.execSync() method is generally identical to exec with the exception that the method will not return
until the child process has fully closed. When a timeout has been encountered
and killSignal is sent, the method won't return until the process has
completely exited. If the child process intercepts and handles the SIGTERMsignal and doesn't exit, the parent process will wait until the child process
has exited.
The child_process.fork() method is a special case of spawn used specifically to spawn new Node.js processes.
Like spawn, a ChildProcess object is returned. The
returned ChildProcess will have an additional communication channel
built-in that allows messages to be passed back and forth between the parent and
child. See subprocess.send() for details.
The child_process.spawn() method spawns a new process using the givencommand, with command-line arguments in args. If omitted, args defaults
to an empty array.
The child_process.spawnSync() method is generally identical to spawn with the exception that the function will not return
until the child process has fully closed. When a timeout has been encountered
and killSignal is sent, the method won't return until the process has
completely exited. If the process intercepts and handles the SIGTERM signal
and doesn't exit, the parent process will wait until the child process has
exited.
cluster
Clusters of Node.js processes can be used to run multiple instances of Node.js
that can distribute workloads among their application threads. When process isolation
is not needed, use the worker_threads
module instead, which allows running multiple application threads within a single Node.js instance.
A Worker object contains all public information and method about a worker.
In the primary it can be obtained using cluster.workers. In a worker
it can be obtained using cluster.worker.
console
The node:console module provides a simple debugging console that is similar to
the JavaScript console mechanism provided by web browsers.
The console module provides a simple debugging console that is similar to the
JavaScript console mechanism provided by web browsers.
crypto
The node:crypto module provides cryptographic functionality that includes a
set of wrappers for OpenSSL's hash, HMAC, cipher, decipher, sign, and verify
functions.
SPKAC is a Certificate Signing Request mechanism originally implemented by
Netscape and was specified formally as part of HTML5's keygen element.
Checks the primality of the candidate.
Checks the primality of the candidate.
Instances of the Cipher class are used to encrypt data. The class can be
used in one of two ways:
Specifies the active default cipher list used by the current Node.js process (colon-separated values).
Specifies the built-in default cipher list used by Node.js (colon-separated values).
Causes the salt length for RSA_PKCS1_PSS_PADDING to be determined automatically when verifying a signature.
Sets the salt length for RSA_PKCS1_PSS_PADDING to the digest size when signing or verifying.
Sets the salt length for RSA_PKCS1_PSS_PADDING to the maximum permissible value when signing data.
Applies multiple bug workarounds within OpenSSL. See https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html for detail.
Instructs OpenSSL to allow a non-[EC]DHE-based key exchange mode for TLS v1.3
Allows legacy insecure renegotiation between OpenSSL and unpatched clients or servers. See https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html.
Attempts to use the server's preferences instead of the client's when selecting a cipher. See https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html.
Instructs OpenSSL to use Cisco's version identifier of DTLS_BAD_VER.
Instructs OpenSSL to add server-hello extension from an early version of the cryptopro draft.
Instructs OpenSSL to disable a SSL 3.0/TLS 1.0 vulnerability workaround added in OpenSSL 0.9.6d.
Allows initial connection to servers that do not support RI.
Instructs OpenSSL to disable support for SSL/TLS compression.
Instructs OpenSSL to disable encrypt-then-MAC.
Instructs OpenSSL to disable renegotiation.
Instructs OpenSSL to always start a new session when performing renegotiation.
Instructs OpenSSL to turn off SSL v2
Instructs OpenSSL to turn off SSL v3
Instructs OpenSSL to disable use of RFC4507bis tickets.
Instructs OpenSSL to turn off TLS v1
Instructs OpenSSL to turn off TLS v1.1
Instructs OpenSSL to turn off TLS v1.2
Instructs OpenSSL to turn off TLS v1.3
Instructs OpenSSL server to prioritize ChaCha20-Poly1305 when the client does. This option has no effect if SSL_OP_CIPHER_SERVER_PREFERENCE is not enabled.
Instructs OpenSSL to disable version rollback attack detection.
Creates and returns a Cipher object, with the given algorithm, key and
initialization vector (iv).
Creates and returns a Decipher object that uses the given algorithm, keyand initialization vector (iv).
Creates a DiffieHellman key exchange object using the supplied prime and an
optional specific generator.
An alias for getDiffieHellman
Creates an Elliptic Curve Diffie-Hellman (ECDH) key exchange object using a
predefined curve specified by the curveName string. Use getCurves to obtain a list of available curve names. On recent
OpenSSL releases, openssl ecparam -list_curves will also display the name
and description of each available elliptic curve.
Creates and returns a Hash object that can be used to generate hash digests
using the given algorithm. Optional options argument controls stream
behavior. For XOF hash functions such as 'shake256', the outputLength option
can be used to specify the desired output length in bytes.
Creates and returns an Hmac object that uses the given algorithm and key.
Optional options argument controls stream behavior.
Creates and returns a new key object containing a private key. If key is a
string or Buffer, format is assumed to be 'pem'; otherwise, keymust be an object with the properties described above.
Creates and returns a new key object containing a public key. If key is a
string or Buffer, format is assumed to be 'pem'; if key is a KeyObjectwith type 'private', the public key is derived from the given private key;
otherwise, key must be an object with the properties described above.
Creates and returns a new key object containing a secret key for symmetric
encryption or Hmac.
Creates and returns a Sign object that uses the given algorithm. Use getHashes to obtain the names of the available digest algorithms.
Optional options argument controls the stream.Writable behavior.
Creates and returns a Verify object that uses the given algorithm.
Use getHashes to obtain an array of names of the available
signing algorithms. Optional options argument controls thestream.Writable behavior.
Instances of the Decipher class are used to decrypt data. The class can be
used in one of two ways:
The DiffieHellman class is a utility for creating Diffie-Hellman key
exchanges.
Computes the Diffie-Hellman secret based on a privateKey and a publicKey.
Both keys must have the same asymmetricKeyType, which must be one of 'dh'(for Diffie-Hellman), 'ec' (for ECDH), 'x448', or 'x25519' (for ECDH-ES).
The ECDH class is a utility for creating Elliptic Curve Diffie-Hellman (ECDH)
key exchanges.
Asynchronously generates a new random secret key of the given length. Thetype will determine which validations will be performed on the length.
Generates a new asymmetric key pair of the given type. RSA, RSA-PSS, DSA, EC,
Ed25519, Ed448, X25519, X448, and DH are currently supported.
Generates a new asymmetric key pair of the given type. RSA, RSA-PSS, DSA, EC,
Ed25519, Ed448, X25519, X448, and DH are currently supported.
Synchronously generates a new random secret key of the given length. Thetype will determine which validations will be performed on the length.
Generates a pseudorandom prime of size bits.
Generates a pseudorandom prime of size bits.
Returns information about a given cipher.
Creates a predefined DiffieHellmanGroup key exchange object. The
supported groups are listed in the documentation for DiffieHellmanGroup.
A convenient alias for webcrypto.getRandomValues. This implementation is not compliant with the Web Crypto spec, to write web-compatible code use webcrypto.getRandomValues instead.
The Hash class is a utility for creating hash digests of data. It can be
used in one of two ways:
HKDF is a simple key derivation function defined in RFC 5869. The given ikm,salt and info are used with the digest to derive a key of keylen bytes.
Provides a synchronous HKDF key derivation function as defined in RFC 5869. The
given ikm, salt and info are used with the digest to derive a key ofkeylen bytes.
The Hmac class is a utility for creating cryptographic HMAC digests. It can
be used in one of two ways:
Node.js uses a KeyObject class to represent a symmetric or asymmetric key,
and each kind of key exposes different functions. The createSecretKey, createPublicKey and createPrivateKey methods are used to create KeyObjectinstances. KeyObject
objects are not to be created directly using the newkeyword.
Provides an asynchronous Password-Based Key Derivation Function 2 (PBKDF2)
implementation. A selected HMAC digest algorithm specified by digest is
applied to derive a key of the requested byte length (keylen) from thepassword, salt and iterations.
Provides a synchronous Password-Based Key Derivation Function 2 (PBKDF2)
implementation. A selected HMAC digest algorithm specified by digest is
applied to derive a key of the requested byte length (keylen) from thepassword, salt and iterations.
Decrypts buffer with privateKey. buffer was previously encrypted using
the corresponding public key, for example using publicEncrypt.
Encrypts buffer with privateKey. The returned data can be decrypted using
the corresponding public key, for example using publicDecrypt.
Decrypts buffer with key.buffer was previously encrypted using
the corresponding private key, for example using privateEncrypt.
Encrypts the content of buffer with key and returns a new Buffer with encrypted content. The returned data can be decrypted using
the corresponding private key, for example using privateDecrypt.
Generates cryptographically strong pseudorandom data. The size argument
is a number indicating the number of bytes to generate.
This function is similar to randomBytes but requires the first
argument to be a Buffer that will be filled. It also
requires that a callback is passed in.
Synchronous version of randomFill.
Return a random integer n such that min <= n < max. This
implementation avoids modulo bias.
Generates a random RFC 4122 version 4 UUID. The UUID is generated using a cryptographic pseudorandom number generator.
Provides a synchronous scrypt implementation. Scrypt is a password-based key derivation function that is designed to be expensive computationally and memory-wise in order to make brute-force attacks unrewarding.
Load and set the engine for some or all OpenSSL functions (selected by flags).
Enables the FIPS compliant crypto provider in a FIPS-enabled Node.js build. Throws an error if FIPS mode is not available.
The Sign class is a utility for generating signatures. It can be used in one
of two ways:
Calculates and returns the signature for data using the given private key and
algorithm. If algorithm is null or undefined, then the algorithm is
dependent upon the key type (especially Ed25519 and Ed448).
A convenient alias for crypto.webcrypto.subtle.
This function compares the underlying bytes that represent the givenArrayBuffer, TypedArray, or DataView instances using a constant-time
algorithm.
The Verify class is a utility for verifying signatures. It can be used in one
of two ways:
Verifies the given signature for data using the given key and algorithm. Ifalgorithm is null or undefined, then the algorithm is dependent upon the
key type (especially Ed25519 and Ed448).
Calling require('node:crypto').webcrypto returns an instance of the Crypto class.
Crypto is a singleton that provides access to the remainder of the crypto API.
The CryptoKeyPair is a simple dictionary object with publicKey and privateKey properties, representing an asymmetric key pair.
Encapsulates an X509 certificate and provides read-only access to its information.
Creates and returns a Cipher object that uses the given algorithm andpassword.
Creates and returns a Decipher object that uses the given algorithm andpassword (key).
dgram
The node:dgram module provides an implementation of UDP datagram sockets.
Creates a dgram.Socket object. Once the socket is created, calling socket.bind() will instruct the socket to begin listening for datagram
messages. When address and port are not passed to socket.bind() the
method will bind the socket to the "all interfaces" address on a random port
(it does the right thing for both udp4 and udp6 sockets). The bound address
and port can be retrieved using socket.address().address and socket.address().port.
Encapsulates the datagram functionality.
diagnostics_channel
The node:diagnostics_channel module provides an API to create named channels
to report arbitrary message data for diagnostics purposes.
The class Channel represents an individual named channel within the data
pipeline. It is used to track subscribers and to publish messages when there
are subscribers present. It exists as a separate object to avoid channel
lookups at publish time, enabling very fast publish speeds and allowing
for heavy use while incurring very minimal cost. Channels are created with channel, constructing a channel directly
with new Channel(name) is not supported.
This is the primary entry-point for anyone wanting to publish to a named channel. It produces a channel object which is optimized to reduce overhead at publish time as much as possible.
Check if there are active subscribers to the named channel. This is helpful if the message you want to send might be expensive to prepare.
Register a message handler to subscribe to this channel. This message handler
will be run synchronously whenever a message is published to the channel. Any
errors thrown in the message handler will trigger an 'uncaughtException'.
The class TracingChannel is a collection of TracingChannel Channels which
together express a single traceable action. It is used to formalize and
simplify the process of producing events for tracing application flow.tracingChannel is used to construct aTracingChannel. As with Channel it is recommended to create and reuse a
single TracingChannel at the top-level of the file rather than creating them
dynamically.
Creates a TracingChannel wrapper for the given TracingChannel Channels. If a name is given, the corresponding tracing
channels will be created in the form of tracing:${name}:${eventType} whereeventType corresponds to the types of TracingChannel Channels.
Remove a message handler previously registered to this channel with subscribe.
dns
The node:dns module enables name resolution. For example, use it to look up IP
addresses of host names.
Limits returned address types to the types of non-loopback addresses configured on the system. For example, IPv4 addresses are only returned if the current system has at least one IPv4 address configured.
If dns.V4MAPPED is specified, return resolved IPv6 addresses as
well as IPv4 mapped IPv6 addresses.
Get the default value for verbatim in lookup and dnsPromises.lookup().
The value could be:
Returns an array of IP address strings, formatted according to RFC 5952, that are currently configured for DNS resolution. A string will include a port section if a custom port is used.
Resolves a host name (e.g. 'nodejs.org') into the first found A (IPv4) or
AAAA (IPv6) record. All option properties are optional. If options is an
integer, then it must be 4 or 6 – if options is 0 or not provided, then
IPv4 and IPv6 addresses are both returned if found.
Resolves the given address and port into a host name and service using
the operating system's underlying getnameinfo implementation.
The dns.promises API provides an alternative set of asynchronous DNS methods
that return Promise objects rather than using callbacks. The API is accessible
via require('node:dns').promises or require('node:dns/promises').
Get the default value for verbatim in lookup and dnsPromises.lookup().
The value could be:
Returns an array of IP address strings, formatted according to RFC 5952, that are currently configured for DNS resolution. A string will include a port section if a custom port is used.
Resolves a host name (e.g. 'nodejs.org') into the first found A (IPv4) or
AAAA (IPv6) record. All option properties are optional. If options is an
integer, then it must be 4 or 6 – if options is not provided, then IPv4
and IPv6 addresses are both returned if found.
Resolves the given address and port into a host name and service using
the operating system's underlying getnameinfo implementation.
Uses the DNS protocol to resolve a host name (e.g. 'nodejs.org') into an array
of the resource records. When successful, the Promise is resolved with an
array of resource records. The type and structure of individual results vary
based on rrtype:
Uses the DNS protocol to resolve IPv4 addresses (A records) for the hostname. On success, the Promise is resolved with an array of IPv4
addresses (e.g. ['74.125.79.104', '74.125.79.105', '74.125.79.106']).
Uses the DNS protocol to resolve IPv6 addresses (AAAA records) for the hostname. On success, the Promise is resolved with an array of IPv6
addresses.
Uses the DNS protocol to resolve all records (also known as ANY or * query).
On success, the Promise is resolved with an array containing various types of
records. Each object has a property type that indicates the type of the
current record. And depending on the type, additional properties will be
present on the object:
Uses the DNS protocol to resolve CAA records for the hostname. On success,
the Promise is resolved with an array of objects containing available
certification authority authorization records available for the hostname (e.g. [{critical: 0, iodef: 'mailto:pki@example.com'},{critical: 128, issue: 'pki.example.com'}]).
Uses the DNS protocol to resolve CNAME records for the hostname. On success,
the Promise is resolved with an array of canonical name records available for
the hostname (e.g. ['bar.example.com']).
Uses the DNS protocol to resolve mail exchange records (MX records) for the hostname. On success, the Promise is resolved with an array of objects
containing both a priority and exchange property (e.g.[{priority: 10, exchange: 'mx.example.com'}, ...]).
Uses the DNS protocol to resolve regular expression-based records (NAPTR records) for the hostname. On success, the Promise is resolved with an array
of objects with the following properties:
Uses the DNS protocol to resolve name server records (NS records) for the hostname. On success, the Promise is resolved with an array of name server
records available for hostname (e.g.['ns1.example.com', 'ns2.example.com']).
Uses the DNS protocol to resolve pointer records (PTR records) for the hostname. On success, the Promise is resolved with an array of strings
containing the reply records.
An independent resolver for DNS requests.
Uses the DNS protocol to resolve a start of authority record (SOA record) for
the hostname. On success, the Promise is resolved with an object with the
following properties:
Uses the DNS protocol to resolve service records (SRV records) for the hostname. On success, the Promise is resolved with an array of objects with
the following properties:
Uses the DNS protocol to resolve text queries (TXT records) for the hostname. On success, the Promise is resolved with a two-dimensional array
of the text records available for hostname (e.g.[ ['v=spf1 ip4:0.0.0.0 ', '~all' ] ]). Each sub-array contains TXT chunks of
one record. Depending on the use case, these could be either joined together or
treated separately.
Performs a reverse DNS query that resolves an IPv4 or IPv6 address to an array of host names.
Set the default value of verbatim in dns.lookup() and dnsPromises.lookup(). The value could be:
Sets the IP address and port of servers to be used when performing DNS
resolution. The servers argument is an array of RFC 5952 formatted
addresses. If the port is the IANA default DNS port (53) it can be omitted.
Uses the DNS protocol to resolve a host name (e.g. 'nodejs.org') into an array
of the resource records. The callback function has arguments (err, records). When successful, records will be an array of resource
records. The type and structure of individual results varies based on rrtype:
Uses the DNS protocol to resolve a IPv4 addresses (A records) for the hostname. The addresses argument passed to the callback function
will contain an array of IPv4 addresses (e.g.['74.125.79.104', '74.125.79.105', '74.125.79.106']).
Uses the DNS protocol to resolve IPv6 addresses (AAAA records) for the hostname. The addresses argument passed to the callback function
will contain an array of IPv6 addresses.
Uses the DNS protocol to resolve all records (also known as ANY or * query).
The ret argument passed to the callback function will be an array containing
various types of records. Each object has a property type that indicates the
type of the current record. And depending on the type, additional properties
will be present on the object:
Uses the DNS protocol to resolve CAA records for the hostname. The addresses argument passed to the callback function
will contain an array of certification authority authorization records
available for the hostname (e.g. [{critical: 0, iodef: 'mailto:pki@example.com'}, {critical: 128, issue: 'pki.example.com'}]).
Uses the DNS protocol to resolve CNAME records for the hostname. The addresses argument passed to the callback function
will contain an array of canonical name records available for the hostname (e.g. ['bar.example.com']).
Uses the DNS protocol to resolve mail exchange records (MX records) for the hostname. The addresses argument passed to the callback function will
contain an array of objects containing both a priority and exchange property (e.g. [{priority: 10, exchange: 'mx.example.com'}, ...]).
Uses the DNS protocol to resolve regular expression-based records (NAPTR records) for the hostname. The addresses argument passed to the callback function will contain an array of
objects with the following properties:
Uses the DNS protocol to resolve name server records (NS records) for the hostname. The addresses argument passed to the callback function will
contain an array of name server records available for hostname (e.g. ['ns1.example.com', 'ns2.example.com']).
Uses the DNS protocol to resolve pointer records (PTR records) for the hostname. The addresses argument passed to the callback function will
be an array of strings containing the reply records.
An independent resolver for DNS requests.
Uses the DNS protocol to resolve a start of authority record (SOA record) for
the hostname. The address argument passed to the callback function will
be an object with the following properties:
Uses the DNS protocol to resolve service records (SRV records) for the hostname. The addresses argument passed to the callback function will
be an array of objects with the following properties:
Uses the DNS protocol to resolve text queries (TXT records) for the hostname. The records argument passed to the callback function is a
two-dimensional array of the text records available for hostname (e.g.[ ['v=spf1 ip4:0.0.0.0 ', '~all' ] ]). Each sub-array contains TXT chunks of
one record. Depending on the use case, these could be either joined together or
treated separately.
Performs a reverse DNS query that resolves an IPv4 or IPv6 address to an array of host names.
Set the default value of verbatim in lookup and dnsPromises.lookup().
The value could be:
Sets the IP address and port of servers to be used when performing DNS
resolution. The servers argument is an array of RFC 5952 formatted
addresses. If the port is the IANA default DNS port (53) it can be omitted.
If the IPv6 family was specified, but no IPv6 addresses were found, then return IPv4 mapped IPv6 addresses. It is not supported on some operating systems (e.g. FreeBSD 10.1).
dns/promises
The dns.promises API provides an alternative set of asynchronous DNS methods
that return Promise objects rather than using callbacks. The API is accessible
via require('node:dns').promises or require('node:dns/promises').
Get the default value for verbatim in lookup and dnsPromises.lookup().
The value could be:
Returns an array of IP address strings, formatted according to RFC 5952, that are currently configured for DNS resolution. A string will include a port section if a custom port is used.
Resolves a host name (e.g. 'nodejs.org') into the first found A (IPv4) or
AAAA (IPv6) record. All option properties are optional. If options is an
integer, then it must be 4 or 6 – if options is not provided, then IPv4
and IPv6 addresses are both returned if found.
Resolves the given address and port into a host name and service using
the operating system's underlying getnameinfo implementation.
Uses the DNS protocol to resolve a host name (e.g. 'nodejs.org') into an array
of the resource records. When successful, the Promise is resolved with an
array of resource records. The type and structure of individual results vary
based on rrtype:
Uses the DNS protocol to resolve IPv4 addresses (A records) for the hostname. On success, the Promise is resolved with an array of IPv4
addresses (e.g. ['74.125.79.104', '74.125.79.105', '74.125.79.106']).
Uses the DNS protocol to resolve IPv6 addresses (AAAA records) for the hostname. On success, the Promise is resolved with an array of IPv6
addresses.
Uses the DNS protocol to resolve all records (also known as ANY or * query).
On success, the Promise is resolved with an array containing various types of
records. Each object has a property type that indicates the type of the
current record. And depending on the type, additional properties will be
present on the object:
Uses the DNS protocol to resolve CAA records for the hostname. On success,
the Promise is resolved with an array of objects containing available
certification authority authorization records available for the hostname (e.g. [{critical: 0, iodef: 'mailto:pki@example.com'},{critical: 128, issue: 'pki.example.com'}]).
Uses the DNS protocol to resolve CNAME records for the hostname. On success,
the Promise is resolved with an array of canonical name records available for
the hostname (e.g. ['bar.example.com']).
Uses the DNS protocol to resolve mail exchange records (MX records) for the hostname. On success, the Promise is resolved with an array of objects
containing both a priority and exchange property (e.g.[{priority: 10, exchange: 'mx.example.com'}, ...]).
Uses the DNS protocol to resolve regular expression-based records (NAPTR records) for the hostname. On success, the Promise is resolved with an array
of objects with the following properties:
Uses the DNS protocol to resolve name server records (NS records) for the hostname. On success, the Promise is resolved with an array of name server
records available for hostname (e.g.['ns1.example.com', 'ns2.example.com']).
Uses the DNS protocol to resolve pointer records (PTR records) for the hostname. On success, the Promise is resolved with an array of strings
containing the reply records.
An independent resolver for DNS requests.
Uses the DNS protocol to resolve a start of authority record (SOA record) for
the hostname. On success, the Promise is resolved with an object with the
following properties:
Uses the DNS protocol to resolve service records (SRV records) for the hostname. On success, the Promise is resolved with an array of objects with
the following properties:
Uses the DNS protocol to resolve text queries (TXT records) for the hostname. On success, the Promise is resolved with a two-dimensional array
of the text records available for hostname (e.g.[ ['v=spf1 ip4:0.0.0.0 ', '~all' ] ]). Each sub-array contains TXT chunks of
one record. Depending on the use case, these could be either joined together or
treated separately.
Performs a reverse DNS query that resolves an IPv4 or IPv6 address to an array of host names.
Set the default value of verbatim in dns.lookup() and dnsPromises.lookup(). The value could be:
Sets the IP address and port of servers to be used when performing DNS
resolution. The servers argument is an array of RFC 5952 formatted
addresses. If the port is the IANA default DNS port (53) it can be omitted.
domain
This module is pending deprecation. Once a replacement API has been finalized, this module will be fully deprecated. Most developers should not have cause to use this module. Users who absolutely must have the functionality that domains provide may rely on it for the time being but should expect to have to migrate to a different solution in the future.
events
Much of the Node.js core API is built around an idiomatic asynchronous
event-driven architecture in which certain kinds of objects (called "emitters")
emit named events that cause Function objects ("listeners") to be called.
The EventEmitter class is defined and exposed by the node:events module:
Integrates EventEmitter with AsyncResource for EventEmitters that
require manual async tracking. Specifically, all events emitted by instances
of events.EventEmitterAsyncResource will run within its async context.
fs
The node:fs module enables interacting with the file system in a
way modeled on standard POSIX functions.
Tests a user's permissions for the file or directory specified by path.
The mode argument is an optional integer that specifies the accessibility
checks to be performed. mode should be either the value fs.constants.F_OKor a mask consisting of the bitwise OR of any of fs.constants.R_OK,fs.constants.W_OK, and fs.constants.X_OK
(e.g.fs.constants.W_OK | fs.constants.R_OK). Check File access constants for
possible values of mode.
Synchronously tests a user's permissions for the file or directory specified
by path. The mode argument is an optional integer that specifies the
accessibility checks to be performed. mode should be either the valuefs.constants.F_OK or a mask consisting of the bitwise OR of any offs.constants.R_OK, fs.constants.W_OK, and
fs.constants.X_OK (e.g.fs.constants.W_OK | fs.constants.R_OK). Check File access constants for
possible values of mode.
Asynchronously append data to a file, creating the file if it does not yet
exist. data can be a string or a Buffer.
Synchronously append data to a file, creating the file if it does not yet
exist. data can be a string or a Buffer.
Asynchronously changes the permissions of a file. No arguments other than a possible exception are given to the completion callback.
For detailed information, see the documentation of the asynchronous version of this API: chmod.
Asynchronously changes owner and group of a file. No arguments other than a possible exception are given to the completion callback.
Synchronously changes owner and group of a file. Returns undefined.
This is the synchronous version of chown.
Closes the file descriptor. No arguments other than a possible exception are given to the completion callback.
Closes the file descriptor. Returns undefined.
Constant for fs.copyFile. Flag indicating the destination file should not be overwritten if it already exists.
Constant for fs.copyFile. copy operation will attempt to create a copy-on-write reflink. If the underlying platform does not support copy-on-write, then a fallback copy mechanism is used.
Constant for fs.copyFile. Copy operation will attempt to create a copy-on-write reflink. If the underlying platform does not support copy-on-write, then the operation will fail with an error.
Constant for fs.access(). File is visible to the calling process.
Constant for fs.open(). Flag indicating that data will be appended to the end of the file.
Constant for fs.open(). Flag indicating to create the file if it does not already exist.
Constant for fs.open(). When set, an attempt will be made to minimize caching effects of file I/O.
Constant for fs.open(). Flag indicating that the open should fail if the path is not a directory.
Constant for fs.open(). Flag indicating that the file is opened for synchronous I/O with write operations waiting for data integrity.
Constant for fs.open(). Flag indicating that opening a file should fail if the O_CREAT flag is set and the file already exists.
constant for fs.open(). Flag indicating reading accesses to the file system will no longer result in an update to the atime information associated with the file. This flag is available on Linux operating systems only.
Constant for fs.open(). Flag indicating that if path identifies a terminal device, opening the path shall not cause that terminal to become the controlling terminal for the process (if the process does not already have one).
Constant for fs.open(). Flag indicating that the open should fail if the path is a symbolic link.
Constant for fs.open(). Flag indicating to open the file in nonblocking mode when possible.
Constant for fs.open(). Flag indicating to open a file for read-only access.
Constant for fs.open(). Flag indicating to open a file for read-write access.
Constant for fs.open(). Flag indicating to open the symbolic link itself rather than the resource it is pointing to.
Constant for fs.open(). Flag indicating that the file is opened for synchronous I/O.
Constant for fs.open(). Flag indicating that if the file exists and is a regular file, and the file is opened successfully for write access, its length shall be truncated to zero.
Constant for fs.open(). Flag indicating to open a file for write-only access.
Constant for fs.access(). File can be read by the calling process.
Constant for fs.Stats mode property for determining a file's type. File type constant for a block-oriented device file.
Constant for fs.Stats mode property for determining a file's type. File type constant for a character-oriented device file.
Constant for fs.Stats mode property for determining a file's type. File type constant for a directory.
Constant for fs.Stats mode property for determining a file's type. File type constant for a FIFO/pipe.
Constant for fs.Stats mode property for determining a file's type. File type constant for a symbolic link.
Constant for fs.Stats mode property for determining a file's type. Bit mask used to extract the file type code.
Constant for fs.Stats mode property for determining a file's type. File type constant for a regular file.
Constant for fs.Stats mode property for determining a file's type. File type constant for a socket.
Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by group.
Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by others.
Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by owner.
Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by group.
Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by others.
Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by owner.
Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by group.
Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by others.
Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by owner.
Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by group.
Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by others.
Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by owner.
When set, a memory file mapping is used to access the file. This flag is available on Windows operating systems only. On other operating systems, this flag is ignored.
Constant for fs.access(). File can be written by the calling process.
Constant for fs.access(). File can be executed by the calling process.
Asynchronously copies src to dest. By default, dest is overwritten if it
already exists. No arguments other than a possible exception are given to the
callback function. Node.js makes no guarantees about the atomicity of the copy
operation. If an error occurs after the destination file has been opened for
writing, Node.js will attempt to remove the destination.
Synchronously copies src to dest. By default, dest is overwritten if it
already exists. Returns undefined. Node.js makes no guarantees about the
atomicity of the copy operation. If an error occurs after the destination file
has been opened for writing, Node.js will attempt to remove the destination.
Asynchronously copies the entire directory structure from src to dest,
including subdirectories and files.
Synchronously copies the entire directory structure from src to dest,
including subdirectories and files.
Unlike the 16 KiB default highWaterMark for a stream.Readable, the stream
returned by this method has a default highWaterMark of 64 KiB.
options may also include a start option to allow writing data at some
position past the beginning of the file, allowed values are in the
[0, Number.MAX_SAFE_INTEGER] range. Modifying a file rather than
replacing it may require the flags option to be set to r+ rather than the
default w. The encoding can be any one of those accepted by Buffer.
A class representing a directory stream.
A representation of a directory entry, which can be a file or a subdirectory
within the directory, as returned by reading from an fs.Dir. The
directory entry is a combination of the file name and file type pairs.
Returns true if the path exists, false otherwise.
Sets the permissions on the file. No arguments other than a possible exception are given to the completion callback.
Sets the permissions on the file. Returns undefined.
Sets the owner of the file. No arguments other than a possible exception are given to the completion callback.
Sets the owner of the file. Returns undefined.
Forces all currently queued I/O operations associated with the file to the
operating system's synchronized I/O completion state. Refer to the POSIX fdatasync(2) documentation for details. No arguments other
than a possible
exception are given to the completion callback.
Forces all currently queued I/O operations associated with the file to the
operating system's synchronized I/O completion state. Refer to the POSIX fdatasync(2) documentation for details. Returns undefined.
Invokes the callback with the fs.Stats for the file descriptor.
Retrieves the fs.Stats for the file descriptor.
Request that all data for the open file descriptor is flushed to the storage
device. The specific implementation is operating system and device specific.
Refer to the POSIX fsync(2) documentation for more detail. No arguments other
than a possible exception are given to the completion callback.
Truncates the file descriptor. No arguments other than a possible exception are given to the completion callback.
Truncates the file descriptor. Returns undefined.
Change the file system timestamps of the object referenced by the supplied file descriptor. See utimes.
Synchronous version of futimes. Returns undefined.
Set the owner of the symbolic link. No arguments other than a possible exception are given to the completion callback.
Set the owner for the path. Returns undefined.
Retrieves the fs.Stats for the symbolic link referred to by the path.
The callback gets two arguments (err, stats) where stats is a fs.Stats object. lstat() is identical to stat(), except that if path is a symbolic
link, then the link itself is stat-ed, not the file that it refers to.
Synchronous lstat(2) - Get file status. Does not dereference symbolic links.
Changes the access and modification times of a file in the same way as utimes, with the difference that if the path refers to a symbolic link, then the link is not dereferenced: instead, the timestamps of the symbolic link itself are changed.
Change the file system timestamps of the symbolic link referenced by path.
Returns undefined, or throws an exception when parameters are incorrect or
the operation fails. This is the synchronous version of lutimes.
Asynchronously creates a directory.
Synchronously creates a directory. Returns undefined, or if recursive istrue, the first directory path created.
This is the synchronous version of mkdir.
Creates a unique temporary directory.
Returns the created directory path.
Returns a Blob whose data is backed by the given file.
Asynchronously open a directory. See the POSIX opendir(3) documentation for
more details.
Synchronously open a directory. See opendir(3).
Returns an integer representing the file descriptor.
Valid types for path values in "fs".
The fs/promises API provides asynchronous file system methods that return
promises.
Tests a user's permissions for the file or directory specified by path.
The mode argument is an optional integer that specifies the accessibility
checks to be performed. mode should be either the value fs.constants.F_OKor a mask consisting of the bitwise OR of any of fs.constants.R_OK,fs.constants.W_OK, and fs.constants.X_OK
(e.g.fs.constants.W_OK | fs.constants.R_OK). Check File access constants for
possible values of mode.
Asynchronously append data to a file, creating the file if it does not yet
exist. data can be a string or a Buffer.
Changes the permissions of a file.
Changes the ownership of a file.
Asynchronously copies src to dest. By default, dest is overwritten if it
already exists.
Asynchronously copies the entire directory structure from src to dest,
including subdirectories and files.
Changes the ownership on a symbolic link.
Creates a new link from the existingPath to the newPath. See the POSIX link(2) documentation for more detail.
Equivalent to fsPromises.stat() unless path refers to a symbolic link,
in which case the link itself is stat-ed, not the file that it refers to.
Refer to the POSIX lstat(2) document for more detail.
Changes the access and modification times of a file in the same way as fsPromises.utimes(), with the difference that if the path refers to a
symbolic link, then the link is not dereferenced: instead, the timestamps of
the symbolic link itself are changed.
Asynchronously creates a directory.
Creates a unique temporary directory. A unique directory name is generated by
appending six random characters to the end of the provided prefix. Due to
platform inconsistencies, avoid trailing X characters in prefix. Some
platforms, notably the BSDs, can return more than six random characters, and
replace trailing X characters in prefix with random characters.
Opens a FileHandle.
Asynchronously open a directory for iterative scanning. See the POSIX opendir(3) documentation for more detail.
Reads the contents of a directory.
Asynchronously reads the entire contents of a file.
Reads the contents of the symbolic link referred to by path. See the POSIX readlink(2) documentation for more detail. The promise is
fulfilled with thelinkString upon success.
Determines the actual location of path using the same semantics as thefs.realpath.native() function.
Renames oldPath to newPath.
Removes files and directories (modeled on the standard POSIX rm utility).
Removes the directory identified by path.
Creates a symbolic link.
Truncates (shortens or extends the length) of the content at path to lenbytes.
If path refers to a symbolic link, then the link is removed without affecting
the file or directory to which that link refers. If the path refers to a file
path that is not a symbolic link, the file is deleted. See the POSIX unlink(2) documentation for more detail.
Change the file system timestamps of the object referenced by path.
Returns an async iterator that watches for changes on filename, where filenameis either a file or a directory.
Asynchronously writes data to a file, replacing the file if it already exists.data can be a string, a buffer, an
AsyncIterable, or an
Iterable object.
Read data from the file specified by fd.
Reads the contents of a directory. The callback gets two arguments (err, files)where files is an array of the names of the files in the directory excluding'.' and '..'.
Reads the contents of the directory.
Asynchronously reads the entire contents of a file.
Returns the contents of the path.
Reads the contents of the symbolic link referred to by path. The callback gets
two arguments (err, linkString).
Returns the symbolic link's string value.
Instances of fs.ReadStream are created and returned using the createReadStream function.
Returns the number of bytesRead.
Read from a file specified by fd and write to an array of ArrayBufferViews
using readv().
For detailed information, see the documentation of the asynchronous version of this API: readv.
Asynchronously computes the canonical pathname by resolving ., .., and
symbolic links.
Asynchronous realpath(3).
Returns the resolved pathname.
Asynchronously rename file at oldPath to the pathname provided
as newPath. In the case that newPath already exists, it will
be overwritten. If there is a directory at newPath, an error will
be raised instead. No arguments other than a possible exception are
given to the completion callback.
Renames the file from oldPath to newPath. Returns undefined.
Asynchronously removes files and directories (modeled on the standard POSIX rmutility). No arguments other than a possible exception are given to the
completion callback.
Synchronously removes files and directories (modeled on the standard POSIX rmutility). Returns undefined.
Synchronous statfs(2). Returns information about the mounted file system which
contains path.
A fs.Stats object provides information about a file.
Provides information about a mounted file system.
Synchronous stat(2) - Get file status.
Class: fs.StatWatcher
Creates the link called path pointing to target. No arguments other than a
possible exception are given to the completion callback.
Returns undefined.
Truncates the file. No arguments other than a possible exception are
given to the completion callback. A file descriptor can also be passed as the
first argument. In this case, fs.ftruncate() is called.
Truncates the file. Returns undefined. A file descriptor can also be
passed as the first argument. In this case, fs.ftruncateSync() is called.
Asynchronously removes a file or symbolic link. No arguments other than a possible exception are given to the completion callback.
Synchronous unlink(2). Returns undefined.
Stop watching for changes on filename. If listener is specified, only that
particular listener is removed. Otherwise, all listeners are removed,
effectively stopping watching of filename.
Change the file system timestamps of the object referenced by path.
Returns undefined.
Watch for changes on filename, where filename is either a file or a
directory.
Watch for changes on filename. The callback listener will be called each
time the file is accessed.
Watch for changes on filename. The callback listener will be called each
time the file is accessed.
Write buffer to the file specified by fd.
When file is a filename, asynchronously writes data to the file, replacing the
file if it already exists. data can be a string or a buffer.
Returns undefined.
- Extends
stream.Writable
For detailed information, see the documentation of the asynchronous version of this API: write.
Write an array of ArrayBufferViews to the file specified by fd usingwritev().
For detailed information, see the documentation of the asynchronous version of this API: writev.
Test whether or not the given path exists by checking with the file system.
Then call the callback argument with either true or false:
Changes the permissions on a symbolic link. No arguments other than a possible exception are given to the completion callback.
Changes the permissions on a symbolic link. Returns undefined.
Changes the permissions on a symbolic link.
fs/promises
The fs/promises API provides asynchronous file system methods that return
promises.
Tests a user's permissions for the file or directory specified by path.
The mode argument is an optional integer that specifies the accessibility
checks to be performed. mode should be either the value fs.constants.F_OKor a mask consisting of the bitwise OR of any of fs.constants.R_OK,fs.constants.W_OK, and fs.constants.X_OK
(e.g.fs.constants.W_OK | fs.constants.R_OK). Check File access constants for
possible values of mode.
Asynchronously append data to a file, creating the file if it does not yet
exist. data can be a string or a Buffer.
Changes the permissions of a file.
Changes the ownership of a file.
Asynchronously copies src to dest. By default, dest is overwritten if it
already exists.
Asynchronously copies the entire directory structure from src to dest,
including subdirectories and files.
Changes the ownership on a symbolic link.
Changes the access and modification times of a file in the same way as fsPromises.utimes(), with the difference that if the path refers to a
symbolic link, then the link is not dereferenced: instead, the timestamps of
the symbolic link itself are changed.
Asynchronously creates a directory.
Creates a unique temporary directory. A unique directory name is generated by
appending six random characters to the end of the provided prefix. Due to
platform inconsistencies, avoid trailing X characters in prefix. Some
platforms, notably the BSDs, can return more than six random characters, and
replace trailing X characters in prefix with random characters.
Opens a FileHandle.
Asynchronously open a directory for iterative scanning. See the POSIX opendir(3) documentation for more detail.
Reads the contents of a directory.
Asynchronously reads the entire contents of a file.
Reads the contents of the symbolic link referred to by path. See the POSIX readlink(2) documentation for more detail. The promise is
fulfilled with thelinkString upon success.
Determines the actual location of path using the same semantics as thefs.realpath.native() function.
Renames oldPath to newPath.
Removes files and directories (modeled on the standard POSIX rm utility).
Removes the directory identified by path.
Creates a symbolic link.
Truncates (shortens or extends the length) of the content at path to lenbytes.
Change the file system timestamps of the object referenced by path.
Returns an async iterator that watches for changes on filename, where filenameis either a file or a directory.
Asynchronously writes data to a file, replacing the file if it already exists.data can be a string, a buffer, an
AsyncIterable, or an
Iterable object.
Changes the permissions on a symbolic link.
http
To use the HTTP server and client one must require('node:http').
An Agent is responsible for managing connection persistence
and reuse for HTTP clients. It maintains a queue of pending requests
for a given host and port, reusing a single socket connection for each
until the queue is empty, at which time the socket is either destroyed
or put into a pool where it is kept to be used again for requests to the
same host and port. Whether it is destroyed or pooled depends on thekeepAlive option.
This object is created internally and returned from request. It
represents an in-progress request whose header has already been queued. The
header is still mutable using the setHeader(name, value),getHeader(name), removeHeader(name) API. The actual header will
be sent along with the first data chunk or when calling request.end().
Returns a new instance of Server.
Since most requests are GET requests without bodies, Node.js provides this
convenience method. The only difference between this method and request is that it sets the method to GET by default and calls req.end()automatically. The callback must take care to
consume the response
data for reasons stated in ClientRequest section.
An IncomingMessage object is created by Server or ClientRequest and passed as the first argument to the 'request' and 'response' event respectively. It may be used to
access response
status, headers, and data.
Read-only property specifying the maximum allowed size of HTTP headers in bytes.
Defaults to 16KB. Configurable using the --max-http-header-size CLI option.
This class serves as the parent class of ClientRequest and ServerResponse. It is an abstract outgoing message from the perspective of the participants of an HTTP transaction.
options in socket.connect() are also supported.
This object is created internally by an HTTP server, not by the user. It is
passed as the second parameter to the 'request' event.
Set the maximum number of idle HTTP parsers.
Performs the low-level validations on the provided name that are done whenres.setHeader(name, value) is called.
Performs the low-level validations on the provided value that are done whenres.setHeader(name, value) is called.
http2
The node:http2 module provides an implementation of the HTTP/2 protocol.
It can be accessed using:
Returns a ClientHttp2Session instance.
Returns a tls.Server instance that creates and manages Http2Sessioninstances.
Returns a net.Server instance that creates and manages Http2Sessioninstances.
Returns an object containing the default settings for an Http2Sessioninstance. This method returns a new object instance every time it is called
so instances returned may be safely modified for use.
Returns a Buffer instance containing serialized representation of the given
HTTP/2 settings as specified in the HTTP/2 specification. This is intended
for use with the HTTP2-Settings header field.
Returns a HTTP/2 Settings Object containing the deserialized settings from
the given Buffer as generated by http2.getPackedSettings().
A Http2ServerRequest object is created by Server or SecureServer and passed as the first argument to the 'request' event. It may be used to access a request status,
headers, and
data.
This object is created internally by an HTTP server, not by the user. It is
passed as the second parameter to the 'request' event.
This symbol can be set as a property on the HTTP/2 headers object with an array value in order to provide a list of headers considered sensitive.
https
HTTPS is the HTTP protocol over TLS/SSL. In Node.js this is implemented as a separate module.
An Agent object for HTTPS similar to http.Agent. See request for more information.
Like http.get() but for HTTPS.
Makes a request to a secure web server.
See http.Server for more information.
inspector
The node:inspector module provides an API for interacting with the V8
inspector.
Deactivate the inspector. Blocks until there are no active connections.
Console message.
Breakpoint identifier.
JavaScript call frame. Array of call frames form the call stack.
Call frame identifier.
Location in the source code.
Scope description.
Location in the source code.
Search match for resource.
Heap snapshot object id.
Profile.
Sampling Heap Profile node. Holds callsite information, allocation statistics and child nodes.
Unique identifier of attached debugging session.
Activate inspector on host and port. Equivalent tonode --inspect=[[host:]port], but can be done programmatically after node has
started.
Coverage data for a source range.
Coverage data for a JavaScript function.
Specifies a number of samples attributed to a certain source position.
Profile.
Profile node. Holds callsite information, execution statistics and child nodes.
Coverage data for a JavaScript script.
Type profile data collected during runtime for a JavaScript script.
Describes a type collected during runtime.
Source offset and types for a parameter or return value.
Represents function call argument. Either remote object id objectId, primitive value, unserializable primitive value or neither of (for undefined) them should be specified.
Stack entry for runtime errors and assertions.
Detailed information about exception (or error) that was thrown during script compilation or execution.
Description of an isolated world.
Id of an execution context.
Object internal property descriptor. This property isn't normally visible in JavaScript code.
Object containing abbreviated remote object value.
Object property descriptor.
Mirror object referencing original JavaScript object.
Unique object identifier.
Unique script identifier.
Call frames for assertions or error messages.
If debuggerId is set stack trace comes from another debugger and can be resolved there. This allows to track cross-debugger calls. See Runtime.StackTrace and Debugger.paused for usages.
Number of milliseconds since epoch.
Unique identifier of current debugger.
Primitive value which cannot be JSON-stringified.
Description of the protocol domain.
The inspector.Session is used for dispatching messages to the V8 inspector
back-end and receiving message responses and notifications.
Return the URL of the active inspector, or undefined if there is none.
Blocks until a client (existing or connected later) has sentRuntime.runIfWaitingForDebugger command.
path is the resolved path for the file for which a corresponding source map
should be fetched.
The initialize hook provides a way to define a custom function that runs in the hooks thread
when the hooks module is initialized. Initialization happens when the hooks module is registered via register.
The load hook provides a way to define a custom method of determining how a URL should be interpreted, retrieved, and parsed.
It is also in charge of validating the import assertion.
The resolve hook chain is responsible for resolving file URL for a given module specifier and parent URL, and optionally its format (such as 'module') as a hint to the load hook.
If a format is specified, the load hook is ultimately responsible for providing the final format value (and it is free to ignore the hint provided by resolve);
if resolve provides a format, a custom load hook is required even if only to pass the value to the Node.js default load hook.
The module.syncBuiltinESMExports() method updates all the live bindings for
builtin ES Modules to match the properties of the CommonJS exports. It
does not add or remove exported names from the ES Modules.
net
Stability: 2 - Stable
The BlockList object can be used with some network APIs to specify rules for
disabling inbound or outbound access to specific IP addresses, IP ranges, or
IP subnets.
Aliases to createConnection.
A factory function, which creates a new Socket,
immediately initiates connection with socket.connect(),
then returns the net.Socket that starts the connection.
Creates a new TCP or IPC server.
Gets the current default value of the autoSelectFamily option of socket.connect(options).
The initial default value is true, unless the command line option--no-network-family-autoselection is provided.
Gets the current default value of the autoSelectFamilyAttemptTimeout option of socket.connect(options).
The initial default value is 250.
Returns 6 if input is an IPv6 address. Returns 4 if input is an IPv4
address in dot-decimal notation with no leading zeroes. Otherwise, returns0.
Returns true if input is an IPv4 address in dot-decimal notation with no
leading zeroes. Otherwise, returns false.
Returns true if input is an IPv6 address. Otherwise, returns false.
This class is used to create a TCP or IPC server.
Sets the default value of the autoSelectFamily option of socket.connect(options).
Sets the default value of the autoSelectFamilyAttemptTimeout option of socket.connect(options).
This class is an abstraction of a TCP socket or a streaming IPC endpoint
(uses named pipes on Windows, and Unix domain sockets otherwise). It is also
an EventEmitter.
os
The node:os module provides operating system-related utility methods and
properties. It can be accessed using:
Returns the operating system CPU architecture for which the Node.js binary was
compiled. Possible values are 'arm', 'arm64', 'ia32', 'loong64','mips', 'mipsel', 'ppc', 'ppc64', 'riscv64', 's390', 's390x',
and 'x64'.
Returns an estimate of the default amount of parallelism a program should use. Always returns a value greater than zero.
The node:os module provides operating system-related utility methods and
properties. It can be accessed using:
Returns an array of objects containing information about each logical CPU core.
The array will be empty if no CPU information is available, such as if the/proc file system is unavailable.
Returns a string identifying the endianness of the CPU for which the Node.js binary was compiled.
Returns the amount of free system memory in bytes as an integer.
Returns the scheduling priority for the process specified by pid. If pid is
not provided or is 0, the priority of the current process is returned.
Returns the string path of the current user's home directory.
Returns the host name of the operating system as a string.
Returns an array containing the 1, 5, and 15 minute load averages.
Returns the machine type as a string, such as arm, arm64, aarch64,mips, mips64, ppc64, ppc64le, s390, s390x, i386, i686, x86_64.
Returns an object containing network interfaces that have been assigned a network address.
Returns a string identifying the operating system platform for which
the Node.js binary was compiled. The value is set at compile time.
Possible values are 'aix', 'darwin', 'freebsd','linux','openbsd', 'sunos', and 'win32'.
Returns the operating system as a string.
Attempts to set the scheduling priority for the process specified by pid. Ifpid is not provided or is 0, the process ID of the current process is used.
Returns the operating system's default directory for temporary files as a string.
Returns the total amount of system memory in bytes as an integer.
Returns the system uptime in number of seconds.
Returns information about the currently effective user. On POSIX platforms,
this is typically a subset of the password file. The returned object includes
the username, uid, gid, shell, and homedir. On Windows, the uid andgid fields are -1, and shell is null.
Returns a string identifying the kernel version.
path
The node:path module provides utilities for working with file and directory
paths. It can be accessed using:
The node:path module provides utilities for working with file and directory
paths. It can be accessed using:
A parsed path object generated by path.parse() or consumed by path.format().
The node:path module provides utilities for working with file and directory
paths. It can be accessed using:
A parsed path object generated by path.parse() or consumed by path.format().
perf_hooks
This module provides an implementation of a subset of the W3C Web Performance APIs as well as additional APIs for Node.js-specific performance measurements.
Returns a RecordableHistogram.
This property is an extension by Node.js. It is not available in Web browsers.
The constructor of this class is not exposed to users directly.
Exposes marks created via the Performance.mark() method.
Exposes measures created via the Performance.measure() method.
This property is an extension by Node.js. It is not available in Web browsers.
Most of the time the unhandledRejection will be an Error, but this should not be relied upon as anything can be thrown/rejected, it is therefore unsafe to assume that the value is an Error.
punycode
**The version of the punycode module bundled in Node.js is being deprecated.**In a future major version of Node.js this module will be removed. Users
currently depending on the punycode module should switch to using the
userland-provided Punycode.js module instead. For punycode-based URL
encoding, see url.domainToASCII or, more generally, the WHATWG URL API.
querystring
The node:querystring module provides utilities for parsing and formatting URL
query strings. It can be accessed using:
The querystring.decode() function is an alias for querystring.parse().
The querystring.encode() function is an alias for querystring.stringify().
The querystring.escape() method performs URL percent-encoding on the givenstr in a manner that is optimized for the specific requirements of URL
query strings.
The querystring.parse() method parses a URL query string (str) into a
collection of key and value pairs.
The querystring.stringify() method produces a URL query string from a
given obj by iterating through the object's "own properties".
The node:querystring module provides utilities for parsing and formatting URL
query strings. It can be accessed using:
The querystring.unescape() method performs decoding of URL percent-encoded
characters on the given str.
readline
The node:readline module provides an interface for reading data from a Readable stream (such as process.stdin) one line at a time.
The readline.clearLine() method clears current line of given TTY stream
in a specified direction identified by dir.
The readline.clearScreenDown() method clears the given TTY stream from
the current position of the cursor down.
The readline.createInterface() method creates a new readline.Interfaceinstance.
The readline.cursorTo() method moves cursor to the specified position in a
given TTY stream.
The readline.emitKeypressEvents() method causes the given Readable stream to begin emitting 'keypress' events corresponding to received input.
Instances of the readline.Interface class are constructed using thereadline.createInterface() method. Every instance is associated with a
single input Readable stream and a single output Writable stream.
The output stream is used to print prompts for user input that arrives on,
and is read from, the input stream.
The readline.moveCursor() method moves the cursor relative to its current
position in a given TTY stream.
The readlinePromises.createInterface() method creates a new readlinePromises.Interfaceinstance.
Instances of the readlinePromises.Interface class are constructed using thereadlinePromises.createInterface() method. Every instance is associated with a
single input Readable stream and a single output Writable stream.
The output stream is used to print prompts for user input that arrives on,
and is read from, the input stream.
The readlinePromises.createInterface() method creates a new readlinePromises.Interfaceinstance.
Instances of the readlinePromises.Interface class are constructed using thereadlinePromises.createInterface() method. Every instance is associated with a
single input Readable stream and a single output Writable stream.
The output stream is used to print prompts for user input that arrives on,
and is read from, the input stream.
repl
The node:repl module provides a Read-Eval-Print-Loop (REPL) implementation
that is available both as a standalone program or includible in other
applications. It can be accessed using:
Indicates a recoverable error that a REPLServer can use to support multi-line input.
A flag passed in the REPL options. Evaluates expressions in sloppy mode.
A flag passed in the REPL options. Evaluates expressions in strict mode.
This is equivalent to prefacing every repl statement with 'use strict'.
Instances of repl.REPLServer are created using the start method
or directly using the JavaScript new keyword.
The repl.start() method creates and starts a REPLServer instance.
This is the default "writer" value, if none is passed in the REPL options, and it can be overridden by custom print functions.
sea
This feature allows the distribution of a Node.js application conveniently to a system that does not have Node.js installed.
This feature allows the distribution of a Node.js application conveniently to a system that does not have Node.js installed.
This method can be used to retrieve the assets configured to be bundled into the single-executable application at build time. An error is thrown when no matching asset can be found.
Similar to sea.getAsset(), but returns the result in a Blob.
An error is thrown when no matching asset can be found.
This method can be used to retrieve the assets configured to be bundled into the single-executable application at build time. An error is thrown when no matching asset can be found.
stream
A stream is an abstract interface for working with streaming data in Node.js.
The node:stream module provides an API for implementing the stream interface.
A stream to attach a signal to.
Duplex streams are streams that implement both the Readable and Writable interfaces.
A readable and/or writable stream/webstream.
Returns the default highWaterMark used by streams.
Defaults to 16384 (16 KiB), or 16 for objectMode.
Returns whether the stream has encountered an error.
Returns whether the stream is readable.
The stream.PassThrough class is a trivial implementation of a Transform stream that simply passes the input bytes across to the output. Its purpose is
primarily for examples and testing, but there are some use cases wherestream.PassThrough is useful as a building block for novel sorts of streams.
A module method to pipe between streams and generators forwarding errors and properly cleaning up and provide a callback when the pipeline is complete.
Sets the default highWaterMark used by streams.
Transform streams are Duplex streams where the output is in some way
related to the input. Like all Duplex streams, Transform streams
implement both the Readable and Writable interfaces.
A stream to attach a signal to.
Duplex streams are streams that implement both the Readable and Writable interfaces.
A readable and/or writable stream/webstream.
Returns the default highWaterMark used by streams.
Defaults to 16384 (16 KiB), or 16 for objectMode.
Returns whether the stream has encountered an error.
Returns whether the stream is readable.
The stream.PassThrough class is a trivial implementation of a Transform stream that simply passes the input bytes across to the output. Its purpose is
primarily for examples and testing, but there are some use cases wherestream.PassThrough is useful as a building block for novel sorts of streams.
A module method to pipe between streams and generators forwarding errors and properly cleaning up and provide a callback when the pipeline is complete.
Sets the default highWaterMark used by streams.
Transform streams are Duplex streams where the output is in some way
related to the input. Like all Duplex streams, Transform streams
implement both the Readable and Writable interfaces.
This Streams API interface provides a built-in byte length queuing strategy that can be used when constructing streams.
This Streams API interface provides a built-in byte length queuing strategy that can be used when constructing streams.
This Streams API interface represents a readable stream of byte data.
This Streams API interface provides a standard abstraction for writing streaming data to a destination, known as a sink. This object comes with built-in back pressure and queuing.
This Streams API interface represents a controller allowing control of a WritableStream's state. When constructing a WritableStream, the underlying sink is given a corresponding WritableStreamDefaultController instance to manipulate.
This Streams API interface is the object returned by WritableStream.getWriter() and once created locks the < writer to the WritableStream ensuring that no other streams can write to the underlying sink.
string_decoder
The node:string_decoder module provides an API for decoding Buffer objects
into strings in a manner that preserves encoded multi-byte UTF-8 and UTF-16
characters. It can be accessed using:
The node:string_decoder module provides an API for decoding Buffer objects
into strings in a manner that preserves encoded multi-byte UTF-8 and UTF-16
characters. It can be accessed using:
test/reporters
The node:test/reporters module exposes the builtin-reporters for node:test.
To access it:
The dot reporter outputs the test results in a compact format,
where each passing test is represented by a .,
and each failing test is represented by a X.
The junit reporter outputs test results in a jUnit XML format
The spec reporter outputs the test results in a human-readable format.
The spec reporter outputs the test results in a human-readable format.
timers
The timer module exposes a global API for scheduling functions to
be called at some future period of time. Because the timer functions are
globals, there is no need to call require('node:timers') to use the API.
Cancels an Immediate object created by setImmediate().
Cancels a Timeout object created by setInterval().
Cancels a Timeout object created by setTimeout().
This object is created internally and is returned from setImmediate(). It
can be passed to clearImmediate() in order to cancel the scheduled
actions.
Schedules the "immediate" execution of the callback after I/O events'
callbacks.
Schedules repeated execution of callback every delay milliseconds.
Schedules execution of a one-time callback after delay milliseconds.
This object is created internally and is returned from setTimeout() and setInterval(). It can be passed to either clearTimeout() or clearInterval() in order to cancel the
scheduled actions.
timers/promises
The timers/promises API provides an alternative set of timer functions
that return Promise objects. The API is accessible viarequire('node:timers/promises').
Returns an async iterator that generates values in an interval of delay ms.
If ref is true, you need to call next() of async iterator explicitly
or implicitly to keep the event loop alive.
tls
The node:tls module provides an implementation of the Transport Layer Security
(TLS) and Secure Socket Layer (SSL) protocols that is built on top of OpenSSL.
The module can be accessed using:
Verifies the certificate cert is issued to hostname.
The callback function, if specified, will be added as a listener for the 'secureConnect' event.
createServer sets the default value of the honorCipherOrder option
to true, other APIs that create secure contexts leave it unset.
Creates a new Server. The secureConnectionListener, if provided, is
automatically set as a listener for the 'secureConnection' event.
The default value of the ciphers option of tls.createSecureContext(). It can be assigned any of the supported OpenSSL ciphers. Defaults to the content of crypto.constants.defaultCoreCipherList, unless changed using CLI options using --tls-default-ciphers.
The default curve name to use for ECDH key agreement in a tls server. The default value is 'auto'. See tls.createSecureContext() for further information.
The default value of the maxVersion option of tls.createSecureContext(). It can be assigned any of the supported TLS protocol versions, 'TLSv1.3', 'TLSv1.2', 'TLSv1.1', or 'TLSv1'. Default: 'TLSv1.3', unless changed using CLI options. Using --tls-max-v1.2 sets the default to 'TLSv1.2'. Using --tls-max-v1.3 sets the default to 'TLSv1.3'. If multiple of the options are provided, the highest maximum is used.
The default value of the minVersion option of tls.createSecureContext(). It can be assigned any of the supported TLS protocol versions, 'TLSv1.3', 'TLSv1.2', 'TLSv1.1', or 'TLSv1'. Default: 'TLSv1.2', unless changed using CLI options. Using --tls-min-v1.0 sets the default to 'TLSv1'. Using --tls-min-v1.1 sets the default to 'TLSv1.1'. Using --tls-min-v1.3 sets the default to 'TLSv1.3'. If multiple of the options are provided, the lowest minimum is used.
Returns an array with the names of the supported TLS ciphers. The names are
lower-case for historical reasons, but must be uppercased to be used in
the ciphers option of createSecureContext.
An immutable array of strings representing the root certificates (in PEM format) used for verifying peer certificates. This is the default value of the ca option to tls.createSecureContext().
Accepts encrypted connections using TLS or SSL.
Performs transparent encryption of written data and all required TLS negotiation.
Creates a new secure pair object with two streams, one of which reads and writes the encrypted data and the other of which reads and writes the cleartext data. Generally, the encrypted stream is piped to/from an incoming encrypted data stream and the cleartext one is used as a replacement for the initial encrypted stream.
trace_events
The node:trace_events module provides a mechanism to centralize tracing
information generated by V8, Node.js core, and userspace code.
Creates and returns a Tracing object for the given set of categories.
Returns a comma-separated list of all currently-enabled trace event
categories. The current set of enabled trace event categories is determined
by the union of all currently-enabled Tracing objects and any categories
enabled using the --trace-event-categories flag.
The Tracing object is used to enable or disable tracing for sets of
categories. Instances are created using the
trace_events.createTracing() method.
tty
The node:tty module provides the tty.ReadStream and tty.WriteStreamclasses. In most cases, it will not be necessary or possible to use this module
directly. However, it can be accessed using:
-1 - to the left from cursor 0 - the entire line 1 - to the right from cursor
The tty.isatty() method returns true if the given fd is associated with
a TTY and false if it is not, including whenever fd is not a non-negative
integer.
Represents the readable side of a TTY. In normal circumstances process.stdin will be the only tty.ReadStream instance in a Node.js
process and there should be no reason to create additional instances.
Represents the writable side of a TTY. In normal circumstances,process.stdout and process.stderr will be the onlytty.WriteStream instances created for a Node.js process and there
should be no reason to create additional instances.
url
The node:url module provides utilities for URL resolution and parsing. It can
be accessed using:
Returns the Punycode ASCII serialization of the domain. If domain is an
invalid domain, the empty string is returned.
Returns the Unicode serialization of the domain. If domain is an invalid
domain, the empty string is returned.
This function ensures the correct decodings of percent-encoded characters as well as ensuring a cross-platform valid absolute path string.
The url.format() method returns a formatted URL string derived from urlObject.
This function ensures that path is resolved absolutely, and that the URL
control characters are correctly encoded when converting into a File URL.
The url.resolve() method resolves a target URL relative to a base URL in a
manner similar to that of a web browser resolving an anchor tag.
Browser-compatible URL class, implemented by following the WHATWG URL
Standard. Examples of parsed URLs may be found in the Standard itself.
The URL class is also available on the global object.
The URLSearchParams API provides read and write access to the query of a URL. The URLSearchParams class can also be used standalone with one of the
four following constructors.
The URLSearchParams class is also available on the global object.
This utility function converts a URL object into an ordinary options object as
expected by the http.request() and https.request() APIs.
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:
Listens to abort event on the provided signal and
returns a promise that is fulfilled when the signal is
aborted. If the passed resource is garbage collected before the signal is
aborted, the returned promise shall remain pending indefinitely.
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 Promiseresolved), 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:
This function is identical to format, except in that it takes
an inspectOptions argument which specifies options that are passed along to inspect.
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.
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 andextends 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.
That can be used to declare custom inspect functions.
Allows changing inspect settings from the repl.
Returns true if there is deep strict equality between val1 and val2.
Otherwise, returns false.
The MIMEParams API provides read and write access to the parameters of aMIMEType.
An implementation of the MIMEType class.
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.
That can be used to declare custom promisified variants of functions.
Returns str with any ANSI escape codes removed.
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.
Returns the string after replacing any surrogate code points
(or equivalently, any unpaired surrogate code units) with the
Unicode "replacement character" U+FFFD.
Creates and returns an AbortController instance whose AbortSignal is marked
as transferable and can be used with structuredClone() or postMessage().
Marks the given AbortSignal as transferable so that it can be used withstructuredClone() and postMessage().
Returns true if the value is a built-in ArrayBuffer or
SharedArrayBuffer instance.
Returns true if the value is an arguments object.
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 BigInt64Array instance.
Returns true if the value is a BigUint64Array instance.
Returns true if the value is a boolean object, e.g. created
by new Boolean().
Returns true if the value is any boxed primitive object, e.g. created
by new Boolean(), new String() or Object(Symbol()).
Returns true if value is a CryptoKey, false otherwise.
Returns true if the value is a built-in DataView instance.
Returns true if the value is a built-in Date instance.
Returns true if the value is a native External value.
Returns true if the value is a built-in Float32Array instance.
Returns true if the value is a built-in Float64Array instance.
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 is a built-in Int16Array instance.
Returns true if the value is a built-in Int32Array instance.
Returns true if the value is a built-in Int8Array instance.
Returns true if value is a KeyObject, false otherwise.
Returns true if the value is a built-in Map instance.
Returns true if the value is an iterator returned for a built-in Map instance.
Returns true if the value is an instance of a Module Namespace Object.
Returns true if the value was returned by the constructor of a built-in Error type.
Returns true if the value is a number object, e.g. created
by new Number().
Returns true if the value is a built-in Promise.
Returns true if the value is a Proxy instance.
Returns true if the value is a regular expression object.
Returns true if the value is a built-in Set instance.
Returns true if the value is an iterator returned for a built-in Set instance.
Returns true if the value is a string object, e.g. created
by new String().
Returns true if the value is a symbol object, created
by calling Object() on a Symbol primitive.
Returns true if the value is a built-in TypedArray instance.
Returns true if the value is a built-in Uint16Array instance.
Returns true if the value is a built-in Uint32Array instance.
Returns true if the value is a built-in Uint8Array instance.
Returns true if the value is a built-in Uint8ClampedArray instance.
Returns true if the value is a built-in WeakMap instance.
Returns true if the value is a built-in WeakSet instance.
Alias for Array.isArray().
Returns true if the given object is a Boolean. Otherwise, returns false.
Returns true if the given object is a Buffer. Otherwise, returns false.
Returns true if the given object is a Date. Otherwise, returns false.
Returns true if the given object is an Error. Otherwise, returnsfalse.
Returns true if the given object is a Function. Otherwise, returnsfalse.
Returns true if the given object is strictly null. Otherwise, returnsfalse.
Returns true if the given object is null or undefined. Otherwise,
returns false.
Returns true if the given object is a Number. Otherwise, returns false.
Returns true if the given object is strictly an Objectand not aFunction (even though functions are objects in JavaScript).
Otherwise, returns false.
Returns true if the given object is a primitive type. Otherwise, returnsfalse.
Returns true if the given object is a RegExp. Otherwise, returns false.
Returns true if the given object is a string. Otherwise, returns false.
Returns true if the given object is a Symbol. Otherwise, returns false.
Returns true if the given object is undefined. Otherwise, returns false.
The util.log() method prints the given string to stdout with an included
timestamp.
Returns true if the value is a built-in ArrayBuffer or
SharedArrayBuffer instance.
Returns true if the value is an arguments object.
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 BigInt64Array instance.
Returns true if the value is a BigUint64Array instance.
Returns true if the value is a boolean object, e.g. created
by new Boolean().
Returns true if the value is any boxed primitive object, e.g. created
by new Boolean(), new String() or Object(Symbol()).
Returns true if value is a CryptoKey, false otherwise.
Returns true if the value is a built-in DataView instance.
Returns true if the value is a native External value.
Returns true if the value is a built-in Float32Array instance.
Returns true if the value is a built-in Float64Array instance.
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 is a built-in Int16Array instance.
Returns true if the value is a built-in Int32Array instance.
Returns true if the value is a built-in Int8Array instance.
Returns true if value is a KeyObject, false otherwise.
Returns true if the value is an iterator returned for a built-in Map instance.
Returns true if the value is an instance of a Module Namespace Object.
Returns true if the value was returned by the constructor of a built-in Error type.
Returns true if the value is a number object, e.g. created
by new Number().
Returns true if the value is a regular expression object.
Returns true if the value is an iterator returned for a built-in Set instance.
Returns true if the value is a string object, e.g. created
by new String().
Returns true if the value is a symbol object, created
by calling Object() on a Symbol primitive.
Returns true if the value is a built-in TypedArray instance.
Returns true if the value is a built-in Uint16Array instance.
Returns true if the value is a built-in Uint32Array instance.
Returns true if the value is a built-in Uint8Array instance.
Returns true if the value is a built-in Uint8ClampedArray instance.
v8
The node:v8 module exposes APIs that are specific to the version of V8 built into the Node.js binary. It can be accessed using:
Called immediately after a promise continuation executes. This may be after a then(), catch(), or finally() handler or before an await after another await.
Called before a promise continuation executes. This can be in the form of then(), catch(), or finally() handlers or an await resuming.
Returns an integer representing a version tag derived from the V8 version,
command-line flags, and detected CPU features. This is useful for determining
whether a vm.Script cachedData buffer is compatible with this instance
of V8.
A subclass of Deserializer corresponding to the format written by DefaultSerializer.
A subclass of Serializer that serializes TypedArray(in particular Buffer) and DataView objects as host objects, and only
stores the part of their underlying ArrayBuffers that they are referring to.
Uses a DefaultDeserializer with default options to read a JS value
from a buffer.
This API collects GC data in current thread.
Get statistics about code and its metadata in the heap, see
V8 GetHeapCodeAndMetadataStatistics API. Returns an object with the
following properties:
Generates a snapshot of the current V8 heap and returns a Readable Stream that may be used to read the JSON serialized representation. This JSON stream format is intended to be used with tools such as Chrome DevTools. The JSON schema is undocumented and specific to the V8 engine. Therefore, the schema may change from one version of V8 to the next.
Returns statistics about the V8 heap spaces, i.e. the segments which make up
the V8 heap. Neither the ordering of heap spaces, nor the availability of a
heap space can be guaranteed as the statistics are provided via the
V8 GetHeapSpaceStatistics function and may change from one V8 version to the
next.
Returns an object with the following properties:
Key events in the lifetime of a promise have been categorized into four areas: creation of a promise, before/after a continuation handler is called or around an await, and when the promise resolves or rejects.
Called when a promise is constructed. This does not mean that corresponding before/after events will occur, only that the possibility exists. This will happen if a promise is created without ever getting a continuation.
The promiseHooks interface can be used to track promise lifecycle events.
Uses a DefaultSerializer to serialize value into a buffer.
The v8.setFlagsFromString() method can be used to programmatically set
V8 command-line flags. This method should be used with care. Changing settings
after the VM has started may result in unpredictable behavior, including
crashes and data loss; or it may simply do nothing.
The API is a no-op if --heapsnapshot-near-heap-limit is already set from the command line or the API is called more than once.
limit must be a positive integer. See --heapsnapshot-near-heap-limit for more information.
Called when the promise receives a resolution or rejection value. This may occur synchronously in the case of Promise.resolve() or Promise.reject().
The v8.startupSnapshot interface can be used to add serialization and deserialization hooks for custom startup snapshots.
The v8.stopCoverage() method allows the user to stop the coverage collection
started by NODE_V8_COVERAGE, so that V8 can release the execution count
records and optimize code. This can be used in conjunction with takeCoverage if the user wants to collect the coverage on demand.
The v8.takeCoverage() method allows the user to write the coverage started by NODE_V8_COVERAGE to disk on demand. This method can be invoked multiple
times during the lifetime of the process. Each time the execution counter will
be reset and a new coverage report will be written to the directory specified
by NODE_V8_COVERAGE.
Generates a snapshot of the current V8 heap and writes it to a JSON file. This file is intended to be used with tools such as Chrome DevTools. The JSON schema is undocumented and specific to the V8 engine, and may change from one version of V8 to the next.
vm
The node:vm module enables compiling and running code within V8 Virtual
Machine contexts.
Compiles the given code into the provided context (if no context is
supplied, the current context is used), and returns it wrapped inside a
function with the given params.
If given a contextObject, the vm.createContext() method will prepare that object so that it can be used in calls to runInContext or script.runInContext(). Inside such scripts,
the contextObject will be the global object, retaining all of its existing
properties but also having the built-in objects and functions any standard global object has. Outside of scripts run by the vm module, global variables
will remain unchanged.
Returns true if the given object object has been contextified using createContext.
Measure the memory known to V8 and used by all contexts known to the current V8 isolate, or the main context.
This feature is only available with the --experimental-vm-modules command
flag enabled.
The vm.runInContext() method compiles code, runs it within the context of
the contextifiedObject, then returns the result. Running code does not have
access to the local scope. The contextifiedObject object must have been
previously contextified using the createContext method.
The vm.runInNewContext() first contextifies the given contextObject (or
creates a new contextObject if passed as undefined), compiles the code,
runs it within the created context, then returns the result. Running code
does not have access to the local scope.
vm.runInThisContext() compiles code, runs it within the context of the
current global and returns the result. Running code does not have access to
local scope, but does have access to the current global object.
Instances of the vm.Script class contain precompiled scripts that can be
executed in specific contexts.
This feature is only available with the --experimental-vm-modules command
flag enabled.
This feature is only available with the --experimental-vm-modules command
flag enabled.
wasi
The node:wasi module does not currently provide the
comprehensive file system security properties provided by some WASI runtimes.
Full support for secure file system sandboxing may or may not be implemented in
future. In the mean time, do not rely on it to run untrusted code.
The WASI class provides the WASI system call API and additional convenience
methods for working with WASI-based applications. Each WASI instance
represents a distinct environment.
The node:wasi module does not currently provide the
comprehensive file system security properties provided by some WASI runtimes.
Full support for secure file system sandboxing may or may not be implemented in
future. In the mean time, do not rely on it to run untrusted code.
worker_threads
The node:worker_threads module enables the use of threads that execute
JavaScript in parallel. To access it:
Instances of BroadcastChannel allow asynchronous one-to-many communication
with all other BroadcastChannel instances bound to the same channel name.
Within a worker thread, worker.getEnvironmentData() returns a clone
of data passed to the spawning thread's worker.setEnvironmentData().
Every new Worker receives its own copy of the environment data
automatically.
Mark an object as not transferable. If object occurs in the transfer list of
a port.postMessage() call, it is ignored.
Instances of the worker.MessageChannel class represent an asynchronous,
two-way communications channel.
The MessageChannel has no methods of its own. new MessageChannel()yields an object with port1 and port2 properties, which refer to linked MessagePort instances.
Instances of the worker.MessagePort class represent one end of an
asynchronous, two-way communications channel. It can be used to transfer
structured data, memory regions and other MessagePorts between different Worker s.
Transfer a MessagePort to a different vm Context. The original portobject is rendered unusable, and the returned MessagePort instance
takes its place.
Receive a single message from a given MessagePort. If no message is available,undefined is returned, otherwise an object with a single message property
that contains the message payload, corresponding to the oldest message in theMessagePort's queue.
The worker.setEnvironmentData() API sets the content ofworker.getEnvironmentData() in the current thread and all new Workerinstances spawned from the current context.
The Worker class represents an independent JavaScript execution thread.
Most Node.js APIs are available inside of it.
zlib
The node:zlib module provides compression functionality implemented using
Gzip, Deflate/Inflate, and Brotli.
Compress a chunk of data with BrotliCompress.
Decompress a chunk of data with BrotliDecompress.
Creates and returns a new BrotliCompress object.
Creates and returns a new BrotliDecompress object.
Creates and returns a new Deflate object.
Creates and returns a new DeflateRaw object.
Creates and returns a new Gunzip object.
Creates and returns a new Gzip object.
See example.
Creates and returns a new Inflate object.
Creates and returns a new InflateRaw object.
Creates and returns a new Unzip object.
Compress a chunk of data with DeflateRaw.
Compress a chunk of data with Deflate.
Decompress a chunk of data with Gunzip.
Compress a chunk of data with Gzip.
Decompress a chunk of data with InflateRaw.
Decompress a chunk of data with Inflate.
Decompress a chunk of data with Unzip.