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:assert
module 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 for ifError()
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 to assert.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.
async_hooks
We strongly discourage the use of the async_hooks
API.
Other APIs that can cover most of its use cases include:
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.
Promise contexts may not get valid triggerAsyncId
s by default. See
the section on promise execution tracking.
buffer
Buffer
objects are used to represent a fixed-length sequence of bytes. Many
Node.js APIs support Buffer
s.
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.
- compare
- copy
- equals
- fill
- includes
- indexOf
- lastIndexOf
- readBigInt64BE
- readBigInt64LE
- readBigUInt64BE
- readBigUInt64LE
- readBigUint64BE
- readBigUint64LE
- readDoubleBE
- readDoubleLE
- readFloatBE
- readFloatLE
- readInt16BE
- readInt16LE
- readInt32BE
- readInt32LE
- readInt8
- readIntBE
- readIntLE
- readUInt16BE
- readUInt16LE
- readUInt32BE
- readUInt32LE
- readUInt8
- readUIntBE
- readUIntLE
- readUint16BE
- readUint16LE
- readUint32BE
- readUint32LE
- readUint8
- readUintBE
- readUintLE
- reverse
- slice
- subarray
- swap16
- swap32
- swap64
- toJSON
- toString
- write
- writeBigInt64BE
- writeBigInt64LE
- writeBigUInt64BE
- writeBigUInt64LE
- writeBigUint64BE
- writeBigUint64LE
- writeDoubleBE
- writeDoubleLE
- writeFloatBE
- writeFloatLE
- writeInt16BE
- writeInt16LE
- writeInt32BE
- writeInt32LE
- writeInt8
- writeIntBE
- writeIntLE
- writeUInt16BE
- writeUInt16LE
- writeUInt32BE
- writeUInt32LE
- writeUInt8
- writeUIntBE
- writeUIntLE
- writeUint16BE
- writeUint16LE
- writeUint32BE
- writeUint32LE
- writeUint8
- writeUintBE
- writeUintLE
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.
Instances of the ChildProcess
represent spawned child processes.
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 SIGTERM
signal 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 given command
, 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.
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.
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
, key
and 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, key
must 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 KeyObject
with 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 the stream.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).
Asynchronously generates a new random secret key of the given length
. The type
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.
Synchronously generates a new random secret key of the given length
. The type
will determine which validations will be performed on the length
.
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.
A utility for creating one-shot hash digests of data. It can be faster than the object-based crypto.createHash()
when hashing a smaller amount of data
(<= 5MB) that's readily available. If the data can be big or if it is streamed, it's still recommended to use crypto.createHash()
instead. The algorithm
is dependent on the available algorithms supported by the version of OpenSSL on the platform. Examples are 'sha256'
, 'sha512'
, etc. On recent releases
of OpenSSL, openssl list -digest-algorithms
will display the available digest algorithms.
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 of keylen
bytes.
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 the password
, 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 the password
, 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.
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.
Enables the FIPS compliant crypto provider in a FIPS-enabled Node.js build. Throws an error if FIPS mode is not available.
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 given ArrayBuffer
, TypedArray
, or DataView
instances using a constant-time
algorithm.
Verifies the given signature for data
using the given key and algorithm. If algorithm
is null
or undefined
, then the algorithm is dependent upon the
key type (especially Ed25519 and Ed448).
Importing the webcrypto
object (import { webcrypto } from 'node:crypto'
) gives 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.
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
.
- addListener
- addMembership
- addSourceSpecificMembership
- address
- bind
- close
- connect
- disconnect
- dropMembership
- dropSourceSpecificMembership
- emit
- getRecvBufferSize
- getSendBufferSize
- getSendQueueCount
- getSendQueueSize
- on
- once
- prependListener
- prependOnceListener
- ref
- remoteAddress
- send
- setBroadcast
- setMulticastInterface
- setMulticastLoopback
- setMulticastTTL
- setRecvBufferSize
- setSendBufferSize
- setTTL
- unref
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 a TracingChannel
. 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}
where eventType
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 order
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 import { promises as dnsPromises } from 'node:dns'
or import dnsPromises from '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.
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 order
in dns.lookup()
and [lookup](././dns/~/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.
Performs a reverse DNS query that resolves an IPv4 or IPv6 address to an array of host names.
Set the default value of order
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 import { promises as dnsPromises } from 'node:dns'
or import dnsPromises from '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.
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 order
in dns.lookup()
and [lookup](././dns/promises/~/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.
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 EventEmitter
s 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_OK
or 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 value fs.constants.F_OK
or 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
.
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.
Asynchronously changes owner and group of a file. No arguments other than a possible exception are given to the completion callback.
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 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
.
Synchronous version of futimes. Returns undefined
.
Retrieves the files matching the specified pattern.
Retrieves the files matching the specified pattern.
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.
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.
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_OK
or 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.
Retrieves the files matching the specified pattern.
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 the fs.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 len
bytes.
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 filename
is 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 ArrayBufferView
s
using 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 rm
utility). No arguments other than a possible exception are given to the
completion callback.
Synchronously removes files and directories (modeled on the standard POSIX rm
utility). 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.
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
.
stream.Writable
Write an array of ArrayBufferView
s to the file specified by fd
using writev()
.
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
.
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_OK
or 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.
Retrieves the files matching the specified pattern.
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 the fs.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 len
bytes.
Change the file system timestamps of the object referenced by path
.
Returns an async iterator that watches for changes on filename
, where filename
is 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.
http
To use the HTTP server and client one must import the node:http
module.
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 the keepAlive
option
.
Returns a new instance of Server.
Global instance of Agent
which is used as the default for all HTTP client
requests. Diverges from a default Agent
configuration by having keepAlive
enabled and a timeout
of 5 seconds.
- accept
- accept-language
- accept-patch
- accept-ranges
- access-control-allow-credentials
- access-control-allow-headers
- access-control-allow-methods
- access-control-allow-origin
- access-control-expose-headers
- access-control-max-age
- access-control-request-headers
- access-control-request-method
- age
- allow
- alt-svc
- authorization
- cache-control
- connection
- content-disposition
- content-encoding
- content-language
- content-length
- content-location
- content-range
- content-type
- cookie
- date
- etag
- expect
- expires
- forwarded
- from
- host
- if-match
- if-modified-since
- if-none-match
- if-unmodified-since
- last-modified
- location
- origin
- pragma
- proxy-authenticate
- proxy-authorization
- public-key-pins
- range
- referer
- retry-after
- sec-websocket-accept
- sec-websocket-extensions
- sec-websocket-key
- sec-websocket-protocol
- sec-websocket-version
- set-cookie
- strict-transport-security
- tk
- trailer
- transfer-encoding
- upgrade
- user-agent
- vary
- via
- warning
- www-authenticate
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.
- accept
- accept-charset
- accept-encoding
- accept-language
- accept-ranges
- access-control-allow-credentials
- access-control-allow-headers
- access-control-allow-methods
- access-control-allow-origin
- access-control-expose-headers
- access-control-max-age
- access-control-request-headers
- access-control-request-method
- age
- allow
- authorization
- cache-control
- cdn-cache-control
- connection
- content-disposition
- content-encoding
- content-language
- content-length
- content-location
- content-range
- content-security-policy
- content-security-policy-report-only
- cookie
- date
- dav
- dnt
- etag
- expect
- expires
- forwarded
- from
- host
- if-match
- if-modified-since
- if-none-match
- if-range
- if-unmodified-since
- last-modified
- link
- location
- max-forwards
- origin
- prgama
- proxy-authenticate
- proxy-authorization
- public-key-pins
- public-key-pins-report-only
- range
- referer
- referrer-policy
- refresh
- retry-after
- sec-websocket-accept
- sec-websocket-extensions
- sec-websocket-key
- sec-websocket-protocol
- sec-websocket-version
- server
- set-cookie
- strict-transport-security
- te
- trailer
- transfer-encoding
- upgrade
- upgrade-insecure-requests
- user-agent
- vary
- via
- warning
- www-authenticate
- x-content-type-options
- x-dns-prefetch-control
- x-frame-options
- x-xss-protection
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.
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 when res.setHeader(name, value)
is called.
Performs the low-level validations on the provided value
that are done when res.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 Http2Session
instances.
Returns a net.Server
instance that creates and manages Http2Session
instances.
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.
- accept
- accept-charset
- accept-encoding
- accept-language
- accept-ranges
- access-control-allow-credentials
- access-control-allow-headers
- access-control-allow-methods
- access-control-allow-origin
- access-control-expose-headers
- access-control-max-age
- access-control-request-headers
- access-control-request-method
- age
- allow
- authorization
- cache-control
- cdn-cache-control
- connection
- content-disposition
- content-encoding
- content-language
- content-length
- content-location
- content-range
- content-security-policy
- content-security-policy-report-only
- cookie
- date
- dav
- dnt
- etag
- expect
- expires
- forwarded
- from
- host
- if-match
- if-modified-since
- if-none-match
- if-range
- if-unmodified-since
- last-modified
- link
- location
- max-forwards
- origin
- prgama
- proxy-authenticate
- proxy-authorization
- public-key-pins
- public-key-pins-report-only
- range
- referer
- referrer-policy
- refresh
- retry-after
- sec-websocket-accept
- sec-websocket-extensions
- sec-websocket-key
- sec-websocket-protocol
- sec-websocket-version
- server
- set-cookie
- strict-transport-security
- te
- trailer
- transfer-encoding
- upgrade
- upgrade-insecure-requests
- user-agent
- vary
- via
- warning
- www-authenticate
- x-content-type-options
- x-dns-prefetch-control
- x-frame-options
- x-xss-protection
Create an HTTP/2 server session from an existing socket.
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.
Or
Like http.get()
but for HTTPS.
Makes a request to a secure web server.
Deactivate the inspector. Blocks until there are no active connections.
An object to send messages to the remote inspector console.
Breakpoint identifier.
JavaScript call frame. Array of call frames form the call stack.
Call frame identifier.
Heap snapshot object id.
Sampling Heap Profile node. Holds callsite information, allocation statistics and child nodes.
Request / response headers as keys / values of JSON object.
This feature is only available with the --experimental-network-inspection
flag enabled.
This feature is only available with the --experimental-network-inspection
flag enabled.
Monotonically increasing time in seconds since an arbitrary point in the past.
Unique request identifier.
This feature is only available with the --experimental-network-inspection
flag enabled.
Resource type as it was perceived by the rendering engine.
This feature is only available with the --experimental-network-inspection
flag enabled.
UTC time in seconds, counted from January 1, 1970.
Unique identifier of attached debugging session.
Activate inspector on host and port. Equivalent to node --inspect=[[host:]port]
, but can be done programmatically after node has
started.
Specifies a number of samples attributed to a certain source position.
Profile node. Holds callsite information, execution statistics and child nodes.
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.
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.
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.
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 sent Runtime.runIfWaitingForDebugger
command.
inspector/promises
The node:inspector/promises
module provides an API for interacting with the V8
inspector.
Deactivate the inspector. Blocks until there are no active connections.
An object to send messages to the remote inspector console.
Breakpoint identifier.
JavaScript call frame. Array of call frames form the call stack.
Call frame identifier.
Heap snapshot object id.
Sampling Heap Profile node. Holds callsite information, allocation statistics and child nodes.
Request / response headers as keys / values of JSON object.
This feature is only available with the --experimental-network-inspection
flag enabled.
This feature is only available with the --experimental-network-inspection
flag enabled.
Monotonically increasing time in seconds since an arbitrary point in the past.
Unique request identifier.
This feature is only available with the --experimental-network-inspection
flag enabled.
Resource type as it was perceived by the rendering engine.
This feature is only available with the --experimental-network-inspection
flag enabled.
UTC time in seconds, counted from January 1, 1970.
Unique identifier of attached debugging session.
Activate inspector on host and port. Equivalent to node --inspect=[[host:]port]
, but can be done programmatically after node has
started.
Specifies a number of samples attributed to a certain source position.
Profile node. Holds callsite information, execution statistics and child nodes.
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.
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.
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.
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 sent Runtime.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
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
or the value specified via the command line option --network-family-autoselection-attempt-timeout
.
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)
.
- addListener
- address
- autoSelectFamilyAttemptedAddresses
- bufferSize
- bytesRead
- bytesWritten
- connect
- connecting
- destroySoon
- destroyed
- emit
- end
- localAddress
- localFamily
- localPort
- on
- once
- pause
- pending
- prependListener
- prependOnceListener
- readyState
- ref
- remoteAddress
- remoteFamily
- remotePort
- resetAndDestroy
- resume
- setEncoding
- setKeepAlive
- setNoDelay
- setTimeout
- timeout
- unref
- write
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.
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.
The operating system-specific end-of-line marker.
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
. If pid
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
and gid
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:
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.
Provides detailed network timing data regarding the loading of an application's resources.
- abort
- addListener
- allowedNodeEnvironmentFlags
- arch
- argv
- argv0
- availableMemory
- channel
- chdir
- config
- connected
- constrainedMemory
- cpuUsage
- cwd
- debugPort
- disconnect
- dlopen
- emit
- emitWarning
- env
- execArgv
- execPath
- exit
- exitCode
- features
- finalization
- getActiveResourcesInfo
- getBuiltinModule
- getegid
- geteuid
- getgid
- getgroups
- getuid
- hasUncaughtExceptionCaptureCallback
- hrtime
- kill
- listeners
- loadEnvFile
- mainModule
- memoryUsage
- nextTick
- on
- once
- permission
- pid
- platform
- ppid
- prependListener
- prependOnceListener
- release
- report
- resourceUsage
- send
- setSourceMapsEnabled
- setUncaughtExceptionCaptureCallback
- setegid
- seteuid
- setgid
- setgroups
- setuid
- sourceMapsEnabled
- stderr
- stdin
- stdout
- throwDeprecation
- title
- traceDeprecation
- umask
- uptime
- version
- versions
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 given str
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.clearScreenDown()
method clears the given TTY stream from
the current position of the cursor down.
The readline.createInterface()
method creates a new readline.Interface
instance.
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 the readline.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.Interface
instance.
Instances of the readlinePromises.Interface
class are constructed using the readlinePromises.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.Interface
instance.
Instances of the readlinePromises.Interface
class are constructed using the readlinePromises.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.
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'
.
This is the default "writer" value, if none is passed in the REPL options, and it can be overridden by custom print functions.
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.
The utility function duplexPair
returns an Array with two items,
each being a Duplex
stream connected to the other side:
A readable and/or writable stream/webstream.
Returns the default highWaterMark used by streams.
Defaults to 65536
(64 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 where stream.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.
The utility function duplexPair
returns an Array with two items,
each being a Duplex
stream connected to the other side:
A readable and/or writable stream/webstream.
Returns the default highWaterMark used by streams.
Defaults to 65536
(64 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 where stream.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.
- _construct
- _destroy
- _read
- addListener
- asIndexedPairs
- closed
- destroy
- destroyed
- drop
- emit
- errored
- every
- filter
- find
- flatMap
- forEach
- from
- isDisturbed
- isPaused
- iterator
- map
- on
- once
- pause
- prependListener
- prependOnceListener
- push
- read
- readable
- readableAborted
- readableDidRead
- readableEncoding
- readableEnded
- readableFlowing
- readableHighWaterMark
- readableLength
- readableObjectMode
- reduce
- removeListener
- resume
- setEncoding
- some
- take
- toArray
- unpipe
- unshift
- wrap
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 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 lcov
reporter outputs test coverage when used with the
--experimental-test-coverage
flag.
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 import 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.
timers/promises
The timers/promises
API provides an alternative set of timer functions
that return Promise
objects. The API is accessible via import timersPromises from '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](././tls/~/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 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 createSecureContext()
for further
information.
The default value of the maxVersion
option of 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 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](././tls/~/createSecureContext)
.
An immutable array of strings representing the root certificates (in PEM format) from the bundled Mozilla CA store as supplied by the current Node.js version.
Accepts encrypted connections using TLS or SSL.
Performs transparent encryption of written data and all required TLS negotiation.
- addListener
- alpnProtocol
- authorizationError
- authorized
- disableRenegotiation
- emit
- enableTrace
- encrypted
- exportKeyingMaterial
- getCertificate
- getCipher
- getEphemeralKeyInfo
- getFinished
- getPeerCertificate
- getPeerFinished
- getPeerX509Certificate
- getProtocol
- getSession
- getSharedSigalgs
- getTLSTicket
- getX509Certificate
- isSessionReused
- on
- once
- prependListener
- prependOnceListener
- renegotiate
- setMaxSendFragment
tty
The node:tty
module provides the tty.ReadStream
and tty.WriteStream
classes. 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 Promise
resolved), and the second argument will be the resolved value.
The util.debuglog()
method is used to create a function that conditionally
writes debug messages to stderr
based on the existence of the NODE_DEBUG
environment variable. If the section
name appears within the value of that
environment variable, then the returned function operates similar to console.error()
. If not, then the returned function is a no-op.
The util.deprecate()
method wraps fn
(which may be a function or class) in
such a way that it is marked as deprecated.
The util.format()
method returns a formatted string using the first argument
as a printf
-like format string which can contain zero or more format
specifiers. Each specifier is replaced with the converted value from the
corresponding argument. Supported specifiers are:
Returns the string name for a numeric error code that comes from a Node.js API.
The mapping between error codes and error names is platform-dependent.
See Common System Errors
for the names of common errors.
Usage of util.inherits()
is discouraged. Please use the ES6 class
and extends
keywords to get language level inheritance support. Also note
that the two styles are semantically incompatible.
The util.inspect()
method returns a string representation of object
that is
intended for debugging. The output of util.inspect
may change at any time
and should not be depended upon programmatically. Additional options
may be
passed that alter the result. util.inspect()
will use the constructor's name and/or @@toStringTag
to make
an identifiable tag for an inspected value.
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
.
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.
Stability: 1.1 - Active development
Given an example .env
file:
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.
Stability: 1.1 - Active development
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.
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, returns false
.
Returns true
if the given object
is a Function
. Otherwise, returns false
.
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 Object
and 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.
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 ArrayBuffer
s that they are referring to.
Uses a DefaultDeserializer
with default options to read a JS value
from a buffer.
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.
This is similar to the queryObjects()
console API
provided by the Chromium DevTools console. It can be used to search for objects that have the matching constructor on its prototype chain
in the heap after a full garbage collection, which can be useful for memory leak regression tests. To avoid surprising results, users should
avoid using this API on constructors whose implementation they don't control, or on constructors that can be invoked by other parties in the
application.
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
.
Returns an object containing commonly used constants for VM operations.
Stability: 1.1 - Active development
Returns true
if the given object
object has been contextified
using createContext.
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.
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.
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.
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 MessagePort
s between different Worker
s.
The worker.setEnvironmentData()
API sets the content of worker.getEnvironmentData()
in the current thread and all new Worker
instances spawned from the current context.
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
.
Computes a 32-bit Cyclic Redundancy Check checksum of data
.
If value
is specified, it is used as the starting value of the checksum, otherwise, 0 is used as the starting value.
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
.