assert
The node:assert
module provides a set of assertion functions for verifyinginvariants.
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 objectsare 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, immediatelycalls the function and awaits the returned promise to complete. It will thencheck 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 defaulterror message. If the message
parameter is an instance of an Error
thenit will be thrown instead of the AssertionError
.
Throws value
if value
is not undefined
or null
. This is useful whentesting the error
argument in callbacks. The stack trace contains all framesfrom 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 asdetermined 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, immediatelycalls the function and awaits the returned promise to complete. It will thencheck 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 asdetermined 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:
The class AsyncResource
is designed to be extended by the embedder's asyncresources. Using this, users can easily trigger the lifetime events of theirown resources.
Registers functions to be called for different lifetime events of each asyncoperation.
The ID returned from executionAsyncId()
is related to execution timing, notcausality (which is covered by triggerAsyncId()
):
Resource objects returned by executionAsyncResource()
are most often internalNode.js handle objects with undocumented APIs. Using any functions or propertieson the object is likely to crash your application and should be avoided.
Promise contexts may not get valid triggerAsyncId
s by default. Seethe section on promise execution tracking.
buffer
Buffer
objects are used to represent a fixed-length sequence of bytes. ManyNode.js APIs support Buffer
s.
Decodes a string of Base64-encoded data into bytes, and encodes those bytesinto a string using Latin-1 (ISO-8859-1).
Decodes a string into bytes using Latin-1 (ISO-8859), and encodes those bytesinto 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 usinga prior call to URL.createObjectURL()
.
Re-encodes the given Buffer
or Uint8Array
instance from one characterencoding 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 notreturn until the child process has fully closed. When a timeout has beenencountered and killSignal
is sent, the method won't return until the processhas completely exited.
The child_process.execSync()
method is generally identical to exec with the exception that the method will not returnuntil the child process has fully closed. When a timeout has been encounteredand killSignal
is sent, the method won't return until the process hascompletely exited. If the child process intercepts and handles the SIGTERM
signal and doesn't exit, the parent process will wait until the child processhas 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. Thereturned ChildProcess
will have an additional communication channelbuilt-in that allows messages to be passed back and forth between the parent andchild. 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
defaultsto an empty array.
The child_process.spawnSync()
method is generally identical to spawn with the exception that the function will not returnuntil the child process has fully closed. When a timeout has been encounteredand killSignal
is sent, the method won't return until the process hascompletely exited. If the process intercepts and handles the SIGTERM
signaland doesn't exit, the parent process will wait until the child process hasexited.
cluster
Clusters of Node.js processes can be used to run multiple instances of Node.jsthat can distribute workloads among their application threads. When process isolationis not needed, use the worker_threads
module instead, which allows running multiple application threads within a single Node.js instance.
A Worker
object contains all public information and method about a worker.In the primary it can be obtained using cluster.workers
. In a workerit can be obtained using cluster.worker
.
console
The node:console
module provides a simple debugging console that is similar tothe JavaScript console mechanism provided by web browsers.
The console
module provides a simple debugging console that is similar to theJavaScript console mechanism provided by web browsers.
crypto
The node:crypto
module provides cryptographic functionality that includes aset of wrappers for OpenSSL's hash, HMAC, cipher, decipher, sign, and verifyfunctions.
SPKAC is a Certificate Signing Request mechanism originally implemented byNetscape and was specified formally as part of HTML5's keygen
element.
Checks the primality of the candidate
.
Checks the primality of the candidate
.
Instances of the Cipher
class are used to encrypt data. The class can beused 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
andinitialization 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 anoptional specific generator
.
An alias for getDiffieHellman
Creates an Elliptic Curve Diffie-Hellman (ECDH
) key exchange object using apredefined curve specified by the curveName
string. Use getCurves to obtain a list of available curve names. On recentOpenSSL releases, openssl ecparam -list_curves
will also display the nameand description of each available elliptic curve.
Creates and returns a Hash
object that can be used to generate hash digestsusing the given algorithm
. Optional options
argument controls streambehavior. For XOF hash functions such as 'shake256'
, the outputLength
optioncan 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 astring 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 astring 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 symmetricencryption 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 availablesigning algorithms. Optional options
argument controls the stream.Writable
behavior.
Instances of the Decipher
class are used to decrypt data. The class can beused in one of two ways:
The DiffieHellman
class is a utility for creating Diffie-Hellman keyexchanges.
Computes the Diffie-Hellman secret based on a privateKey
and a publicKey
.Both keys must have the same asymmetricKeyType
, which must be one of 'dh'
(for Diffie-Hellman), 'ec'
(for ECDH), 'x448'
, or 'x25519'
(for ECDH-ES).
The ECDH
class is a utility for creating Elliptic Curve Diffie-Hellman (ECDH)key exchanges.
Asynchronously generates a new random secret key of the given length
. 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.
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.
Generates a pseudorandom prime of size
bits.
Returns information about a given cipher.
Creates a predefined DiffieHellmanGroup
key exchange object. Thesupported groups are listed in the documentation for DiffieHellmanGroup
.
A convenient alias for webcrypto.getRandomValues. Thisimplementation is not compliant with the Web Crypto spec, to writeweb-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 releasesof 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. Thegiven ikm
, salt
and info
are used with the digest
to derive a key of keylen
bytes.
Node.js uses a KeyObject
class to represent a symmetric or asymmetric key,and each kind of key exposes different functions. The createSecretKey, createPublicKey and createPrivateKey methods are used to create KeyObject
instances. KeyObject
objects are not to be created directly using the new
keyword.
Provides an asynchronous Password-Based Key Derivation Function 2 (PBKDF2)implementation. A selected HMAC digest algorithm specified by digest
isapplied 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
isapplied to derive a key of the requested byte length (keylen
) from the password
, salt
and iterations
.
Decrypts buffer
with privateKey
. buffer
was previously encrypted usingthe corresponding public key, for example using publicEncrypt.
Encrypts buffer
with privateKey
. The returned data can be decrypted usingthe corresponding public key, for example using publicDecrypt.
Decrypts buffer
with key
.buffer
was previously encrypted usingthe corresponding private key, for example using privateEncrypt.
Encrypts the content of buffer
with key
and returns a new Buffer
with encrypted content. The returned data can be decrypted usingthe corresponding private key, for example using privateDecrypt.
Generates cryptographically strong pseudorandom data. The size
argumentis a number indicating the number of bytes to generate.
This function is similar to randomBytes but requires the firstargument to be a Buffer
that will be filled. It alsorequires that a callback is passed in.
Synchronous version of randomFill.
Return a random integer n
such that min <= n < max
. Thisimplementation avoids modulo bias.
Generates a random RFC 4122 version 4 UUID. The UUID is generated using acryptographic pseudorandom number generator.
Provides a synchronous scrypt implementation. Scrypt is a password-basedkey derivation function that is designed to be expensive computationally andmemory-wise in order to make brute-force attacks unrewarding.
Load and set the engine
for some or all OpenSSL functions (selected by flags).
Enables the FIPS compliant crypto provider in a FIPS-enabled Node.js build.Throws an error if FIPS mode is not available.
Calculates and returns the signature for data
using the given private key andalgorithm. If algorithm
is null
or undefined
, then the algorithm isdependent 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-timealgorithm.
Verifies the given signature for data
using the given key and algorithm. If algorithm
is null
or undefined
, then the algorithm is dependent upon thekey 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 toits 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 datagrammessages. When address
and port
are not passed to socket.bind()
themethod 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 addressand port can be retrieved using socket.address().address
and socket.address().port
.
Encapsulates the datagram functionality.
- 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 channelsto report arbitrary message data for diagnostics purposes.
The class Channel
represents an individual named channel within the datapipeline. It is used to track subscribers and to publish messages when thereare subscribers present. It exists as a separate object to avoid channellookups at publish time, enabling very fast publish speeds and allowingfor heavy use while incurring very minimal cost. Channels are created with channel, constructing a channel directlywith new Channel(name)
is not supported.
This is the primary entry-point for anyone wanting to publish to a namedchannel. It produces a channel object which is optimized to reduce overhead atpublish time as much as possible.
Check if there are active subscribers to the named channel. This is helpful ifthe message you want to send might be expensive to prepare.
Register a message handler to subscribe to this channel. This message handlerwill be run synchronously whenever a message is published to the channel. Anyerrors thrown in the message handler will trigger an 'uncaughtException'
.
The class TracingChannel
is a collection of TracingChannel Channels
whichtogether express a single traceable action. It is used to formalize andsimplify 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 asingle TracingChannel
at the top-level of the file rather than creating themdynamically.
Creates a TracingChannel
wrapper for the given TracingChannel Channels
. If a name is given, the corresponding tracingchannels 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 IPaddresses of host names.
Limits returned address types to the types of non-loopback addresses configured on the system. For example, IPv4 addresses areonly returned if the current system has at least one IPv4 address configured.
If dns.V4MAPPED
is specified, return resolved IPv6 addresses aswell 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 portsection if a custom port is used.
Resolves a host name (e.g. 'nodejs.org'
) into the first found A (IPv4) orAAAA (IPv6) record. All option
properties are optional. If options
is aninteger, then it must be 4
or 6
– if options
is 0
or not provided, thenIPv4 and IPv6 addresses are both returned if found.
Resolves the given address
and port
into a host name and service usingthe operating system's underlying getnameinfo
implementation.
The dns.promises
API provides an alternative set of asynchronous DNS methodsthat return Promise
objects rather than using callbacks. The API is accessiblevia 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 portsection if a custom port is used.
Resolves a host name (e.g. 'nodejs.org'
) into the first found A (IPv4) orAAAA (IPv6) record. All option
properties are optional. If options
is aninteger, then it must be 4
or 6
– if options
is not provided, then IPv4and IPv6 addresses are both returned if found.
Resolves the given address
and port
into a host name and service usingthe operating system's underlying getnameinfo
implementation.
Uses the DNS protocol to resolve a host name (e.g. 'nodejs.org'
) into an arrayof the resource records. When successful, the Promise
is resolved with anarray of resource records. The type and structure of individual results varybased 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 IPv4addresses (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 IPv6addresses.
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 ofrecords. Each object has a property type
that indicates the type of thecurrent record. And depending on the type
, additional properties will bepresent 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 availablecertification 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 forthe 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 objectscontaining 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 arrayof 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 serverrecords 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 stringscontaining the reply records.
Uses the DNS protocol to resolve a start of authority record (SOA
record) forthe hostname
. On success, the Promise
is resolved with an object with thefollowing 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 withthe 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 arrayof the text records available for hostname
(e.g.[ ['v=spf1 ip4:0.0.0.0 ', '~all' ] ]
). Each sub-array contains TXT chunks ofone record. Depending on the use case, these could be either joined together ortreated separately.
Performs a reverse DNS query that resolves an IPv4 or IPv6 address to anarray 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 DNSresolution. The servers
argument is an array of RFC 5952 formattedaddresses. If the port is the IANA default DNS port (53) it can be omitted.
Uses the DNS protocol to resolve a host name (e.g. 'nodejs.org'
) into an arrayof the resource records. The callback
function has arguments (err, records)
. When successful, records
will be an array of resourcerecords. The type and structure of individual results varies based on rrtype
:
Uses the DNS protocol to resolve a IPv4 addresses (A
records) for the hostname
. The addresses
argument passed to the callback
functionwill contain an array of IPv4 addresses (e.g.['74.125.79.104', '74.125.79.105', '74.125.79.106']
).
Uses the DNS protocol to resolve IPv6 addresses (AAAA
records) for the hostname
. The addresses
argument passed to the callback
functionwill contain an array of IPv6 addresses.
Uses the DNS protocol to resolve all records (also known as ANY
or *
query).The ret
argument passed to the callback
function will be an array containingvarious types of records. Each object has a property type
that indicates thetype of the current record. And depending on the type
, additional propertieswill be present on the object:
Uses the DNS protocol to resolve CAA
records for the hostname
. The addresses
argument passed to the callback
functionwill contain an array of certification authority authorization recordsavailable for the hostname
(e.g. [{critical: 0, iodef: 'mailto:pki@example.com'}, {critical: 128, issue: 'pki.example.com'}]
).
Uses the DNS protocol to resolve CNAME
records for the hostname
. The addresses
argument passed to the callback
functionwill contain an array of canonical name records available for the hostname
(e.g. ['bar.example.com']
).
Uses the DNS protocol to resolve mail exchange records (MX
records) for the hostname
. The addresses
argument passed to the callback
function willcontain an array of objects containing both a priority
and exchange
property (e.g. [{priority: 10, exchange: 'mx.example.com'}, ...]
).
Uses the DNS protocol to resolve regular expression-based records (NAPTR
records) for the hostname
. The addresses
argument passed to the callback
function will contain an array ofobjects with the following properties:
Uses the DNS protocol to resolve name server records (NS
records) for the hostname
. The addresses
argument passed to the callback
function willcontain an array of name server records available for hostname
(e.g. ['ns1.example.com', 'ns2.example.com']
).
Uses the DNS protocol to resolve pointer records (PTR
records) for the hostname
. The addresses
argument passed to the callback
function willbe an array of strings containing the reply records.
Uses the DNS protocol to resolve a start of authority record (SOA
record) forthe hostname
. The address
argument passed to the callback
function willbe an object with the following properties:
Uses the DNS protocol to resolve service records (SRV
records) for the hostname
. The addresses
argument passed to the callback
function willbe an array of objects with the following properties:
Uses the DNS protocol to resolve text queries (TXT
records) for the hostname
. The records
argument passed to the callback
function is atwo-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 ofone record. Depending on the use case, these could be either joined together ortreated separately.
Performs a reverse DNS query that resolves an IPv4 or IPv6 address to anarray 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 DNSresolution. The servers
argument is an array of RFC 5952 formattedaddresses. 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 supportedon some operating systems (e.g. FreeBSD 10.1).
dns/promises
The dns.promises
API provides an alternative set of asynchronous DNS methodsthat return Promise
objects rather than using callbacks. The API is accessiblevia 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 portsection if a custom port is used.
Resolves a host name (e.g. 'nodejs.org'
) into the first found A (IPv4) orAAAA (IPv6) record. All option
properties are optional. If options
is aninteger, then it must be 4
or 6
– if options
is not provided, then IPv4and IPv6 addresses are both returned if found.
Resolves the given address
and port
into a host name and service usingthe operating system's underlying getnameinfo
implementation.
Uses the DNS protocol to resolve a host name (e.g. 'nodejs.org'
) into an arrayof the resource records. When successful, the Promise
is resolved with anarray of resource records. The type and structure of individual results varybased 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 IPv4addresses (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 IPv6addresses.
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 ofrecords. Each object has a property type
that indicates the type of thecurrent record. And depending on the type
, additional properties will bepresent 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 availablecertification 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 forthe 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 objectscontaining 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 arrayof 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 serverrecords 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 stringscontaining the reply records.
Uses the DNS protocol to resolve a start of authority record (SOA
record) forthe hostname
. On success, the Promise
is resolved with an object with thefollowing 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 withthe 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 arrayof the text records available for hostname
(e.g.[ ['v=spf1 ip4:0.0.0.0 ', '~all' ] ]
). Each sub-array contains TXT chunks ofone record. Depending on the use case, these could be either joined together ortreated separately.
Performs a reverse DNS query that resolves an IPv4 or IPv6 address to anarray 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 DNSresolution. The servers
argument is an array of RFC 5952 formattedaddresses. If the port is the IANA default DNS port (53) it can be omitted.
domain
This module is pending deprecation. Once a replacement API has beenfinalized, this module will be fully deprecated. Most developers shouldnot have cause to use this module. Users who absolutely must havethe functionality that domains provide may rely on it for the time beingbut should expect to have to migrate to a different solutionin the future.
events
Much of the Node.js core API is built around an idiomatic asynchronousevent-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 thatrequire manual async tracking. Specifically, all events emitted by instancesof events.EventEmitterAsyncResource
will run within its async context
.
fs
The node:fs
module enables interacting with the file system in away 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 accessibilitychecks 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
forpossible values of mode
.
Synchronously tests a user's permissions for the file or directory specifiedby path
. The mode
argument is an optional integer that specifies theaccessibility 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
, andfs.constants.X_OK
(e.g.fs.constants.W_OK | fs.constants.R_OK
). Check File access constants
forpossible values of mode
.
Asynchronously append data to a file, creating the file if it does not yetexist. data
can be a string or a Buffer
.
Synchronously append data to a file, creating the file if it does not yetexist. data
can be a string or a Buffer
.
Asynchronously changes the permissions of a file. No arguments other than apossible exception are given to the completion callback.
Asynchronously changes owner and group of a file. No arguments other than apossible exception are given to the completion callback.
Closes the file descriptor. No arguments other than a possible exception aregiven 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 inan 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 flagis 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 italready exists. No arguments other than a possible exception are given to thecallback function. Node.js makes no guarantees about the atomicity of the copyoperation. If an error occurs after the destination file has been opened forwriting, Node.js will attempt to remove the destination.
Synchronously copies src
to dest
. By default, dest
is overwritten if italready exists. Returns undefined
. Node.js makes no guarantees about theatomicity of the copy operation. If an error occurs after the destination filehas 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 streamreturned by this method has a default highWaterMark
of 64 KiB.
options
may also include a start
option to allow writing data at someposition past the beginning of the file, allowed values are in the[0, Number.MAX_SAFE_INTEGER
] range. Modifying a file rather thanreplacing it may require the flags
option to be set to r+
rather than thedefault 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 subdirectorywithin the directory, as returned by reading from an fs.Dir
. Thedirectory 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 exceptionare 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 aregiven to the completion callback.
Sets the owner of the file. Returns undefined
.
Forces all currently queued I/O operations associated with the file to theoperating system's synchronized I/O completion state. Refer to the POSIX fdatasync(2)
documentation for details. No arguments otherthan a possibleexception are given to the completion callback.
Forces all currently queued I/O operations associated with the file to theoperating 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.
Truncates the file descriptor. No arguments other than a possible exception aregiven 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 possibleexception 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 symboliclink, 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 orthe 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 formore 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 returnpromises.
Tests a user's permissions for the file or directory specified by path
.The mode
argument is an optional integer that specifies the accessibilitychecks 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
forpossible values of mode
.
Asynchronously append data to a file, creating the file if it does not yetexist. 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 italready 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 asymbolic link, then the link is not dereferenced: instead, the timestamps ofthe symbolic link itself are changed.
Asynchronously creates a directory.
Creates a unique temporary directory. A unique directory name is generated byappending six random characters to the end of the provided prefix
. Due toplatform inconsistencies, avoid trailing X
characters in prefix
. Someplatforms, notably the BSDs, can return more than six random characters, andreplace 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 isfulfilled 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 affectingthe file or directory to which that link refers. If the path
refers to a filepath 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, anAsyncIterable, or anIterable 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 getstwo 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
susing readv()
.
Asynchronously computes the canonical pathname by resolving .
, ..
, andsymbolic links.
Asynchronous realpath(3)
.
Returns the resolved pathname.
Asynchronously rename file at oldPath
to the pathname providedas newPath
. In the case that newPath
already exists, it willbe overwritten. If there is a directory at newPath
, an error willbe raised instead. No arguments other than a possible exception aregiven 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 thecompletion 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 whichcontains 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 apossible exception are given to the completion callback.
Returns undefined
.
Truncates the file. No arguments other than a possible exception aregiven to the completion callback. A file descriptor can also be passed as thefirst argument. In this case, fs.ftruncate()
is called.
Truncates the file. Returns undefined
. A file descriptor can also bepassed as the first argument. In this case, fs.ftruncateSync()
is called.
Asynchronously removes a file or symbolic link. No arguments other than apossible exception are given to the completion callback.
Synchronous unlink(2)
. Returns undefined
.
Stop watching for changes on filename
. If listener
is specified, only thatparticular 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 adirectory.
Watch for changes on filename
. The callback listener
will be called eachtime the file is accessed.
Watch for changes on filename
. The callback listener
will be called eachtime the file is accessed.
Write buffer
to the file specified by fd
.
When file
is a filename, asynchronously writes data to the file, replacing thefile if it already exists. data
can be a string or a buffer.
Returns undefined
.
Instances of fs.WriteStream
are created and returned using the createWriteStream function.
Write an array of ArrayBufferView
s to the file specified by fd
using writev()
.
For detailed information, see the documentation of the asynchronous version ofthis 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 possibleexception are given to the completion callback.
Changes the permissions on a symbolic link. Returns undefined
.
Changes the permissions on a symbolic link.
fs/promises
The fs/promises
API provides asynchronous file system methods that returnpromises.
Tests a user's permissions for the file or directory specified by path
.The mode
argument is an optional integer that specifies the accessibilitychecks 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
forpossible values of mode
.
Asynchronously append data to a file, creating the file if it does not yetexist. 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 italready 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 asymbolic link, then the link is not dereferenced: instead, the timestamps ofthe symbolic link itself are changed.
Asynchronously creates a directory.
Creates a unique temporary directory. A unique directory name is generated byappending six random characters to the end of the provided prefix
. Due toplatform inconsistencies, avoid trailing X
characters in prefix
. Someplatforms, notably the BSDs, can return more than six random characters, andreplace 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 isfulfilled 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, anAsyncIterable, or anIterable object.
Changes the permissions on a symbolic link.
http
To use the HTTP server and client one must import the node:http
module.
An Agent
is responsible for managing connection persistenceand reuse for HTTP clients. It maintains a queue of pending requestsfor a given host and port, reusing a single socket connection for eachuntil the queue is empty, at which time the socket is either destroyedor put into a pool where it is kept to be used again for requests to thesame host and port. Whether it is destroyed or pooled depends on the keepAlive
option
.
This object is created internally and returned from request. Itrepresents an in-progress request whose header has already been queued. Theheader is still mutable using the setHeader(name, value)
, getHeader(name)
, removeHeader(name)
API. The actual header willbe sent along with the first data chunk or when calling request.end()
.
Returns a new instance of Server.
Since most requests are GET requests without bodies, Node.js provides thisconvenience method. The only difference between this method and request is that it sets the method to GET by default and calls req.end()
automatically. The callback must take care toconsume the responsedata for reasons stated in ClientRequest section.
Global instance of Agent
which is used as the default for all HTTP clientrequests. 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 toaccess responsestatus, 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 fromthe perspective of the participants of an HTTP transaction.
options
in socket.connect()
are also supported.
This object is created internally by an HTTP server, not by the user. It ispassed 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.
Returns an object containing the default settings for an Http2Session
instance. This method returns a new object instance every time it is calledso instances returned may be safely modified for use.
Returns a Buffer
instance containing serialized representation of the givenHTTP/2 settings as specified in the HTTP/2 specification. This is intendedfor use with the HTTP2-Settings
header field.
Returns a HTTP/2 Settings Object
containing the deserialized settings fromthe given Buffer
as generated by http2.getPackedSettings()
.
A Http2ServerRequest
object is created by Server or SecureServer and passed as the first argument to the 'request'
event. It may be used to access a request status,headers, anddata.
This object is created internally by an HTTP server, not by the user. It ispassed 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 withan 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 aseparate module.
Or
Like http.get()
but for HTTPS.
Makes a request to a secure web server.
See http.Server
for more information.
inspector
The node:inspector
module provides an API for interacting with the V8inspector.
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 hasstarted.
Coverage data for a JavaScript function.
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 <code>objectId</code>, primitive <code>value</code>, 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.
Call frames for assertions or error messages.
If <code>debuggerId</code> is set stack trace comes from another debugger and can be resolved there. This allows to track cross-debugger calls. See <code>Runtime.StackTrace</code> and <code>Debugger.paused</code> 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 inspectorback-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 V8inspector.
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 hasstarted.
Coverage data for a JavaScript function.
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 <code>objectId</code>, primitive <code>value</code>, 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.
Call frames for assertions or error messages.
If <code>debuggerId</code> is set stack trace comes from another debugger and can be resolved there. This allows to track cross-debugger calls. See <code>Runtime.StackTrace</code> and <code>Debugger.paused</code> 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 inspectorback-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 mapshould be fetched.
The initialize
hook provides a way to define a custom function that runs in the hooks threadwhen 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 forbuiltin ES Modules
to match the properties of the CommonJS
exports. Itdoes not add or remove exported names from the ES Modules
.
net
The node:net
module provides an asynchronous network API for creating stream-basedTCP or IPC
servers (createServer) and clients(createConnection).
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 IPv4address in dot-decimal notation with no leading zeroes. Otherwise, returns0
.
Returns true
if input
is an IPv4 address in dot-decimal notation with noleading zeroes. Otherwise, returns false
.
Returns true
if input
is an IPv6 address. Otherwise, returns false
.
This class is used to create a TCP or IPC
server.
Sets the default value of the autoSelectFamily
option of socket.connect(options)
.
Sets the default value of the autoSelectFamilyAttemptTimeout
option of socket.connect(options)
.
This class is an abstraction of a TCP socket or a streaming IPC
endpoint(uses named pipes on Windows, and Unix domain sockets otherwise). It is alsoan EventEmitter
.
- 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 andproperties. It can be accessed using:
Returns the operating system CPU architecture for which the Node.js binary wascompiled. 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.jsbinary 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
isnot 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 anetwork address.
Returns a string identifying the operating system platform for whichthe 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 astring.
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 includesthe 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 directorypaths. 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 forNode.js-specific performance measurements.
Returns a RecordableHistogram
.
This property is an extension by Node.js. It is not available in Web browsers.
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 uponas 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. Userscurrently depending on the punycode
module should switch to using theuserland-provided Punycode.js module instead. For punycode-based URLencoding, see url.domainToASCII
or, more generally, the WHATWG URL API
.
querystring
The node:querystring
module provides utilities for parsing and formatting URLquery 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 URLquery strings.
The querystring.parse()
method parses a URL query string (str
) into acollection of key and value pairs.
The querystring.stringify()
method produces a URL query string from agiven obj
by iterating through the object's "own properties".
The node:querystring
module provides utilities for parsing and formatting URLquery strings. It can be accessed using:
The querystring.unescape()
method performs decoding of URL percent-encodedcharacters 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 fromthe 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 asingle 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 currentposition 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 asingle 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 asingle input
Readable
stream and a single output
Writable
stream.The output
stream is used to print prompts for user input that arrives on,and is read from, the input
stream.
repl
The node:repl
module provides a Read-Eval-Print-Loop (REPL) implementationthat is available both as a standalone program or includible in otherapplications. It can be accessed using:
Indicates a recoverable error that a REPLServer
can use to support multi-line input.
A flag passed in the REPL options. Evaluates expressions in sloppy mode.
A flag passed in the REPL options. Evaluates expressions in strict mode.This is equivalent to prefacing every repl statement with 'use strict'
.
Instances of repl.REPLServer
are created using the start methodor directly using the JavaScript new
keyword.
The repl.start()
method creates and starts a REPLServer instance.
This is the default "writer" value, if none is passed in the REPL options,and it can be overridden by custom print functions.
sea
This feature allows the distribution of a Node.js application conveniently to asystem that does not have Node.js installed.
This method can be used to retrieve the assets configured to be bundled into thesingle-executable application at build time.An error is thrown when no matching asset can be found.
Similar to sea.getAsset()
, but returns the result in a Blob
.An error is thrown when no matching asset can be found.
This method can be used to retrieve the assets configured to be bundled into thesingle-executable application at build time.An error is thrown when no matching asset can be found.
sqlite
The node:sqlite
module facilitates working with SQLite databases.To access it:
This class represents a single connection to a SQLite database. All APIsexposed by this class execute synchronously.
This class represents a single prepared statement. This class cannot beinstantiated via its constructor. Instead, instances are created via thedatabase.prepare()
method. All APIs exposed by this class executesynchronously.
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 isprimarily 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 andproperly 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 wayrelated to the input. Like all Duplex
streams, Transform
streamsimplement 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 isprimarily 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 andproperly 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 wayrelated to the input. Like all Duplex
streams, Transform
streamsimplement 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 queuingstrategy that can be used when constructing streams.
This Streams API interface provides a built-in byte length queuingstrategy 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 aWritableStream's state. When constructing a WritableStream, theunderlying sink is given a corresponding WritableStreamDefaultControllerinstance to manipulate.
This Streams API interface is the object returned byWritableStream.getWriter() and once created locks the < writer to theWritableStream ensuring that no other streams can write to the underlyingsink.
string_decoder
The node:string_decoder
module provides an API for decoding Buffer
objectsinto strings in a manner that preserves encoded multi-byte UTF-8 and UTF-16characters. It can be accessed using:
The node:string_decoder
module provides an API for decoding Buffer
objectsinto strings in a manner that preserves encoded multi-byte UTF-8 and UTF-16characters. 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 tobe called at some future period of time. Because the timer functions areglobals, 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()
. Itcan be passed to clearImmediate()
in order to cancel the scheduledactions.
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 functionsthat 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 explicitlyor 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
optionto true
, other APIs that create secure contexts leave it unset.
Creates a new Server. The secureConnectionListener
, if provided, isautomatically 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
, unlesschanged 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 furtherinformation.
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'
, unlesschanged 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 optionsare 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'
, unlesschanged 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 optionsare provided, the lowest minimum is used.
Returns an array with the names of the supported TLS ciphers. The names arelower-case for historical reasons, but must be uppercased to be used inthe 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 TLSnegotiation.
- 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
Creates a new secure pair object with two streams, one of which reads and writesthe encrypted data and the other of which reads and writes the cleartext data.Generally, the encrypted stream is piped to/from an incoming encrypted datastream and the cleartext one is used as a replacement for the initial encryptedstream.
trace_events
The node:trace_events
module provides a mechanism to centralize tracing informationgenerated by V8, Node.js core, and userspace code.
Creates and returns a Tracing
object for the given set of categories
.
Returns a comma-separated list of all currently-enabled trace eventcategories. The current set of enabled trace event categories is determinedby the union of all currently-enabled Tracing
objects and any categoriesenabled using the --trace-event-categories
flag.
The Tracing
object is used to enable or disable tracing for sets ofcategories. Instances are created using thetrace_events.createTracing()
method.
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 moduledirectly. However, it can be accessed using:
-1 - to the left from cursor0 - the entire line1 - to the right from cursor
The tty.isatty()
method returns true
if the given fd
is associated witha TTY and false
if it is not, including whenever fd
is not a non-negativeinteger.
Represents the readable side of a TTY. In normal circumstances process.stdin
will be the only tty.ReadStream
instance in a Node.jsprocess 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 thereshould be no reason to create additional instances.
url
The node:url
module provides utilities for URL resolution and parsing. It canbe accessed using:
Returns the Punycode ASCII serialization of the domain
. If domain
is aninvalid domain, the empty string is returned.
Returns the Unicode serialization of the domain
. If domain
is an invaliddomain, the empty string is returned.
This function ensures the correct decodings of percent-encoded characters aswell 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 URLcontrol characters are correctly encoded when converting into a File URL.
The url.resolve()
method resolves a target URL relative to a base URL in amanner similar to that of a web browser resolving an anchor tag.
Browser-compatible URL
class, implemented by following the WHATWG URLStandard. 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 thefour following constructors.The URLSearchParams
class is also available on the global object.
This utility function converts a URL object into an ordinary options object asexpected by the http.request()
and https.request()
APIs.
util
The node:util
module supports the needs of Node.js internal APIs. Many of theutilities are useful for application and module developers as well. To accessit:
Listens to abort event on the provided signal
andreturns a promise that is fulfilled when the signal
isaborted. If the passed resource
is garbage collected before the signal
isaborted, the returned promise shall remain pending indefinitely.
Takes an async
function (or a function that returns a Promise
) and returns afunction following the error-first callback style, i.e. takingan (err, value) => ...
callback as the last argument. In the callback, thefirst 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 conditionallywrites debug messages to stderr
based on the existence of the NODE_DEBUG
environment variable. If the section
name appears within the value of thatenvironment 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) insuch a way that it is marked as deprecated.
The util.format()
method returns a formatted string using the first argumentas a printf
-like format string which can contain zero or more formatspecifiers. Each specifier is replaced with the converted value from thecorresponding argument. Supported specifiers are:
Returns a Map of all system error codes available from the Node.js API.The mapping between error codes and error names is platform-dependent.See Common System Errors
for the names of common errors.
Returns the string name for a numeric error code that comes from a Node.js API.The mapping between error codes and error names is platform-dependent.See Common System Errors
for the names of common errors.
Usage of util.inherits()
is discouraged. Please use the ES6 class
and extends
keywords to get language level inheritance support. Also notethat the two styles are semantically incompatible.
The util.inspect()
method returns a string representation of object
that isintended for debugging. The output of util.inspect
may change at any timeand should not be depended upon programmatically. Additional options
may bepassed that alter the result. util.inspect()
will use the constructor's name and/or @@toStringTag
to makean 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 interactingwith process.argv
directly. Takes a specification for the expected argumentsand returns a structured object with the parsed options and positionals.
Stability: 1.1 - Active developmentGiven an example .env
file:
Takes a function following the common error-first callback style, i.e. takingan (err, value) => ...
callback as the last argument, and returns a versionthat 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. Allinstances of TextEncoder
only support UTF-8 encoding.
Returns the string
after replacing any surrogate code points(or equivalently, any unpaired surrogate code units) with theUnicode "replacement character" U+FFFD.
Creates and returns an AbortController
instance whose AbortSignal
is markedas transferable and can be used with structuredClone()
or postMessage()
.
Marks the given AbortSignal
as transferable so that it can be used withstructuredClone()
and postMessage()
.
Returns true
if the value is a built-in ArrayBuffer
orSharedArrayBuffer
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 isdesirable 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 typedarray objects or DataView
. Equivalent toArrayBuffer.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 ifa 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. createdby new Boolean()
.
Returns true
if the value is any boxed primitive object, e.g. createdby 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 ifa transpilation tool was used.
Returns true
if the value is a generator object as returned from abuilt-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 ifa 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. createdby 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. createdby new String()
.
Returns true
if the value is a symbol object, createdby 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 includedtimestamp.
Returns true
if the value is a built-in ArrayBuffer
orSharedArrayBuffer
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 isdesirable 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 typedarray objects or DataView
. Equivalent toArrayBuffer.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 ifa 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. createdby new Boolean()
.
Returns true
if the value is any boxed primitive object, e.g. createdby 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 ifa transpilation tool was used.
Returns true
if the value is a generator object as returned from abuilt-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 ifa 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. createdby 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. createdby new String()
.
Returns true
if the value is a symbol object, createdby calling Object()
on a Symbol
primitive.
Returns true
if the value is a built-in TypedArray
instance.
Returns true
if the value is a built-in Uint16Array
instance.
Returns true
if the value is a built-in Uint32Array
instance.
Returns true
if the value is a built-in Uint8Array
instance.
Returns true
if the value is a built-in Uint8ClampedArray
instance.
v8
The node:v8
module exposes APIs that are specific to the version of V8 built into the Node.js binary. It can be accessed using:
Called immediately after a promise continuation executes. This may be after a then()
, catch()
, or finally()
handler or before an await after another await.
Called before a promise continuation executes. This can be in the form of then()
, catch()
, or finally()
handlers or an await resuming.
Returns an integer representing a version tag derived from the V8 version,command-line flags, and detected CPU features. This is useful for determiningwhether a vm.Script
cachedData
buffer is compatible with this instanceof 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 onlystores the part of their underlying ArrayBuffer
s that they are referring to.
Uses a DefaultDeserializer
with default options to read a JS valuefrom a buffer.
Get statistics about code and its metadata in the heap, seeV8 GetHeapCodeAndMetadataStatistics
API. Returns an object with thefollowing properties:
Generates a snapshot of the current V8 heap and returns a ReadableStream that may be used to read the JSON serialized representation.This JSON stream format is intended to be used with tools such asChrome DevTools. The JSON schema is undocumented and specific to theV8 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 upthe V8 heap. Neither the ordering of heap spaces, nor the availability of aheap space can be guaranteed as the statistics are provided via theV8 GetHeapSpaceStatistics
function and may change from one V8 version to thenext.
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 oraround 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 willhappen 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 APIprovided by the Chromium DevTools console. It can be used to search for objects that have the matching constructor on its prototype chainin the heap after a full garbage collection, which can be useful for memory leak regression tests. To avoid surprising results, users shouldavoid using this API on constructors whose implementation they don't control, or on constructors that can be invoked by other parties in theapplication.
Uses a DefaultSerializer
to serialize value
into a buffer.
The v8.setFlagsFromString()
method can be used to programmatically setV8 command-line flags. This method should be used with care. Changing settingsafter the VM has started may result in unpredictable behavior, includingcrashes 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() orPromise.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 collectionstarted by NODE_V8_COVERAGE
, so that V8 can release the execution countrecords 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 multipletimes during the lifetime of the process. Each time the execution counter willbe reset and a new coverage report will be written to the directory specifiedby NODE_V8_COVERAGE
.
Generates a snapshot of the current V8 heap and writes it to a JSONfile. This file is intended to be used with tools such as ChromeDevTools. The JSON schema is undocumented and specific to the V8engine, and may change from one version of V8 to the next.
vm
The node:vm
module enables compiling and running code within V8 VirtualMachine contexts.
Compiles the given code into the provided context (if no context issupplied, the current context is used), and returns it wrapped inside afunction with the given params
.
Returns an object containing commonly used constants for VM operations.
Stability: 1.1 - Active development
If given a contextObject
, the vm.createContext()
method willprepare that objectand return a reference to it so that it can be used in [runInContext](././vm/~/runInContext)
orscript.runInContext()
. Inside suchscripts, the contextObject
will be the global object, retaining all of itsexisting properties but also having the built-in objects and functions anystandard global object has. Outside of scripts run by the vm module, globalvariables will remain unchanged.
Returns true
if the given object
object has been contextified
using createContext.
Measure the memory known to V8 and used by all contexts known to thecurrent V8 isolate, or the main context.
This feature is only available with the --experimental-vm-modules
commandflag enabled.
The vm.runInContext()
method compiles code
, runs it within the context ofthe contextifiedObject
, then returns the result. Running code does not haveaccess to the local scope. The contextifiedObject
object must have beenpreviously contextified
using the createContext method.
The vm.runInNewContext()
first contextifies the given contextObject
(orcreates a new contextObject
if passed as undefined
), compiles the code
,runs it within the created context, then returns the result. Running codedoes not have access to the local scope.
vm.runInThisContext()
compiles code
, runs it within the context of thecurrent global
and returns the result. Running code does not have access tolocal scope, but does have access to the current global
object.
Instances of the vm.Script
class contain precompiled scripts that can beexecuted in specific contexts.
This feature is only available with the --experimental-vm-modules
commandflag enabled.
This feature is only available with the --experimental-vm-modules
commandflag enabled.
wasi
The node:wasi
module does not currently provide thecomprehensive file system security properties provided by some WASI runtimes.Full support for secure file system sandboxing may or may not be implemented infuture. In the mean time, do not rely on it to run untrusted code.
The WASI
class provides the WASI system call API and additional conveniencemethods for working with WASI-based applications. Each WASI
instancerepresents a distinct environment.
worker_threads
The node:worker_threads
module enables the use of threads that executeJavaScript in parallel. To access it:
Instances of BroadcastChannel
allow asynchronous one-to-many communicationwith all other BroadcastChannel
instances bound to the same channel name.
Within a worker thread, worker.getEnvironmentData()
returns a cloneof data passed to the spawning thread's worker.setEnvironmentData()
.Every new Worker
receives its own copy of the environment dataautomatically.
Mark an object as not transferable. If object
occurs in the transfer list ofa port.postMessage()
call, it is ignored.
Instances of the worker.MessageChannel
class represent an asynchronous,two-way communications channel.The MessageChannel
has no methods of its own. new MessageChannel()
yields an object with port1
and port2
properties, which refer to linked MessagePort
instances.
Instances of the worker.MessagePort
class represent one end of anasynchronous, two-way communications channel. It can be used to transferstructured data, memory regions and other MessagePort
s between different Worker
s.
Transfer a MessagePort
to a different vm
Context. The original port
object is rendered unusable, and the returned MessagePort
instancetakes its place.
Receive a single message from a given MessagePort
. If no message is available,undefined
is returned, otherwise an object with a single message
propertythat contains the message payload, corresponding to the oldest message in the MessagePort
's queue.
The worker.setEnvironmentData()
API sets the content of worker.getEnvironmentData()
in the current thread and all new Worker
instances spawned from the current context.
The Worker
class represents an independent JavaScript execution thread.Most Node.js APIs are available inside of it.
zlib
The node:zlib
module provides compression functionality implemented usingGzip, 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
.