- Assertion testing
- Asynchronous context tracking
- Async hooks
- Buffer
- C++ addons
- C/C++ addons with Node-API
- C++ embedder API
- Child processes
- Cluster
- Command-line options
- Console
- Corepack
- Crypto
- Debugger
- Deprecated APIs
- Diagnostics Channel
- DNS
- Domain
- Errors
- Events
- File system
- Globals
- HTTP
- HTTP/2
- HTTPS
- Inspector
- Internationalization
- Modules: CommonJS modules
- Modules: ECMAScript modules
- Modules:
moduleAPI - Modules: Packages
- Net
- OS
- Path
- Performance hooks
- Policies
- Process
- Punycode
- Query strings
- Readline
- REPL
- Report
- Stream
- String decoder
- Timers
- TLS/SSL
- Trace events
- TTY
- UDP/datagram
- URL
- Utilities
- V8
- VM
- WASI
- Web Crypto API
- Web Streams API
- Worker threads
- Zlib
Node.js v17.9.1 documentation
- Node.js v17.9.1
- ► Other versions
- ► Options
Table of contents
- About this documentation
- Usage and example
- Assert
- Strict assertion mode
- Legacy assertion mode
- Class: assert.AssertionError
- Class:
assert.CallTracker assert(value[, message])assert.deepEqual(actual, expected[, message])assert.deepStrictEqual(actual, expected[, message])assert.doesNotMatch(string, regexp[, message])assert.doesNotReject(asyncFn[, error][, message])assert.doesNotThrow(fn[, error][, message])assert.equal(actual, expected[, message])assert.fail([message])assert.fail(actual, expected[, message[, operator[, stackStartFn]]])assert.ifError(value)assert.match(string, regexp[, message])assert.notDeepEqual(actual, expected[, message])assert.notDeepStrictEqual(actual, expected[, message])assert.notEqual(actual, expected[, message])assert.notStrictEqual(actual, expected[, message])assert.ok(value[, message])assert.rejects(asyncFn[, error][, message])assert.strictEqual(actual, expected[, message])assert.throws(fn[, error][, message])
- Asynchronous context tracking
- Introduction
- Class:
AsyncLocalStorage - Class:
AsyncResourcenew AsyncResource(type[, options])- Static method:
AsyncResource.bind(fn[, type, [thisArg]]) asyncResource.bind(fn[, thisArg])asyncResource.runInAsyncScope(fn[, thisArg, ...args])asyncResource.emitDestroy()asyncResource.asyncId()asyncResource.triggerAsyncId()- Using
AsyncResourcefor aWorkerthread pool - Integrating
AsyncResourcewithEventEmitter
- Async hooks
- Terminology
- Overview
async_hooks.createHook(callbacks)- Class:
AsyncHook - Promise execution tracking
- JavaScript embedder API
- Class:
AsyncLocalStorage
- Buffer
- Buffers and character encodings
- Buffers and TypedArrays
- Buffers and iteration
- Class:
Blob - Class:
Buffer- Static method:
Buffer.alloc(size[, fill[, encoding]]) - Static method:
Buffer.allocUnsafe(size) - Static method:
Buffer.allocUnsafeSlow(size) - Static method:
Buffer.byteLength(string[, encoding]) - Static method:
Buffer.compare(buf1, buf2) - Static method:
Buffer.concat(list[, totalLength]) - Static method:
Buffer.from(array) - Static method:
Buffer.from(arrayBuffer[, byteOffset[, length]]) - Static method:
Buffer.from(buffer) - Static method:
Buffer.from(object[, offsetOrEncoding[, length]]) - Static method:
Buffer.from(string[, encoding]) - Static method:
Buffer.isBuffer(obj) - Static method:
Buffer.isEncoding(encoding) - Class property:
Buffer.poolSize buf[index]buf.bufferbuf.byteOffsetbuf.compare(target[, targetStart[, targetEnd[, sourceStart[, sourceEnd]]]])buf.copy(target[, targetStart[, sourceStart[, sourceEnd]]])buf.entries()buf.equals(otherBuffer)buf.fill(value[, offset[, end]][, encoding])buf.includes(value[, byteOffset][, encoding])buf.indexOf(value[, byteOffset][, encoding])buf.keys()buf.lastIndexOf(value[, byteOffset][, encoding])buf.lengthbuf.parentbuf.readBigInt64BE([offset])buf.readBigInt64LE([offset])buf.readBigUInt64BE([offset])buf.readBigUInt64LE([offset])buf.readDoubleBE([offset])buf.readDoubleLE([offset])buf.readFloatBE([offset])buf.readFloatLE([offset])buf.readInt8([offset])buf.readInt16BE([offset])buf.readInt16LE([offset])buf.readInt32BE([offset])buf.readInt32LE([offset])buf.readIntBE(offset, byteLength)buf.readIntLE(offset, byteLength)buf.readUInt8([offset])buf.readUInt16BE([offset])buf.readUInt16LE([offset])buf.readUInt32BE([offset])buf.readUInt32LE([offset])buf.readUIntBE(offset, byteLength)buf.readUIntLE(offset, byteLength)buf.subarray([start[, end]])buf.slice([start[, end]])buf.swap16()buf.swap32()buf.swap64()buf.toJSON()buf.toString([encoding[, start[, end]]])buf.values()buf.write(string[, offset[, length]][, encoding])buf.writeBigInt64BE(value[, offset])buf.writeBigInt64LE(value[, offset])buf.writeBigUInt64BE(value[, offset])buf.writeBigUInt64LE(value[, offset])buf.writeDoubleBE(value[, offset])buf.writeDoubleLE(value[, offset])buf.writeFloatBE(value[, offset])buf.writeFloatLE(value[, offset])buf.writeInt8(value[, offset])buf.writeInt16BE(value[, offset])buf.writeInt16LE(value[, offset])buf.writeInt32BE(value[, offset])buf.writeInt32LE(value[, offset])buf.writeIntBE(value, offset, byteLength)buf.writeIntLE(value, offset, byteLength)buf.writeUInt8(value[, offset])buf.writeUInt16BE(value[, offset])buf.writeUInt16LE(value[, offset])buf.writeUInt32BE(value[, offset])buf.writeUInt32LE(value[, offset])buf.writeUIntBE(value, offset, byteLength)buf.writeUIntLE(value, offset, byteLength)new Buffer(array)new Buffer(arrayBuffer[, byteOffset[, length]])new Buffer(buffer)new Buffer(size)new Buffer(string[, encoding])
- Static method:
buffermodule APIsBuffer.from(),Buffer.alloc(), andBuffer.allocUnsafe()
- C++ addons
- Node-API
- Implications of ABI stability
- Building
- Usage
- Node-API version matrix
- Environment life cycle APIs
- Basic Node-API data types
- Error handling
- Object lifetime management
- Module registration
- Working with JavaScript values
- Enum types
- Object creation functions
napi_create_arraynapi_create_array_with_lengthnapi_create_arraybuffernapi_create_buffernapi_create_buffer_copynapi_create_datenapi_create_externalnapi_create_external_arraybuffernapi_create_external_buffernapi_create_objectnapi_create_symbolnode_api_symbol_fornapi_create_typedarraynapi_create_dataview
- Functions to convert from C types to Node-API
- Functions to convert from Node-API to C types
napi_get_array_lengthnapi_get_arraybuffer_infonapi_get_buffer_infonapi_get_prototypenapi_get_typedarray_infonapi_get_dataview_infonapi_get_date_valuenapi_get_value_boolnapi_get_value_doublenapi_get_value_bigint_int64napi_get_value_bigint_uint64napi_get_value_bigint_wordsnapi_get_value_externalnapi_get_value_int32napi_get_value_int64napi_get_value_string_latin1napi_get_value_string_utf8napi_get_value_string_utf16napi_get_value_uint32
- Functions to get global instances
- Working with JavaScript values and abstract operations
- Working with JavaScript properties
- Structures
- Functions
napi_get_property_namesnapi_get_all_property_namesnapi_set_propertynapi_get_propertynapi_has_propertynapi_delete_propertynapi_has_own_propertynapi_set_named_propertynapi_get_named_propertynapi_has_named_propertynapi_set_elementnapi_get_elementnapi_has_elementnapi_delete_elementnapi_define_propertiesnapi_object_freezenapi_object_seal
- Working with JavaScript functions
- Object wrap
- Simple asynchronous operations
- Custom asynchronous operations
- Version management
- Memory management
- Promises
- Script execution
- libuv event loop
- Asynchronous thread-safe function calls
- Calling a thread-safe function
- Reference counting of thread-safe functions
- Deciding whether to keep the process running
napi_create_threadsafe_functionnapi_get_threadsafe_function_contextnapi_call_threadsafe_functionnapi_acquire_threadsafe_functionnapi_release_threadsafe_functionnapi_ref_threadsafe_functionnapi_unref_threadsafe_function
- Miscellaneous utilities
- C++ embedder API
- Child process
- Asynchronous process creation
- Synchronous process creation
- Class:
ChildProcess- Event:
'close' - Event:
'disconnect' - Event:
'error' - Event:
'exit' - Event:
'message' - Event:
'spawn' subprocess.channelsubprocess.connectedsubprocess.disconnect()subprocess.exitCodesubprocess.kill([signal])subprocess.killedsubprocess.pidsubprocess.ref()subprocess.send(message[, sendHandle[, options]][, callback])subprocess.signalCodesubprocess.spawnargssubprocess.spawnfilesubprocess.stderrsubprocess.stdinsubprocess.stdiosubprocess.stdoutsubprocess.unref()
- Event:
maxBufferand Unicode- Shell requirements
- Default Windows shell
- Advanced serialization
- Cluster
- How it works
- Class:
Worker - Event:
'disconnect' - Event:
'exit' - Event:
'fork' - Event:
'listening' - Event:
'message' - Event:
'online' - Event:
'setup' cluster.disconnect([callback])cluster.fork([env])cluster.isMastercluster.isPrimarycluster.isWorkercluster.schedulingPolicycluster.settingscluster.setupMaster([settings])cluster.setupPrimary([settings])cluster.workercluster.workers
- Command-line API
- Synopsis
- Program entry point
- Options
-----abort-on-uncaught-exception--completion-bash-C=condition,--conditions=condition--cpu-prof--cpu-prof-dir--cpu-prof-interval--cpu-prof-name--diagnostic-dir=directory--disable-proto=mode--disallow-code-generation-from-strings--dns-result-order=order--enable-fips--enable-source-maps--experimental-fetch--experimental-global-webcrypto--experimental-import-meta-resolve--experimental-loader=module--experimental-network-imports--experimental-policy--no-experimental-repl-await--experimental-specifier-resolution=mode--experimental-vm-modules--experimental-wasi-unstable-preview1--experimental-wasm-modules--force-context-aware--force-fips--frozen-intrinsics--heapsnapshot-near-heap-limit=max_count--heapsnapshot-signal=signal--heap-prof--heap-prof-dir--heap-prof-interval--heap-prof-name--icu-data-dir=file--input-type=type--inspect-brk[=[host:]port]--inspect-port=[host:]port--inspect[=[host:]port]--inspect-publish-uid=stderr,http--insecure-http-parser--jitless--max-http-header-size=size--napi-modules--no-addons--no-deprecation--no-extra-info-on-fatal-exception--no-force-async-hooks-checks--no-global-search-paths--no-warnings--node-memory-debug--openssl-config=file--openssl-legacy-provider--pending-deprecation--policy-integrity=sri--preserve-symlinks--preserve-symlinks-main--prof--prof-process--redirect-warnings=file--report-compact--report-dir=directory,report-directory=directory--report-filename=filename--report-on-fatalerror--report-on-signal--report-signal=signal--report-uncaught-exception--secure-heap=n--secure-heap-min=n--throw-deprecation--title=title--tls-cipher-list=list--tls-keylog=file--tls-max-v1.2--tls-max-v1.3--tls-min-v1.0--tls-min-v1.1--tls-min-v1.2--tls-min-v1.3--trace-atomics-wait--trace-deprecation--trace-event-categories--trace-event-file-pattern--trace-events-enabled--trace-exit--trace-sigint--trace-sync-io--trace-tls--trace-uncaught--trace-warnings--track-heap-objects--unhandled-rejections=mode--use-bundled-ca,--use-openssl-ca--use-largepages=mode--v8-options--v8-pool-size=num--zero-fill-buffers-c,--check-e,--eval "script"-h,--help-i,--interactive-p,--print "script"-r,--require module-v,--version
- Environment variables
FORCE_COLOR=[1, 2, 3]NODE_DEBUG=module[,…]NODE_DEBUG_NATIVE=module[,…]NODE_DISABLE_COLORS=1NODE_EXTRA_CA_CERTS=fileNODE_ICU_DATA=fileNODE_NO_WARNINGS=1NODE_OPTIONS=options...NODE_PATH=path[:…]NODE_PENDING_DEPRECATION=1NODE_PENDING_PIPE_INSTANCES=instancesNODE_PRESERVE_SYMLINKS=1NODE_REDIRECT_WARNINGS=fileNODE_REPL_HISTORY=fileNODE_REPL_EXTERNAL_MODULE=fileNODE_SKIP_PLATFORM_CHECK=valueNODE_TLS_REJECT_UNAUTHORIZED=valueNODE_V8_COVERAGE=dirNO_COLOR=<any>OPENSSL_CONF=fileSSL_CERT_DIR=dirSSL_CERT_FILE=fileTZUV_THREADPOOL_SIZE=size
- Useful V8 options
- Console
- Class:
Consolenew Console(stdout[, stderr][, ignoreErrors])new Console(options)console.assert(value[, ...message])console.clear()console.count([label])console.countReset([label])console.debug(data[, ...args])console.dir(obj[, options])console.dirxml(...data)console.error([data][, ...args])console.group([...label])console.groupCollapsed()console.groupEnd()console.info([data][, ...args])console.log([data][, ...args])console.table(tabularData[, properties])console.time([label])console.timeEnd([label])console.timeLog([label][, ...data])console.trace([message][, ...args])console.warn([data][, ...args])
- Inspector only methods
- Class:
- Corepack
- Crypto
- Determining if crypto support is unavailable
- Class:
Certificate - Class:
Cipher - Class:
Decipher - Class:
DiffieHellmandiffieHellman.computeSecret(otherPublicKey[, inputEncoding][, outputEncoding])diffieHellman.generateKeys([encoding])diffieHellman.getGenerator([encoding])diffieHellman.getPrime([encoding])diffieHellman.getPrivateKey([encoding])diffieHellman.getPublicKey([encoding])diffieHellman.setPrivateKey(privateKey[, encoding])diffieHellman.setPublicKey(publicKey[, encoding])diffieHellman.verifyError
- Class:
DiffieHellmanGroup - Class:
ECDH- Static method:
ECDH.convertKey(key, curve[, inputEncoding[, outputEncoding[, format]]]) ecdh.computeSecret(otherPublicKey[, inputEncoding][, outputEncoding])ecdh.generateKeys([encoding[, format]])ecdh.getPrivateKey([encoding])ecdh.getPublicKey([encoding][, format])ecdh.setPrivateKey(privateKey[, encoding])ecdh.setPublicKey(publicKey[, encoding])
- Static method:
- Class:
Hash - Class:
Hmac - Class:
KeyObject - Class:
Sign - Class:
Verify - Class:
X509Certificatenew X509Certificate(buffer)x509.cax509.checkEmail(email[, options])x509.checkHost(name[, options])x509.checkIP(ip)x509.checkIssued(otherCert)x509.checkPrivateKey(privateKey)x509.fingerprintx509.fingerprint256x509.fingerprint512x509.infoAccessx509.issuerx509.issuerCertificatex509.keyUsagex509.publicKeyx509.rawx509.serialNumberx509.subjectx509.subjectAltNamex509.toJSON()x509.toLegacyObject()x509.toString()x509.validFromx509.validTox509.verify(publicKey)
cryptomodule methods and propertiescrypto.constantscrypto.DEFAULT_ENCODINGcrypto.fipscrypto.checkPrime(candidate[, options, [callback]])crypto.checkPrimeSync(candidate[, options])crypto.createCipher(algorithm, password[, options])crypto.createCipheriv(algorithm, key, iv[, options])crypto.createDecipher(algorithm, password[, options])crypto.createDecipheriv(algorithm, key, iv[, options])crypto.createDiffieHellman(prime[, primeEncoding][, generator][, generatorEncoding])crypto.createDiffieHellman(primeLength[, generator])crypto.createDiffieHellmanGroup(name)crypto.createECDH(curveName)crypto.createHash(algorithm[, options])crypto.createHmac(algorithm, key[, options])crypto.createPrivateKey(key)crypto.createPublicKey(key)crypto.createSecretKey(key[, encoding])crypto.createSign(algorithm[, options])crypto.createVerify(algorithm[, options])crypto.diffieHellman(options)crypto.generateKey(type, options, callback)crypto.generateKeyPair(type, options, callback)crypto.generateKeyPairSync(type, options)crypto.generateKeySync(type, options)crypto.generatePrime(size[, options[, callback]])crypto.generatePrimeSync(size[, options])crypto.getCipherInfo(nameOrNid[, options])crypto.getCiphers()crypto.getCurves()crypto.getDiffieHellman(groupName)crypto.getFips()crypto.getHashes()crypto.getRandomValues(typedArray)crypto.hkdf(digest, ikm, salt, info, keylen, callback)crypto.hkdfSync(digest, ikm, salt, info, keylen)crypto.pbkdf2(password, salt, iterations, keylen, digest, callback)crypto.pbkdf2Sync(password, salt, iterations, keylen, digest)crypto.privateDecrypt(privateKey, buffer)crypto.privateEncrypt(privateKey, buffer)crypto.publicDecrypt(key, buffer)crypto.publicEncrypt(key, buffer)crypto.randomBytes(size[, callback])crypto.randomFillSync(buffer[, offset][, size])crypto.randomFill(buffer[, offset][, size], callback)crypto.randomInt([min, ]max[, callback])crypto.randomUUID([options])crypto.scrypt(password, salt, keylen[, options], callback)crypto.scryptSync(password, salt, keylen[, options])crypto.secureHeapUsed()crypto.setEngine(engine[, flags])crypto.setFips(bool)crypto.sign(algorithm, data, key[, callback])crypto.subtlecrypto.timingSafeEqual(a, b)crypto.verify(algorithm, data, key, signature[, callback])crypto.webcrypto
- Notes
- Crypto constants
- Debugger
- Deprecated APIs
- Revoking deprecations
- List of deprecated APIs
- DEP0001:
http.OutgoingMessage.prototype.flush - DEP0002:
require('_linklist') - DEP0003:
_writableState.buffer - DEP0004:
CryptoStream.prototype.readyState - DEP0005:
Buffer()constructor - DEP0006:
child_processoptions.customFds - DEP0007: Replace
clusterworker.suicidewithworker.exitedAfterDisconnect - DEP0008:
require('constants') - DEP0009:
crypto.pbkdf2without digest - DEP0010:
crypto.createCredentials - DEP0011:
crypto.Credentials - DEP0012:
Domain.dispose - DEP0013:
fsasynchronous function without callback - DEP0014:
fs.readlegacy String interface - DEP0015:
fs.readSynclegacy String interface - DEP0016:
GLOBAL/root - DEP0017:
Intl.v8BreakIterator - DEP0018: Unhandled promise rejections
- DEP0019:
require('.')resolved outside directory - DEP0020:
Server.connections - DEP0021:
Server.listenFD - DEP0022:
os.tmpDir() - DEP0023:
os.getNetworkInterfaces() - DEP0024:
REPLServer.prototype.convertToContext() - DEP0025:
require('sys') - DEP0026:
util.print() - DEP0027:
util.puts() - DEP0028:
util.debug() - DEP0029:
util.error() - DEP0030:
SlowBuffer - DEP0031:
ecdh.setPublicKey() - DEP0032:
domainmodule - DEP0033:
EventEmitter.listenerCount() - DEP0034:
fs.exists(path, callback) - DEP0035:
fs.lchmod(path, mode, callback) - DEP0036:
fs.lchmodSync(path, mode) - DEP0037:
fs.lchown(path, uid, gid, callback) - DEP0038:
fs.lchownSync(path, uid, gid) - DEP0039:
require.extensions - DEP0040:
punycodemodule - DEP0041:
NODE_REPL_HISTORY_FILEenvironment variable - DEP0042:
tls.CryptoStream - DEP0043:
tls.SecurePair - DEP0044:
util.isArray() - DEP0045:
util.isBoolean() - DEP0046:
util.isBuffer() - DEP0047:
util.isDate() - DEP0048:
util.isError() - DEP0049:
util.isFunction() - DEP0050:
util.isNull() - DEP0051:
util.isNullOrUndefined() - DEP0052:
util.isNumber() - DEP0053:
util.isObject() - DEP0054:
util.isPrimitive() - DEP0055:
util.isRegExp() - DEP0056:
util.isString() - DEP0057:
util.isSymbol() - DEP0058:
util.isUndefined() - DEP0059:
util.log() - DEP0060:
util._extend() - DEP0061:
fs.SyncWriteStream - DEP0062:
node --debug - DEP0063:
ServerResponse.prototype.writeHeader() - DEP0064:
tls.createSecurePair() - DEP0065:
repl.REPL_MODE_MAGICandNODE_REPL_MODE=magic - DEP0066:
OutgoingMessage.prototype._headers, OutgoingMessage.prototype._headerNames - DEP0067:
OutgoingMessage.prototype._renderHeaders - DEP0068:
node debug - DEP0069:
vm.runInDebugContext(string) - DEP0070:
async_hooks.currentId() - DEP0071:
async_hooks.triggerId() - DEP0072:
async_hooks.AsyncResource.triggerId() - DEP0073: Several internal properties of
net.Server - DEP0074:
REPLServer.bufferedCommand - DEP0075:
REPLServer.parseREPLKeyword() - DEP0076:
tls.parseCertString() - DEP0077:
Module._debug() - DEP0078:
REPLServer.turnOffEditorMode() - DEP0079: Custom inspection function on objects via
.inspect() - DEP0080:
path._makeLong() - DEP0081:
fs.truncate()using a file descriptor - DEP0082:
REPLServer.prototype.memory() - DEP0083: Disabling ECDH by setting
ecdhCurvetofalse - DEP0084: requiring bundled internal dependencies
- DEP0085: AsyncHooks sensitive API
- DEP0086: Remove
runInAsyncIdScope - DEP0089:
require('assert') - DEP0090: Invalid GCM authentication tag lengths
- DEP0091:
crypto.DEFAULT_ENCODING - DEP0092: Top-level
thisbound tomodule.exports - DEP0093:
crypto.fipsis deprecated and replaced - DEP0094: Using
assert.fail()with more than one argument - DEP0095:
timers.enroll() - DEP0096:
timers.unenroll() - DEP0097:
MakeCallbackwithdomainproperty - DEP0098: AsyncHooks embedder
AsyncResource.emitBeforeandAsyncResource.emitAfterAPIs - DEP0099: Async context-unaware
node::MakeCallbackC++ APIs - DEP0100:
process.assert() - DEP0101:
--with-lttng - DEP0102: Using
noAssertinBuffer#(read|write)operations - DEP0103:
process.binding('util').is[...]typechecks - DEP0104:
process.envstring coercion - DEP0105:
decipher.finaltol - DEP0106:
crypto.createCipherandcrypto.createDecipher - DEP0107:
tls.convertNPNProtocols() - DEP0108:
zlib.bytesRead - DEP0109:
http,https, andtlssupport for invalid URLs - DEP0110:
vm.Scriptcached data - DEP0111:
process.binding() - DEP0112:
dgramprivate APIs - DEP0113:
Cipher.setAuthTag(),Decipher.getAuthTag() - DEP0114:
crypto._toBuf() - DEP0115:
crypto.prng(),crypto.pseudoRandomBytes(),crypto.rng() - DEP0116: Legacy URL API
- DEP0117: Native crypto handles
- DEP0118:
dns.lookup()support for a falsy host name - DEP0119:
process.binding('uv').errname()private API - DEP0120: Windows Performance Counter support
- DEP0121:
net._setSimultaneousAccepts() - DEP0122:
tlsServer.prototype.setOptions() - DEP0123: setting the TLS ServerName to an IP address
- DEP0124: using
REPLServer.rli - DEP0125:
require('_stream_wrap') - DEP0126:
timers.active() - DEP0127:
timers._unrefActive() - DEP0128: modules with an invalid
mainentry and anindex.jsfile - DEP0129:
ChildProcess._channel - DEP0130:
Module.createRequireFromPath() - DEP0131: Legacy HTTP parser
- DEP0132:
worker.terminate()with callback - DEP0133:
httpconnection - DEP0134:
process._tickCallback - DEP0135:
WriteStream.open()andReadStream.open()are internal - DEP0136:
httpfinished - DEP0137: Closing fs.FileHandle on garbage collection
- DEP0138:
process.mainModule - DEP0139:
process.umask()with no arguments - DEP0140: Use
request.destroy()instead ofrequest.abort() - DEP0141:
repl.inputStreamandrepl.outputStream - DEP0142:
repl._builtinLibs - DEP0143:
Transform._transformState - DEP0144:
module.parent - DEP0145:
socket.bufferSize - DEP0146:
new crypto.Certificate() - DEP0147:
fs.rmdir(path, { recursive: true }) - DEP0148: Folder mappings in
"exports"(trailing"/") - DEP0149:
http.IncomingMessage#connection - DEP0150: Changing the value of
process.config - DEP0151: Main index lookup and extension searching
- DEP0152: Extension PerformanceEntry properties
- DEP0153:
dns.lookupanddnsPromises.lookupoptions type coercion - DEP0154: RSA-PSS generate key pair options
- DEP0155: Trailing slashes in pattern specifier resolutions
- DEP0156:
.abortedproperty and'abort','aborted'event inhttp - DEP0157: Thenable support in streams
- DEP0158:
buffer.slice(start, end) - DEP0160:
process.on('multipleResolves', handler) - DEP0161:
process._getActiveRequests()andprocess._getActiveHandles() - DEP0162:
fs.write(),fs.writeFileSync()coercion to string
- DEP0001:
- Diagnostics Channel
- DNS
- Class:
dns.Resolver dns.getServers()dns.lookup(hostname[, options], callback)dns.lookupService(address, port, callback)dns.resolve(hostname[, rrtype], callback)dns.resolve4(hostname[, options], callback)dns.resolve6(hostname[, options], callback)dns.resolveAny(hostname, callback)dns.resolveCname(hostname, callback)dns.resolveCaa(hostname, callback)dns.resolveMx(hostname, callback)dns.resolveNaptr(hostname, callback)dns.resolveNs(hostname, callback)dns.resolvePtr(hostname, callback)dns.resolveSoa(hostname, callback)dns.resolveSrv(hostname, callback)dns.resolveTxt(hostname, callback)dns.reverse(ip, callback)dns.setDefaultResultOrder(order)dns.setServers(servers)- DNS promises API
- Class:
dnsPromises.Resolver resolver.cancel()dnsPromises.getServers()dnsPromises.lookup(hostname[, options])dnsPromises.lookupService(address, port)dnsPromises.resolve(hostname[, rrtype])dnsPromises.resolve4(hostname[, options])dnsPromises.resolve6(hostname[, options])dnsPromises.resolveAny(hostname)dnsPromises.resolveCaa(hostname)dnsPromises.resolveCname(hostname)dnsPromises.resolveMx(hostname)dnsPromises.resolveNaptr(hostname)dnsPromises.resolveNs(hostname)dnsPromises.resolvePtr(hostname)dnsPromises.resolveSoa(hostname)dnsPromises.resolveSrv(hostname)dnsPromises.resolveTxt(hostname)dnsPromises.reverse(ip)dnsPromises.setDefaultResultOrder(order)dnsPromises.setServers(servers)
- Class:
- Error codes
- Implementation considerations
- Class:
- Domain
- Errors
- Error propagation and interception
- Class:
Error - Class:
AssertionError - Class:
RangeError - Class:
ReferenceError - Class:
SyntaxError - Class:
SystemError - Class:
TypeError - Exceptions vs. errors
- OpenSSL errors
- Node.js error codes
ABORT_ERRERR_AMBIGUOUS_ARGUMENTERR_ARG_NOT_ITERABLEERR_ASSERTIONERR_ASYNC_CALLBACKERR_ASYNC_TYPEERR_BROTLI_COMPRESSION_FAILEDERR_BROTLI_INVALID_PARAMERR_BUFFER_CONTEXT_NOT_AVAILABLEERR_BUFFER_OUT_OF_BOUNDSERR_BUFFER_TOO_LARGEERR_CANNOT_WATCH_SIGINTERR_CHILD_CLOSED_BEFORE_REPLYERR_CHILD_PROCESS_IPC_REQUIREDERR_CHILD_PROCESS_STDIO_MAXBUFFERERR_CLOSED_MESSAGE_PORTERR_CONSOLE_WRITABLE_STREAMERR_CONSTRUCT_CALL_INVALIDERR_CONSTRUCT_CALL_REQUIREDERR_CONTEXT_NOT_INITIALIZEDERR_CRYPTO_CUSTOM_ENGINE_NOT_SUPPORTEDERR_CRYPTO_ECDH_INVALID_FORMATERR_CRYPTO_ECDH_INVALID_PUBLIC_KEYERR_CRYPTO_ENGINE_UNKNOWNERR_CRYPTO_FIPS_FORCEDERR_CRYPTO_FIPS_UNAVAILABLEERR_CRYPTO_HASH_FINALIZEDERR_CRYPTO_HASH_UPDATE_FAILEDERR_CRYPTO_INCOMPATIBLE_KEYERR_CRYPTO_INCOMPATIBLE_KEY_OPTIONSERR_CRYPTO_INITIALIZATION_FAILEDERR_CRYPTO_INVALID_AUTH_TAGERR_CRYPTO_INVALID_COUNTERERR_CRYPTO_INVALID_CURVEERR_CRYPTO_INVALID_DIGESTERR_CRYPTO_INVALID_IVERR_CRYPTO_INVALID_JWKERR_CRYPTO_INVALID_KEY_OBJECT_TYPEERR_CRYPTO_INVALID_KEYLENERR_CRYPTO_INVALID_KEYPAIRERR_CRYPTO_INVALID_KEYTYPEERR_CRYPTO_INVALID_MESSAGELENERR_CRYPTO_INVALID_SCRYPT_PARAMSERR_CRYPTO_INVALID_STATEERR_CRYPTO_INVALID_TAG_LENGTHERR_CRYPTO_JOB_INIT_FAILEDERR_CRYPTO_JWK_UNSUPPORTED_CURVEERR_CRYPTO_JWK_UNSUPPORTED_KEY_TYPEERR_CRYPTO_OPERATION_FAILEDERR_CRYPTO_PBKDF2_ERRORERR_CRYPTO_SCRYPT_INVALID_PARAMETERERR_CRYPTO_SCRYPT_NOT_SUPPORTEDERR_CRYPTO_SIGN_KEY_REQUIREDERR_CRYPTO_TIMING_SAFE_EQUAL_LENGTHERR_CRYPTO_UNKNOWN_CIPHERERR_CRYPTO_UNKNOWN_DH_GROUPERR_CRYPTO_UNSUPPORTED_OPERATIONERR_DEBUGGER_ERRORERR_DEBUGGER_STARTUP_ERRORERR_DLOPEN_DISABLEDERR_DLOPEN_FAILEDERR_DIR_CLOSEDERR_DIR_CONCURRENT_OPERATIONERR_DNS_SET_SERVERS_FAILEDERR_DOMAIN_CALLBACK_NOT_AVAILABLEERR_DOMAIN_CANNOT_SET_UNCAUGHT_EXCEPTION_CAPTUREERR_ENCODING_INVALID_ENCODED_DATAERR_ENCODING_NOT_SUPPORTEDERR_EVAL_ESM_CANNOT_PRINTERR_EVENT_RECURSIONERR_EXECUTION_ENVIRONMENT_NOT_AVAILABLEERR_FALSY_VALUE_REJECTIONERR_FEATURE_UNAVAILABLE_ON_PLATFORMERR_FS_CP_DIR_TO_NON_DIRERR_FS_CP_EEXISTERR_FS_CP_EINVALERR_FS_CP_FIFO_PIPEERR_FS_CP_NON_DIR_TO_DIRERR_FS_CP_SOCKETERR_FS_CP_SYMLINK_TO_SUBDIRECTORYERR_FS_CP_UNKNOWNERR_FS_EISDIRERR_FS_FILE_TOO_LARGEERR_FS_INVALID_SYMLINK_TYPEERR_HTTP_HEADERS_SENTERR_HTTP_INVALID_HEADER_VALUEERR_HTTP_INVALID_STATUS_CODEERR_HTTP_REQUEST_TIMEOUTERR_HTTP_SOCKET_ENCODINGERR_HTTP_TRAILER_INVALIDERR_HTTP2_ALTSVC_INVALID_ORIGINERR_HTTP2_ALTSVC_LENGTHERR_HTTP2_CONNECT_AUTHORITYERR_HTTP2_CONNECT_PATHERR_HTTP2_CONNECT_SCHEMEERR_HTTP2_ERRORERR_HTTP2_GOAWAY_SESSIONERR_HTTP2_HEADER_SINGLE_VALUEERR_HTTP2_HEADERS_AFTER_RESPONDERR_HTTP2_HEADERS_SENTERR_HTTP2_INFO_STATUS_NOT_ALLOWEDERR_HTTP2_INVALID_CONNECTION_HEADERSERR_HTTP2_INVALID_HEADER_VALUEERR_HTTP2_INVALID_INFO_STATUSERR_HTTP2_INVALID_ORIGINERR_HTTP2_INVALID_PACKED_SETTINGS_LENGTHERR_HTTP2_INVALID_PSEUDOHEADERERR_HTTP2_INVALID_SESSIONERR_HTTP2_INVALID_SETTING_VALUEERR_HTTP2_INVALID_STREAMERR_HTTP2_MAX_PENDING_SETTINGS_ACKERR_HTTP2_NESTED_PUSHERR_HTTP2_NO_MEMERR_HTTP2_NO_SOCKET_MANIPULATIONERR_HTTP2_ORIGIN_LENGTHERR_HTTP2_OUT_OF_STREAMSERR_HTTP2_PAYLOAD_FORBIDDENERR_HTTP2_PING_CANCELERR_HTTP2_PING_LENGTHERR_HTTP2_PSEUDOHEADER_NOT_ALLOWEDERR_HTTP2_PUSH_DISABLEDERR_HTTP2_SEND_FILEERR_HTTP2_SEND_FILE_NOSEEKERR_HTTP2_SESSION_ERRORERR_HTTP2_SETTINGS_CANCELERR_HTTP2_SOCKET_BOUNDERR_HTTP2_SOCKET_UNBOUNDERR_HTTP2_STATUS_101ERR_HTTP2_STATUS_INVALIDERR_HTTP2_STREAM_CANCELERR_HTTP2_STREAM_ERRORERR_HTTP2_STREAM_SELF_DEPENDENCYERR_HTTP2_TOO_MANY_INVALID_FRAMESERR_HTTP2_TRAILERS_ALREADY_SENTERR_HTTP2_TRAILERS_NOT_READYERR_HTTP2_UNSUPPORTED_PROTOCOLERR_ILLEGAL_CONSTRUCTORERR_IMPORT_ASSERTION_TYPE_FAILEDERR_IMPORT_ASSERTION_TYPE_MISSINGERR_IMPORT_ASSERTION_TYPE_UNSUPPORTEDERR_INCOMPATIBLE_OPTION_PAIRERR_INPUT_TYPE_NOT_ALLOWEDERR_INSPECTOR_ALREADY_ACTIVATEDERR_INSPECTOR_ALREADY_CONNECTEDERR_INSPECTOR_CLOSEDERR_INSPECTOR_COMMANDERR_INSPECTOR_NOT_ACTIVEERR_INSPECTOR_NOT_AVAILABLEERR_INSPECTOR_NOT_CONNECTEDERR_INSPECTOR_NOT_WORKERERR_INTERNAL_ASSERTIONERR_INVALID_ADDRESS_FAMILYERR_INVALID_ARG_TYPEERR_INVALID_ARG_VALUEERR_INVALID_ASYNC_IDERR_INVALID_BUFFER_SIZEERR_INVALID_CALLBACKERR_INVALID_CHARERR_INVALID_CURSOR_POSERR_INVALID_FDERR_INVALID_FD_TYPEERR_INVALID_FILE_URL_HOSTERR_INVALID_FILE_URL_PATHERR_INVALID_HANDLE_TYPEERR_INVALID_HTTP_TOKENERR_INVALID_IP_ADDRESSERR_INVALID_MODULEERR_INVALID_MODULE_SPECIFIERERR_INVALID_PACKAGE_CONFIGERR_INVALID_PACKAGE_TARGETERR_INVALID_PERFORMANCE_MARKERR_INVALID_PROTOCOLERR_INVALID_REPL_EVAL_CONFIGERR_INVALID_REPL_INPUTERR_INVALID_RETURN_PROPERTYERR_INVALID_RETURN_PROPERTY_VALUEERR_INVALID_RETURN_VALUEERR_INVALID_STATEERR_INVALID_SYNC_FORK_INPUTERR_INVALID_THISERR_INVALID_TRANSFER_OBJECTERR_INVALID_TUPLEERR_INVALID_URIERR_INVALID_URLERR_INVALID_URL_SCHEMEERR_IPC_CHANNEL_CLOSEDERR_IPC_DISCONNECTEDERR_IPC_ONE_PIPEERR_IPC_SYNC_FORKERR_MANIFEST_ASSERT_INTEGRITYERR_MANIFEST_DEPENDENCY_MISSINGERR_MANIFEST_INTEGRITY_MISMATCHERR_MANIFEST_INVALID_RESOURCE_FIELDERR_MANIFEST_INVALID_SPECIFIERERR_MANIFEST_PARSE_POLICYERR_MANIFEST_TDZERR_MANIFEST_UNKNOWN_ONERRORERR_MEMORY_ALLOCATION_FAILEDERR_MESSAGE_TARGET_CONTEXT_UNAVAILABLEERR_METHOD_NOT_IMPLEMENTEDERR_MISSING_ARGSERR_MISSING_OPTIONERR_MISSING_PASSPHRASEERR_MISSING_PLATFORM_FOR_WORKERERR_MISSING_TRANSFERABLE_IN_TRANSFER_LISTERR_MODULE_NOT_FOUNDERR_MULTIPLE_CALLBACKERR_NAPI_CONS_FUNCTIONERR_NAPI_INVALID_DATAVIEW_ARGSERR_NAPI_INVALID_TYPEDARRAY_ALIGNMENTERR_NAPI_INVALID_TYPEDARRAY_LENGTHERR_NAPI_TSFN_CALL_JSERR_NAPI_TSFN_GET_UNDEFINEDERR_NAPI_TSFN_START_IDLE_LOOPERR_NAPI_TSFN_STOP_IDLE_LOOPERR_NO_CRYPTOERR_NO_ICUERR_NON_CONTEXT_AWARE_DISABLEDERR_OUT_OF_RANGEERR_PACKAGE_IMPORT_NOT_DEFINEDERR_PACKAGE_PATH_NOT_EXPORTEDERR_PERFORMANCE_INVALID_TIMESTAMPERR_PERFORMANCE_MEASURE_INVALID_OPTIONSERR_PROTO_ACCESSERR_REQUIRE_ESMERR_SCRIPT_EXECUTION_INTERRUPTEDERR_SCRIPT_EXECUTION_TIMEOUTERR_SERVER_ALREADY_LISTENERR_SERVER_NOT_RUNNINGERR_SOCKET_ALREADY_BOUNDERR_SOCKET_BAD_BUFFER_SIZEERR_SOCKET_BAD_PORTERR_SOCKET_BAD_TYPEERR_SOCKET_BUFFER_SIZEERR_SOCKET_CLOSEDERR_SOCKET_DGRAM_IS_CONNECTEDERR_SOCKET_DGRAM_NOT_CONNECTEDERR_SOCKET_DGRAM_NOT_RUNNINGERR_SRI_PARSEERR_STREAM_ALREADY_FINISHEDERR_STREAM_CANNOT_PIPEERR_STREAM_DESTROYEDERR_STREAM_NULL_VALUESERR_STREAM_PREMATURE_CLOSEERR_STREAM_PUSH_AFTER_EOFERR_STREAM_UNSHIFT_AFTER_END_EVENTERR_STREAM_WRAPERR_STREAM_WRITE_AFTER_ENDERR_STRING_TOO_LONGERR_SYNTHETICERR_SYSTEM_ERRORERR_TLS_CERT_ALTNAME_FORMATERR_TLS_CERT_ALTNAME_INVALIDERR_TLS_DH_PARAM_SIZEERR_TLS_HANDSHAKE_TIMEOUTERR_TLS_INVALID_CONTEXTERR_TLS_INVALID_PROTOCOL_METHODERR_TLS_INVALID_PROTOCOL_VERSIONERR_TLS_INVALID_STATEERR_TLS_PROTOCOL_VERSION_CONFLICTERR_TLS_PSK_SET_IDENTIY_HINT_FAILEDERR_TLS_RENEGOTIATION_DISABLEDERR_TLS_REQUIRED_SERVER_NAMEERR_TLS_SESSION_ATTACKERR_TLS_SNI_FROM_SERVERERR_TRACE_EVENTS_CATEGORY_REQUIREDERR_TRACE_EVENTS_UNAVAILABLEERR_TRANSFORM_ALREADY_TRANSFORMINGERR_TRANSFORM_WITH_LENGTH_0ERR_TTY_INIT_FAILEDERR_UNAVAILABLE_DURING_EXITERR_UNCAUGHT_EXCEPTION_CAPTURE_ALREADY_SETERR_UNESCAPED_CHARACTERSERR_UNHANDLED_ERRORERR_UNKNOWN_BUILTIN_MODULEERR_UNKNOWN_CREDENTIALERR_UNKNOWN_ENCODINGERR_UNKNOWN_FILE_EXTENSIONERR_UNKNOWN_MODULE_FORMATERR_UNKNOWN_SIGNALERR_UNSUPPORTED_DIR_IMPORTERR_UNSUPPORTED_ESM_URL_SCHEMEERR_VALID_PERFORMANCE_ENTRY_TYPEERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSINGERR_VM_MODULE_ALREADY_LINKEDERR_VM_MODULE_CACHED_DATA_REJECTEDERR_VM_MODULE_CANNOT_CREATE_CACHED_DATAERR_VM_MODULE_DIFFERENT_CONTEXTERR_VM_MODULE_LINKING_ERROREDERR_VM_MODULE_LINK_FAILUREERR_VM_MODULE_NOT_MODULEERR_VM_MODULE_STATUSERR_WASI_ALREADY_STARTEDERR_WASI_NOT_STARTEDERR_WORKER_INIT_FAILEDERR_WORKER_INVALID_EXEC_ARGVERR_WORKER_NOT_RUNNINGERR_WORKER_OUT_OF_MEMORYERR_WORKER_PATHERR_WORKER_UNSERIALIZABLE_ERRORERR_WORKER_UNSUPPORTED_OPERATIONERR_ZLIB_INITIALIZATION_FAILEDHPE_HEADER_OVERFLOWHPE_UNEXPECTED_CONTENT_LENGTHMODULE_NOT_FOUND
- Legacy Node.js error codes
ERR_CANNOT_TRANSFER_OBJECTERR_CRYPTO_HASH_DIGEST_NO_UTF16ERR_HTTP2_FRAME_ERRORERR_HTTP2_HEADERS_OBJECTERR_HTTP2_HEADER_REQUIREDERR_HTTP2_INFO_HEADERS_AFTER_RESPONDERR_HTTP2_STREAM_CLOSEDERR_HTTP_INVALID_CHARERR_INDEX_OUT_OF_RANGEERR_INVALID_OPT_VALUEERR_INVALID_OPT_VALUE_ENCODINGERR_MISSING_MESSAGE_PORT_IN_TRANSFER_LISTERR_NAPI_CONS_PROTOTYPE_OBJECTERR_NETWORK_IMPORT_BAD_RESPONSEERR_NETWORK_IMPORT_DISALLOWEDERR_NO_LONGER_SUPPORTEDERR_OPERATION_FAILEDERR_OUTOFMEMORYERR_PARSE_HISTORY_DATAERR_SOCKET_CANNOT_SENDERR_STDERR_CLOSEERR_STDOUT_CLOSEERR_STREAM_READ_NOT_IMPLEMENTEDERR_TLS_RENEGOTIATION_FAILEDERR_TRANSFERRING_EXTERNALIZED_SHAREDARRAYBUFFERERR_UNKNOWN_STDIN_TYPEERR_UNKNOWN_STREAM_TYPEERR_V8BREAKITERATORERR_VALUE_OUT_OF_RANGEERR_VM_MODULE_NOT_LINKEDERR_WORKER_UNSUPPORTED_EXTENSIONERR_ZLIB_BINDING_CLOSEDERR_CPU_USAGE
- Events
- Passing arguments and
thisto listeners - Asynchronous vs. synchronous
- Handling events only once
- Error events
- Capture rejections of promises
- Class:
EventEmitter- Event:
'newListener' - Event:
'removeListener' emitter.addListener(eventName, listener)emitter.emit(eventName[, ...args])emitter.eventNames()emitter.getMaxListeners()emitter.listenerCount(eventName)emitter.listeners(eventName)emitter.off(eventName, listener)emitter.on(eventName, listener)emitter.once(eventName, listener)emitter.prependListener(eventName, listener)emitter.prependOnceListener(eventName, listener)emitter.removeAllListeners([eventName])emitter.removeListener(eventName, listener)emitter.setMaxListeners(n)emitter.rawListeners(eventName)emitter[Symbol.for('nodejs.rejection')](err, eventName[, ...args])
- Event:
events.defaultMaxListenersevents.errorMonitorevents.getEventListeners(emitterOrTarget, eventName)events.once(emitter, name[, options])events.captureRejectionsevents.captureRejectionSymbolevents.listenerCount(emitter, eventName)events.on(emitter, eventName[, options])events.setMaxListeners(n[, ...eventTargets])- Class:
events.EventEmitterAsyncResource extends EventEmitter EventTargetandEventAPI- Node.js
EventTargetvs. DOMEventTarget NodeEventTargetvs.EventEmitter- Event listener
EventTargeterror handling- Class:
Eventevent.bubblesevent.cancelBubble()event.cancelableevent.composedevent.composedPath()event.currentTargetevent.defaultPreventedevent.eventPhaseevent.isTrustedevent.preventDefault()event.returnValueevent.srcElementevent.stopImmediatePropagation()event.stopPropagation()event.targetevent.timeStampevent.type
- Class:
EventTarget - Class:
NodeEventTargetnodeEventTarget.addListener(type, listener[, options])nodeEventTarget.eventNames()nodeEventTarget.listenerCount(type)nodeEventTarget.off(type, listener)nodeEventTarget.on(type, listener[, options])nodeEventTarget.once(type, listener[, options])nodeEventTarget.removeAllListeners([type])nodeEventTarget.removeListener(type, listener)
- Node.js
- Passing arguments and
- File system
- Promise example
- Callback example
- Synchronous example
- Promises API
- Class:
FileHandle- Event:
'close' filehandle.appendFile(data[, options])filehandle.chmod(mode)filehandle.chown(uid, gid)filehandle.close()filehandle.createReadStream([options])filehandle.createWriteStream([options])filehandle.datasync()filehandle.fdfilehandle.read(buffer, offset, length, position)filehandle.read([options])filehandle.readableWebStream()filehandle.readFile(options)filehandle.readv(buffers[, position])filehandle.stat([options])filehandle.sync()filehandle.truncate(len)filehandle.utimes(atime, mtime)filehandle.write(buffer[, offset[, length[, position]]])filehandle.write(string[, position[, encoding]])filehandle.writeFile(data, options)filehandle.writev(buffers[, position])
- Event:
fsPromises.access(path[, mode])fsPromises.appendFile(path, data[, options])fsPromises.chmod(path, mode)fsPromises.chown(path, uid, gid)fsPromises.copyFile(src, dest[, mode])fsPromises.cp(src, dest[, options])fsPromises.lchmod(path, mode)fsPromises.lchown(path, uid, gid)fsPromises.lutimes(path, atime, mtime)fsPromises.link(existingPath, newPath)fsPromises.lstat(path[, options])fsPromises.mkdir(path[, options])fsPromises.mkdtemp(prefix[, options])fsPromises.open(path, flags[, mode])fsPromises.opendir(path[, options])fsPromises.readdir(path[, options])fsPromises.readFile(path[, options])fsPromises.readlink(path[, options])fsPromises.realpath(path[, options])fsPromises.rename(oldPath, newPath)fsPromises.rmdir(path[, options])fsPromises.rm(path[, options])fsPromises.stat(path[, options])fsPromises.symlink(target, path[, type])fsPromises.truncate(path[, len])fsPromises.unlink(path)fsPromises.utimes(path, atime, mtime)fsPromises.watch(filename[, options])fsPromises.writeFile(file, data[, options])
- Class:
- Callback API
fs.access(path[, mode], callback)fs.appendFile(path, data[, options], callback)fs.chmod(path, mode, callback)fs.chown(path, uid, gid, callback)fs.close(fd[, callback])fs.copyFile(src, dest[, mode], callback)fs.cp(src, dest[, options], callback)fs.createReadStream(path[, options])fs.createWriteStream(path[, options])fs.exists(path, callback)fs.fchmod(fd, mode, callback)fs.fchown(fd, uid, gid, callback)fs.fdatasync(fd, callback)fs.fstat(fd[, options], callback)fs.fsync(fd, callback)fs.ftruncate(fd[, len], callback)fs.futimes(fd, atime, mtime, callback)fs.lchmod(path, mode, callback)fs.lchown(path, uid, gid, callback)fs.lutimes(path, atime, mtime, callback)fs.link(existingPath, newPath, callback)fs.lstat(path[, options], callback)fs.mkdir(path[, options], callback)fs.mkdtemp(prefix[, options], callback)fs.open(path[, flags[, mode]], callback)fs.opendir(path[, options], callback)fs.read(fd, buffer, offset, length, position, callback)fs.read(fd, [options,] callback)fs.readdir(path[, options], callback)fs.readFile(path[, options], callback)fs.readlink(path[, options], callback)fs.readv(fd, buffers[, position], callback)fs.realpath(path[, options], callback)fs.realpath.native(path[, options], callback)fs.rename(oldPath, newPath, callback)fs.rmdir(path[, options], callback)fs.rm(path[, options], callback)fs.stat(path[, options], callback)fs.symlink(target, path[, type], callback)fs.truncate(path[, len], callback)fs.unlink(path, callback)fs.unwatchFile(filename[, listener])fs.utimes(path, atime, mtime, callback)fs.watch(filename[, options][, listener])fs.watchFile(filename[, options], listener)fs.write(fd, buffer[, offset[, length[, position]]], callback)fs.write(fd, string[, position[, encoding]], callback)fs.writeFile(file, data[, options], callback)fs.writev(fd, buffers[, position], callback)
- Synchronous API
fs.accessSync(path[, mode])fs.appendFileSync(path, data[, options])fs.chmodSync(path, mode)fs.chownSync(path, uid, gid)fs.closeSync(fd)fs.copyFileSync(src, dest[, mode])fs.cpSync(src, dest[, options])fs.existsSync(path)fs.fchmodSync(fd, mode)fs.fchownSync(fd, uid, gid)fs.fdatasyncSync(fd)fs.fstatSync(fd[, options])fs.fsyncSync(fd)fs.ftruncateSync(fd[, len])fs.futimesSync(fd, atime, mtime)fs.lchmodSync(path, mode)fs.lchownSync(path, uid, gid)fs.lutimesSync(path, atime, mtime)fs.linkSync(existingPath, newPath)fs.lstatSync(path[, options])fs.mkdirSync(path[, options])fs.mkdtempSync(prefix[, options])fs.opendirSync(path[, options])fs.openSync(path[, flags[, mode]])fs.readdirSync(path[, options])fs.readFileSync(path[, options])fs.readlinkSync(path[, options])fs.readSync(fd, buffer, offset, length, position)fs.readSync(fd, buffer[, options])fs.readvSync(fd, buffers[, position])fs.realpathSync(path[, options])fs.realpathSync.native(path[, options])fs.renameSync(oldPath, newPath)fs.rmdirSync(path[, options])fs.rmSync(path[, options])fs.statSync(path[, options])fs.symlinkSync(target, path[, type])fs.truncateSync(path[, len])fs.unlinkSync(path)fs.utimesSync(path, atime, mtime)fs.writeFileSync(file, data[, options])fs.writeSync(fd, buffer[, offset[, length[, position]]])fs.writeSync(fd, string[, position[, encoding]])fs.writevSync(fd, buffers[, position])
- Common Objects
- Class:
fs.Dir - Class:
fs.Dirent - Class:
fs.FSWatcher - Class:
fs.StatWatcher - Class:
fs.ReadStream - Class:
fs.Statsstats.isBlockDevice()stats.isCharacterDevice()stats.isDirectory()stats.isFIFO()stats.isFile()stats.isSocket()stats.isSymbolicLink()stats.devstats.inostats.modestats.nlinkstats.uidstats.gidstats.rdevstats.sizestats.blksizestats.blocksstats.atimeMsstats.mtimeMsstats.ctimeMsstats.birthtimeMsstats.atimeNsstats.mtimeNsstats.ctimeNsstats.birthtimeNsstats.atimestats.mtimestats.ctimestats.birthtime- Stat time values
- Class:
fs.WriteStream fs.constants
- Class:
- Notes
- Global objects
- Class:
AbortController - Class:
Buffer __dirname__filenameatob(data)btoa(data)clearImmediate(immediateObject)clearInterval(intervalObject)clearTimeout(timeoutObject)consoleCryptocryptoCryptoKeyEventEventTargetexportsfetch- Class
FormData global- Class
Headers MessageChannelMessageEventMessagePortmoduleperformanceprocessqueueMicrotask(callback)require()ResponseRequestsetImmediate(callback[, ...args])setInterval(callback, delay[, ...args])setTimeout(callback, delay[, ...args])structuredClone(value[, options])SubtleCryptoDOMExceptionTextDecoderTextEncoderURLURLSearchParamsWebAssembly
- Class:
- HTTP
- Class:
http.Agent - Class:
http.ClientRequest- Event:
'abort' - Event:
'connect' - Event:
'continue' - Event:
'information' - Event:
'response' - Event:
'socket' - Event:
'timeout' - Event:
'upgrade' request.abort()request.abortedrequest.connectionrequest.end([data[, encoding]][, callback])request.destroy([error])request.finishedrequest.flushHeaders()request.getHeader(name)request.getRawHeaderNames()request.maxHeadersCountrequest.pathrequest.methodrequest.hostrequest.protocolrequest.removeHeader(name)request.reusedSocketrequest.setHeader(name, value)request.setNoDelay([noDelay])request.setSocketKeepAlive([enable][, initialDelay])request.setTimeout(timeout[, callback])request.socketrequest.writableEndedrequest.writableFinishedrequest.write(chunk[, encoding][, callback])
- Event:
- Class:
http.Server- Event:
'checkContinue' - Event:
'checkExpectation' - Event:
'clientError' - Event:
'close' - Event:
'connect' - Event:
'connection' - Event:
'request' - Event:
'upgrade' server.close([callback])server.headersTimeoutserver.listen()server.listeningserver.maxHeadersCountserver.requestTimeoutserver.setTimeout([msecs][, callback])server.maxRequestsPerSocketserver.timeoutserver.keepAliveTimeout
- Event:
- Class:
http.ServerResponse- Event:
'close' - Event:
'finish' response.addTrailers(headers)response.connectionresponse.cork()response.end([data[, encoding]][, callback])response.finishedresponse.flushHeaders()response.getHeader(name)response.getHeaderNames()response.getHeaders()response.hasHeader(name)response.headersSentresponse.removeHeader(name)response.reqresponse.sendDateresponse.setHeader(name, value)response.setTimeout(msecs[, callback])response.socketresponse.statusCoderesponse.statusMessageresponse.uncork()response.writableEndedresponse.writableFinishedresponse.write(chunk[, encoding][, callback])response.writeContinue()response.writeHead(statusCode[, statusMessage][, headers])response.writeProcessing()
- Event:
- Class:
http.IncomingMessage- Event:
'aborted' - Event:
'close' message.abortedmessage.completemessage.connectionmessage.destroy([error])message.headersmessage.httpVersionmessage.methodmessage.rawHeadersmessage.rawTrailersmessage.setTimeout(msecs[, callback])message.socketmessage.statusCodemessage.statusMessagemessage.trailersmessage.url
- Event:
- Class:
http.OutgoingMessage- Event:
'drain' - Event:
'finish' - Event:
'prefinish' outgoingMessage.addTrailers(headers)outgoingMessage.connectionoutgoingMessage.cork()outgoingMessage.destroy([error])outgoingMessage.end(chunk[, encoding][, callback])outgoingMessage.flushHeaders()outgoingMessage.getHeader(name)outgoingMessage.getHeaderNames()outgoingMessage.getHeaders()outgoingMessage.hasHeader(name)outgoingMessage.headersSentoutgoingMessage.pipe()outgoingMessage.removeHeader()outgoingMessage.setHeader(name, value)outgoingMessage.setTimeout(msesc[, callback])outgoingMessage.socketoutgoingMessage.uncork()outgoingMessage.writableCorkedoutgoingMessage.writableEndedoutgoingMessage.writableFinishedoutgoingMessage.writableHighWaterMarkoutgoingMessage.writableLengthoutgoingMessage.writableObjectModeoutgoingMessage.write(chunk[, encoding][, callback])
- Event:
http.METHODShttp.STATUS_CODEShttp.createServer([options][, requestListener])http.get(options[, callback])http.get(url[, options][, callback])http.globalAgenthttp.maxHeaderSizehttp.request(options[, callback])http.request(url[, options][, callback])http.validateHeaderName(name)http.validateHeaderValue(name, value)
- Class:
- HTTP/2
- Determining if crypto support is unavailable
- Core API
- Server-side example
- Client-side example
- Class:
Http2SessionHttp2Sessionand sockets- Event:
'close' - Event:
'connect' - Event:
'error' - Event:
'frameError' - Event:
'goaway' - Event:
'localSettings' - Event:
'ping' - Event:
'remoteSettings' - Event:
'stream' - Event:
'timeout' http2session.alpnProtocolhttp2session.close([callback])http2session.closedhttp2session.connectinghttp2session.destroy([error][, code])http2session.destroyedhttp2session.encryptedhttp2session.goaway([code[, lastStreamID[, opaqueData]]])http2session.localSettingshttp2session.originSethttp2session.pendingSettingsAckhttp2session.ping([payload, ]callback)http2session.ref()http2session.remoteSettingshttp2session.setLocalWindowSize(windowSize)http2session.setTimeout(msecs, callback)http2session.sockethttp2session.statehttp2session.settings([settings][, callback])http2session.typehttp2session.unref()
- Class:
ServerHttp2Session - Class:
ClientHttp2Session - Class:
Http2StreamHttp2StreamLifecycle- Event:
'aborted' - Event:
'close' - Event:
'error' - Event:
'frameError' - Event:
'ready' - Event:
'timeout' - Event:
'trailers' - Event:
'wantTrailers' http2stream.abortedhttp2stream.bufferSizehttp2stream.close(code[, callback])http2stream.closedhttp2stream.destroyedhttp2stream.endAfterHeadershttp2stream.idhttp2stream.pendinghttp2stream.priority(options)http2stream.rstCodehttp2stream.sentHeadershttp2stream.sentInfoHeadershttp2stream.sentTrailershttp2stream.sessionhttp2stream.setTimeout(msecs, callback)http2stream.statehttp2stream.sendTrailers(headers)
- Class:
ClientHttp2Stream - Class:
ServerHttp2Stream - Class:
Http2Server - Class:
Http2SecureServer http2.createServer(options[, onRequestHandler])http2.createSecureServer(options[, onRequestHandler])http2.connect(authority[, options][, listener])http2.constantshttp2.getDefaultSettings()http2.getPackedSettings([settings])http2.getUnpackedSettings(buf)http2.sensitiveHeaders- Headers object
- Settings object
- Error handling
- Invalid character handling in header names and values
- Push streams on the client
- Supporting the
CONNECTmethod - The extended
CONNECTprotocol
- Compatibility API
- ALPN negotiation
- Class:
http2.Http2ServerRequest- Event:
'aborted' - Event:
'close' request.abortedrequest.authorityrequest.completerequest.connectionrequest.destroy([error])request.headersrequest.httpVersionrequest.methodrequest.rawHeadersrequest.rawTrailersrequest.schemerequest.setTimeout(msecs, callback)request.socketrequest.streamrequest.trailersrequest.url
- Event:
- Class:
http2.Http2ServerResponse- Event:
'close' - Event:
'finish' response.addTrailers(headers)response.connectionresponse.createPushResponse(headers, callback)response.end([data[, encoding]][, callback])response.finishedresponse.getHeader(name)response.getHeaderNames()response.getHeaders()response.hasHeader(name)response.headersSentresponse.removeHeader(name)
- Event:
response.reqresponse.sendDateresponse.setHeader(name, value)response.setTimeout(msecs[, callback])response.socketresponse.statusCoderesponse.statusMessageresponse.streamresponse.writableEndedresponse.write(chunk[, encoding][, callback])response.writeContinue()response.writeHead(statusCode[, statusMessage][, headers])
- Collecting HTTP/2 performance metrics
- Note on
:authorityandhost
- HTTPS
- Inspector
- Internationalization support
- Modules: CommonJS modules
- Enabling
- Accessing the main module
- Package manager tips
- The
.mjsextension - All together
- Caching
- Core modules
- Cycles
- File modules
- Folders as modules
- Loading from
node_modulesfolders - Loading from the global folders
- The module wrapper
- The module scope
- The
moduleobject - The
Moduleobject - Source map v3 support
- Modules: ECMAScript modules
- Modules:
moduleAPI - Modules: Packages
- Net
- IPC support
- Class:
net.BlockList - Class:
net.SocketAddress - Class:
net.Server - Class:
net.Socketnew net.Socket([options])- Event:
'close' - Event:
'connect' - Event:
'data' - Event:
'drain' - Event:
'end' - Event:
'error' - Event:
'lookup' - Event:
'ready' - Event:
'timeout' socket.address()socket.bufferSizesocket.bytesReadsocket.bytesWrittensocket.connect()socket.connectingsocket.destroy([error])socket.destroyedsocket.end([data[, encoding]][, callback])socket.localAddresssocket.localPortsocket.pause()socket.pendingsocket.ref()socket.remoteAddresssocket.remoteFamilysocket.remotePortsocket.resume()socket.setEncoding([encoding])socket.setKeepAlive([enable][, initialDelay])socket.setNoDelay([noDelay])socket.setTimeout(timeout[, callback])socket.timeoutsocket.unref()socket.write(data[, encoding][, callback])socket.readyState
net.connect()net.createConnection()net.createServer([options][, connectionListener])net.isIP(input)net.isIPv4(input)net.isIPv6(input)
- OS
os.EOLos.arch()os.constantsos.cpus()os.devNullos.endianness()os.freemem()os.getPriority([pid])os.homedir()os.hostname()os.loadavg()os.networkInterfaces()os.platform()os.release()os.setPriority([pid, ]priority)os.tmpdir()os.totalmem()os.type()os.uptime()os.userInfo([options])os.version()- OS constants
- Path
- Windows vs. POSIX
path.basename(path[, ext])path.delimiterpath.dirname(path)path.extname(path)path.format(pathObject)path.isAbsolute(path)path.join([...paths])path.normalize(path)path.parse(path)path.posixpath.relative(from, to)path.resolve([...paths])path.seppath.toNamespacedPath(path)path.win32
- Performance measurement APIs
perf_hooks.performanceperformance.clearMarks([name])performance.clearMeasures([name])performance.eventLoopUtilization([utilization1[, utilization2]])performance.getEntries()performance.getEntriesByName(name[, type])performance.getEntriesByType(type)performance.mark([name[, options]])performance.measure(name[, startMarkOrOptions[, endMark]])performance.nodeTimingperformance.now()performance.timeOriginperformance.timerify(fn[, options])performance.toJSON()
- Class:
PerformanceEntry - Class:
PerformanceNodeTiming - Class:
perf_hooks.PerformanceObserver - Class:
PerformanceObserverEntryList perf_hooks.createHistogram([options])perf_hooks.monitorEventLoopDelay([options])- Class:
Histogramhistogram.counthistogram.countBigInthistogram.exceedshistogram.exceedsBigInthistogram.maxhistogram.maxBigInthistogram.meanhistogram.minhistogram.minBigInthistogram.percentile(percentile)histogram.percentileBigInt(percentile)histogram.percentileshistogram.percentilesBigInthistogram.reset()histogram.stddev
- Class:
IntervalHistogram extends Histogram - Class:
RecordableHistogram extends Histogram - Examples
- Policies
- Process
- Process events
process.abort()process.allowedNodeEnvironmentFlagsprocess.archprocess.argvprocess.argv0process.channelprocess.chdir(directory)process.configprocess.connectedprocess.cpuUsage([previousValue])process.cwd()process.debugPortprocess.disconnect()process.dlopen(module, filename[, flags])process.emitWarning(warning[, options])process.emitWarning(warning[, type[, code]][, ctor])process.envprocess.execArgvprocess.execPathprocess.exit([code])process.exitCodeprocess.getActiveResourcesInfo()process.getegid()process.geteuid()process.getgid()process.getgroups()process.getuid()process.hasUncaughtExceptionCaptureCallback()process.hrtime([time])process.hrtime.bigint()process.initgroups(user, extraGroup)process.kill(pid[, signal])process.mainModuleprocess.memoryUsage()process.memoryUsage.rss()process.nextTick(callback[, ...args])process.noDeprecationprocess.pidprocess.platformprocess.ppidprocess.releaseprocess.reportprocess.resourceUsage()process.send(message[, sendHandle[, options]][, callback])process.setegid(id)process.seteuid(id)process.setgid(id)process.setgroups(groups)process.setuid(id)process.setSourceMapsEnabled(val)process.setUncaughtExceptionCaptureCallback(fn)process.stderrprocess.stdinprocess.stdoutprocess.throwDeprecationprocess.titleprocess.traceDeprecationprocess.umask()process.umask(mask)process.uptime()process.versionprocess.versions- Exit codes
- Punycode
- Query string
- Readline
- Class:
InterfaceConstructor- Event:
'close' - Event:
'line' - Event:
'history' - Event:
'pause' - Event:
'resume' - Event:
'SIGCONT' - Event:
'SIGINT' - Event:
'SIGTSTP' rl.close()rl.pause()rl.prompt([preserveCursor])rl.question(query[, options], callback)rl.resume()rl.setPrompt(prompt)rl.getPrompt()rl.write(data[, key])rl[Symbol.asyncIterator]()rl.linerl.cursorrl.getCursorPos()
- Event:
- Promises API
- Callback API
readline.emitKeypressEvents(stream[, interface])- Example: Tiny CLI
- Example: Read file stream line-by-Line
- TTY keybindings
- Class:
- REPL
- Diagnostic report
- Stream
- Organization of this document
- Types of streams
- API for stream consumers
- Writable streams
- Class:
stream.Writable- Event:
'close' - Event:
'drain' - Event:
'error' - Event:
'finish' - Event:
'pipe' - Event:
'unpipe' writable.cork()writable.destroy([error])writable.destroyedwritable.end([chunk[, encoding]][, callback])writable.setDefaultEncoding(encoding)writable.uncork()writable.writablewritable.writableEndedwritable.writableCorkedwritable.writableFinishedwritable.writableHighWaterMarkwritable.writableLengthwritable.writableNeedDrainwritable.writableObjectModewritable.write(chunk[, encoding][, callback])
- Event:
- Class:
- Readable streams
- Two reading modes
- Three states
- Choose one API style
- Class:
stream.Readable- Event:
'close' - Event:
'data' - Event:
'end' - Event:
'error' - Event:
'pause' - Event:
'readable' - Event:
'resume' readable.destroy([error])readable.destroyedreadable.isPaused()readable.pause()readable.pipe(destination[, options])readable.read([size])readable.readablereadable.readableAbortedreadable.readableDidReadreadable.readableEncodingreadable.readableEndedreadable.readableFlowingreadable.readableHighWaterMarkreadable.readableLengthreadable.readableObjectModereadable.resume()readable.setEncoding(encoding)readable.unpipe([destination])readable.unshift(chunk[, encoding])readable.wrap(stream)readable[Symbol.asyncIterator]()readable.iterator([options])readable.map(fn[, options])readable.filter(fn[, options])readable.forEach(fn[, options])readable.toArray([options])readable.some(fn[, options])readable.find(fn[, options])readable.every(fn[, options])readable.flatMap(fn[, options])readable.drop(limit[, options])readable.take(limit[, options])readable.asIndexedPairs([options])readable.reduce(fn[, initial[, options]])
- Event:
- Duplex and transform streams
stream.finished(stream[, options], callback)stream.pipeline(source[, ...transforms], destination, callback)stream.pipeline(streams, callback)stream.compose(...streams)stream.Readable.from(iterable[, options])stream.Readable.fromWeb(readableStream[, options])stream.Readable.isDisturbed(stream)stream.isErrored(stream)stream.isReadable(stream)stream.Readable.toWeb(streamReadable)stream.Writable.fromWeb(writableStream[, options])stream.Writable.toWeb(streamWritable)stream.Duplex.from(src)stream.Duplex.fromWeb(pair[, options])stream.Duplex.toWeb(streamDuplex)stream.addAbortSignal(signal, stream)
- Writable streams
- API for stream implementers
- Additional notes
- String decoder
- Timers
- TLS (SSL)
- Determining if crypto support is unavailable
- TLS/SSL concepts
- Modifying the default TLS cipher suite
- X509 certificate error codes
- Class:
tls.CryptoStream - Class:
tls.SecurePair - Class:
tls.Server- Event:
'connection' - Event:
'keylog' - Event:
'newSession' - Event:
'OCSPRequest' - Event:
'resumeSession' - Event:
'secureConnection' - Event:
'tlsClientError' server.addContext(hostname, context)server.address()server.close([callback])server.getTicketKeys()server.listen()server.setSecureContext(options)server.setTicketKeys(keys)
- Event:
- Class:
tls.TLSSocketnew tls.TLSSocket(socket[, options])- Event:
'keylog' - Event:
'OCSPResponse' - Event:
'secureConnect' - Event:
'session' tlsSocket.address()tlsSocket.authorizationErrortlsSocket.authorizedtlsSocket.disableRenegotiation()tlsSocket.enableTrace()tlsSocket.encryptedtlsSocket.exportKeyingMaterial(length, label[, context])tlsSocket.getCertificate()tlsSocket.getCipher()tlsSocket.getEphemeralKeyInfo()tlsSocket.getFinished()tlsSocket.getPeerCertificate([detailed])tlsSocket.getPeerFinished()tlsSocket.getPeerX509Certificate()tlsSocket.getProtocol()tlsSocket.getSession()tlsSocket.getSharedSigalgs()tlsSocket.getTLSTicket()tlsSocket.getX509Certificate()tlsSocket.isSessionReused()tlsSocket.localAddresstlsSocket.localPorttlsSocket.remoteAddresstlsSocket.remoteFamilytlsSocket.remotePorttlsSocket.renegotiate(options, callback)tlsSocket.setMaxSendFragment(size)
tls.checkServerIdentity(hostname, cert)tls.connect(options[, callback])tls.connect(path[, options][, callback])tls.connect(port[, host][, options][, callback])tls.createSecureContext([options])tls.createSecurePair([context][, isServer][, requestCert][, rejectUnauthorized][, options])tls.createServer([options][, secureConnectionListener])tls.getCiphers()tls.rootCertificatestls.DEFAULT_ECDH_CURVEtls.DEFAULT_MAX_VERSIONtls.DEFAULT_MIN_VERSION
- Trace events
- TTY
- Class:
tty.ReadStream - Class:
tty.WriteStream- Event:
'resize' writeStream.clearLine(dir[, callback])writeStream.clearScreenDown([callback])writeStream.columnswriteStream.cursorTo(x[, y][, callback])writeStream.getColorDepth([env])writeStream.getWindowSize()writeStream.hasColors([count][, env])writeStream.isTTYwriteStream.moveCursor(dx, dy[, callback])writeStream.rows
- Event:
tty.isatty(fd)
- Class:
- UDP/datagram sockets
- Class:
dgram.Socket- Event:
'close' - Event:
'connect' - Event:
'error' - Event:
'listening' - Event:
'message' socket.addMembership(multicastAddress[, multicastInterface])socket.addSourceSpecificMembership(sourceAddress, groupAddress[, multicastInterface])socket.address()socket.bind([port][, address][, callback])socket.bind(options[, callback])socket.close([callback])socket.connect(port[, address][, callback])socket.disconnect()socket.dropMembership(multicastAddress[, multicastInterface])socket.dropSourceSpecificMembership(sourceAddress, groupAddress[, multicastInterface])socket.getRecvBufferSize()socket.getSendBufferSize()socket.ref()socket.remoteAddress()socket.send(msg[, offset, length][, port][, address][, callback])socket.setBroadcast(flag)socket.setMulticastInterface(multicastInterface)socket.setMulticastLoopback(flag)socket.setMulticastTTL(ttl)socket.setRecvBufferSize(size)socket.setSendBufferSize(size)socket.setTTL(ttl)socket.unref()
- Event:
dgrammodule functions
- Class:
- URL
- URL strings and URL objects
- The WHATWG URL API
- Class:
URL - Class:
URLSearchParamsnew URLSearchParams()new URLSearchParams(string)new URLSearchParams(obj)new URLSearchParams(iterable)urlSearchParams.append(name, value)urlSearchParams.delete(name)urlSearchParams.entries()urlSearchParams.forEach(fn[, thisArg])urlSearchParams.get(name)urlSearchParams.getAll(name)urlSearchParams.has(name)urlSearchParams.keys()urlSearchParams.set(name, value)urlSearchParams.sort()urlSearchParams.toString()urlSearchParams.values()urlSearchParams[Symbol.iterator]()
url.domainToASCII(domain)url.domainToUnicode(domain)url.fileURLToPath(url)url.format(URL[, options])url.pathToFileURL(path)url.urlToHttpOptions(url)
- Class:
- Legacy URL API
- Percent-encoding in URLs
- Util
util.callbackify(original)util.debuglog(section[, callback])util.debug(section)util.deprecate(fn, msg[, code])util.format(format[, ...args])util.formatWithOptions(inspectOptions, format[, ...args])util.getSystemErrorName(err)util.getSystemErrorMap()util.inherits(constructor, superConstructor)util.inspect(object[, options])util.inspect(object[, showHidden[, depth[, colors]]])util.isDeepStrictEqual(val1, val2)util.promisify(original)util.stripVTControlCharacters(str)- Class:
util.TextDecoder - Class:
util.TextEncoder util.toUSVString(string)util.typesutil.types.isAnyArrayBuffer(value)util.types.isArrayBufferView(value)util.types.isArgumentsObject(value)util.types.isArrayBuffer(value)util.types.isAsyncFunction(value)util.types.isBigInt64Array(value)util.types.isBigUint64Array(value)util.types.isBooleanObject(value)util.types.isBoxedPrimitive(value)util.types.isCryptoKey(value)util.types.isDataView(value)util.types.isDate(value)util.types.isExternal(value)util.types.isFloat32Array(value)util.types.isFloat64Array(value)util.types.isGeneratorFunction(value)util.types.isGeneratorObject(value)util.types.isInt8Array(value)util.types.isInt16Array(value)util.types.isInt32Array(value)util.types.isKeyObject(value)util.types.isMap(value)util.types.isMapIterator(value)util.types.isModuleNamespaceObject(value)util.types.isNativeError(value)util.types.isNumberObject(value)util.types.isPromise(value)util.types.isProxy(value)util.types.isRegExp(value)util.types.isSet(value)util.types.isSetIterator(value)util.types.isSharedArrayBuffer(value)util.types.isStringObject(value)util.types.isSymbolObject(value)util.types.isTypedArray(value)util.types.isUint8Array(value)util.types.isUint8ClampedArray(value)util.types.isUint16Array(value)util.types.isUint32Array(value)util.types.isWeakMap(value)util.types.isWeakSet(value)util.types.isWebAssemblyCompiledModule(value)
- Deprecated APIs
util._extend(target, source)util.isArray(object)util.isBoolean(object)util.isBuffer(object)util.isDate(object)util.isError(object)util.isFunction(object)util.isNull(object)util.isNullOrUndefined(object)util.isNumber(object)util.isObject(object)util.isPrimitive(object)util.isRegExp(object)util.isString(object)util.isSymbol(object)util.isUndefined(object)util.log(string)
- V8
v8.cachedDataVersionTag()v8.getHeapCodeStatistics()v8.getHeapSnapshot()v8.getHeapSpaceStatistics()v8.getHeapStatistics()v8.setFlagsFromString(flags)v8.stopCoverage()v8.takeCoverage()v8.writeHeapSnapshot([filename])- Serialization API
v8.serialize(value)v8.deserialize(buffer)- Class:
v8.Serializernew Serializer()serializer.writeHeader()serializer.writeValue(value)serializer.releaseBuffer()serializer.transferArrayBuffer(id, arrayBuffer)serializer.writeUint32(value)serializer.writeUint64(hi, lo)serializer.writeDouble(value)serializer.writeRawBytes(buffer)serializer._writeHostObject(object)serializer._getDataCloneError(message)serializer._getSharedArrayBufferId(sharedArrayBuffer)serializer._setTreatArrayBufferViewsAsHostObjects(flag)
- Class:
v8.Deserializernew Deserializer(buffer)deserializer.readHeader()deserializer.readValue()deserializer.transferArrayBuffer(id, arrayBuffer)deserializer.getWireFormatVersion()deserializer.readUint32()deserializer.readUint64()deserializer.readDouble()deserializer.readRawBytes(length)deserializer._readHostObject()
- Class:
v8.DefaultSerializer - Class:
v8.DefaultDeserializer
- Promise hooks
- VM (executing JavaScript)
- Class:
vm.Script - Class:
vm.Module - Class:
vm.SourceTextModule - Class:
vm.SyntheticModule vm.compileFunction(code[, params[, options]])vm.createContext([contextObject[, options]])vm.isContext(object)vm.measureMemory([options])vm.runInContext(code, contextifiedObject[, options])vm.runInNewContext(code[, contextObject[, options]])vm.runInThisContext(code[, options])- Example: Running an HTTP server within a VM
- What does it mean to "contextify" an object?
- Timeout interactions with asynchronous tasks and Promises
- Class:
- WebAssembly System Interface (WASI)
- Web Crypto API
- Examples
- Algorithm matrix
- Class:
Crypto - Class:
CryptoKey - Class:
CryptoKeyPair - Class:
SubtleCryptosubtle.decrypt(algorithm, key, data)subtle.deriveBits(algorithm, baseKey, length)subtle.deriveKey(algorithm, baseKey, derivedKeyAlgorithm, extractable, keyUsages)subtle.digest(algorithm, data)subtle.encrypt(algorithm, key, data)subtle.exportKey(format, key)subtle.generateKey(algorithm, extractable, keyUsages)subtle.importKey(format, keyData, algorithm, extractable, keyUsages)subtle.sign(algorithm, key, data)subtle.unwrapKey(format, wrappedKey, unwrappingKey, unwrapAlgo, unwrappedKeyAlgo, extractable, keyUsages)subtle.verify(algorithm, key, signature, data)subtle.wrapKey(format, key, wrappingKey, wrapAlgo)
- Algorithm parameters
- Class:
AesCbcParams - Class:
AesCtrParams - Class:
AesGcmParams - Class:
AesImportParams - Class:
AesKeyGenParams - Class:
AesKwParams - Class:
EcdhKeyDeriveParams - Class:
EcdsaParams - Class:
EcKeyGenParams - Class:
EcKeyImportParams - Class:
HkdfParams - Class:
HmacImportParams - Class:
HmacKeyGenParams - Class:
HmacParams - Class:
Pbkdf2ImportParams - Class:
Pbkdf2Params - Class:
RsaHashedImportParams - Class:
RsaHashedKeyGenParams - Class:
RsaOaepParams - Class:
RsaPssParams - Class:
RsaSignParams
- Class:
- Node.js-specific extensions
- Web Streams API
- Overview
- API
- Class:
ReadableStreamnew ReadableStream([underlyingSource [, strategy]])readableStream.lockedreadableStream.cancel([reason])readableStream.getReader([options])readableStream.pipeThrough(transform[, options])readableStream.pipeTo(destination, options)readableStream.tee()readableStream.values([options])- Async Iteration
- Transferring with
postMessage()
- Class:
ReadableStreamDefaultReader - Class:
ReadableStreamBYOBReader - Class:
ReadableStreamDefaultController - Class:
ReadableByteStreamController - Class:
ReadableStreamBYOBRequest - Class:
WritableStream - Class:
WritableStreamDefaultWriternew WritableStreamDefaultWriter(stream)writableStreamDefaultWriter.abort([reason])writableStreamDefaultWriter.close()writableStreamDefaultWriter.closedwritableStreamDefaultWriter.desiredSizewritableStreamDefaultWriter.readywritableStreamDefaultWriter.releaseLock()writableStreamDefaultWriter.write([chunk])
- Class:
WritableStreamDefaultController - Class:
TransformStream - Class:
TransformStreamDefaultController - Class:
ByteLengthQueuingStrategy - Class:
CountQueuingStrategy - Class:
TextEncoderStream - Class:
TextDecoderStream - Class:
CompressionStream - Class:
DecompressionStream - Utility Consumers
- Class:
- Worker threads
worker.getEnvironmentData(key)worker.isMainThreadworker.markAsUntransferable(object)worker.moveMessagePortToContext(port, contextifiedSandbox)worker.parentPortworker.receiveMessageOnPort(port)worker.resourceLimitsworker.SHARE_ENVworker.setEnvironmentData(key[, value])worker.threadIdworker.workerData- Class:
BroadcastChannel extends EventTarget - Class:
MessageChannel - Class:
MessagePort - Class:
Workernew Worker(filename[, options])- Event:
'error' - Event:
'exit' - Event:
'message' - Event:
'messageerror' - Event:
'online' worker.getHeapSnapshot()worker.performanceworker.postMessage(value[, transferList])worker.ref()worker.resourceLimitsworker.stderrworker.stdinworker.stdoutworker.terminate()worker.threadIdworker.unref()
- Notes
- Zlib
- Threadpool usage and performance considerations
- Compressing HTTP requests and responses
- Memory usage tuning
- Flushing
- Constants
- Class:
Options - Class:
BrotliOptions - Class:
zlib.BrotliCompress - Class:
zlib.BrotliDecompress - Class:
zlib.Deflate - Class:
zlib.DeflateRaw - Class:
zlib.Gunzip - Class:
zlib.Gzip - Class:
zlib.Inflate - Class:
zlib.InflateRaw - Class:
zlib.Unzip - Class:
zlib.ZlibBase zlib.constantszlib.createBrotliCompress([options])zlib.createBrotliDecompress([options])zlib.createDeflate([options])zlib.createDeflateRaw([options])zlib.createGunzip([options])zlib.createGzip([options])zlib.createInflate([options])zlib.createInflateRaw([options])zlib.createUnzip([options])- Convenience methods
zlib.brotliCompress(buffer[, options], callback)zlib.brotliCompressSync(buffer[, options])zlib.brotliDecompress(buffer[, options], callback)zlib.brotliDecompressSync(buffer[, options])zlib.deflate(buffer[, options], callback)zlib.deflateSync(buffer[, options])zlib.deflateRaw(buffer[, options], callback)zlib.deflateRawSync(buffer[, options])zlib.gunzip(buffer[, options], callback)zlib.gunzipSync(buffer[, options])zlib.gzip(buffer[, options], callback)zlib.gzipSync(buffer[, options])zlib.inflate(buffer[, options], callback)zlib.inflateSync(buffer[, options])zlib.inflateRaw(buffer[, options], callback)zlib.inflateRawSync(buffer[, options])zlib.unzip(buffer[, options], callback)zlib.unzipSync(buffer[, options])
About this documentation#
Welcome to the official API reference documentation for Node.js!
Node.js is a JavaScript runtime built on the V8 JavaScript engine.
Contributing#
Report errors in this documentation in the issue tracker. See the contributing guide for directions on how to submit pull requests.
Stability index#
Throughout the documentation are indications of a section's stability. Some APIs are so proven and so relied upon that they are unlikely to ever change at all. Others are brand new and experimental, or known to be hazardous.
The stability indices are as follows:
Features are marked as legacy rather than being deprecated if their use does no harm, and they are widely relied upon within the npm ecosystem. Bugs found in legacy features are unlikely to be fixed.
Use caution when making use of Experimental features, particularly within modules. Users may not be aware that experimental features are being used. Bugs or behavior changes may surprise users when Experimental API modifications occur. To avoid surprises, use of an Experimental feature may need a command-line flag. Experimental features may also emit a warning.
Stability overview#
JSON output#
Every .html document has a corresponding .json document. This is for IDEs
and other utilities that consume the documentation.
System calls and man pages#
Node.js functions which wrap a system call will document that. The docs link to the corresponding man pages which describe how the system call works.
Most Unix system calls have Windows analogues. Still, behavior differences may be unavoidable.
Usage and example#
Usage#
node [options] [V8 options] [script.js | -e "script" | - ] [arguments]
Please see the Command-line options document for more information.
Example#
An example of a web server written with Node.js which responds with
'Hello, World!':
Commands in this document start with $ or > to replicate how they would
appear in a user's terminal. Do not include the $ and > characters. They are
there to show the start of each command.
Lines that don’t start with $ or > character show the output of the previous
command.
First, make sure to have downloaded and installed Node.js. See Installing Node.js via package manager for further install information.
Now, create an empty project folder called projects, then navigate into it.
Linux and Mac:
$ mkdir ~/projects
$ cd ~/projects
Windows CMD:
> mkdir %USERPROFILE%\projects
> cd %USERPROFILE%\projects
Windows PowerShell:
> mkdir $env:USERPROFILE\projects
> cd $env:USERPROFILE\projects
Next, create a new source file in the projects
folder and call it hello-world.js.
Open hello-world.js in any preferred text editor and
paste in the following content:
const http = require('http');
const hostname = '127.0.0.1';
const port = 3000;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello, World!\n');
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
Save the file, go back to the terminal window, and enter the following command:
$ node hello-world.js
Output like this should appear in the terminal:
Server running at http://127.0.0.1:3000/
Now, open any preferred web browser and visit http://127.0.0.1:3000.
If the browser displays the string Hello, World!, that indicates
the server is working.
Assert#
Source Code: lib/assert.js
The assert module provides a set of assertion functions for verifying
invariants.
Strict assertion mode#
In strict assertion mode, non-strict methods behave like their corresponding
strict methods. For example, assert.deepEqual() will behave like
assert.deepStrictEqual().
In strict assertion mode, error messages for objects display a diff. In legacy assertion mode, error messages for objects display the objects, often truncated.
To use strict assertion mode:
import { strict as assert } from 'assert';const assert = require('assert').strict;
import assert from 'assert/strict';const assert = require('assert/strict');
Example error diff:
import { strict as assert } from 'assert';
assert.deepEqual([[[1, 2, 3]], 4, 5], [[[1, 2, '3']], 4, 5]);
// AssertionError: Expected inputs to be strictly deep-equal:
// + actual - expected ... Lines skipped
//
// [
// [
// ...
// 2,
// + 3
// - '3'
// ],
// ...
// 5
// ]const assert = require('assert/strict');
assert.deepEqual([[[1, 2, 3]], 4, 5], [[[1, 2, '3']], 4, 5]);
// AssertionError: Expected inputs to be strictly deep-equal:
// + actual - expected ... Lines skipped
//
// [
// [
// ...
// 2,
// + 3
// - '3'
// ],
// ...
// 5
// ]
To deactivate the colors, use the NO_COLOR or NODE_DISABLE_COLORS
environment variables. This will also deactivate the colors in the REPL. For
more on color support in terminal environments, read the tty
getColorDepth() documentation.
Legacy assertion mode#
Legacy assertion mode uses the == operator in:
To use legacy assertion mode:
import assert from 'assert';const assert = require('assert');
Legacy assertion mode may have surprising results, especially when using
assert.deepEqual():
// WARNING: This does not throw an AssertionError in legacy assertion mode!
assert.deepEqual(/a/gi, new Date());
Class: assert.AssertionError[src]#
- Extends: <errors.Error>
Indicates the failure of an assertion. All errors thrown by the assert module
will be instances of the AssertionError class.
new assert.AssertionError(options)#
options<Object>message<string> If provided, the error message is set to this value.actual<any> Theactualproperty on the error instance.expected<any> Theexpectedproperty on the error instance.operator<string> Theoperatorproperty on the error instance.stackStartFn<Function> If provided, the generated stack trace omits frames before this function.
A subclass of Error that indicates the failure of an assertion.
All instances contain the built-in Error properties (message and name)
and:
actual<any> Set to theactualargument for methods such asassert.strictEqual().expected<any> Set to theexpectedvalue for methods such asassert.strictEqual().generatedMessage<boolean> Indicates if the message was auto-generated (true) or not.code<string> Value is alwaysERR_ASSERTIONto show that the error is an assertion error.operator<string> Set to the passed in operator value.
import assert from 'assert';
// Generate an AssertionError to compare the error message later:
const { message } = new assert.AssertionError({
actual: 1,
expected: 2,
operator: 'strictEqual'
});
// Verify error output:
try {
assert.strictEqual(1, 2);
} catch (err) {
assert(err instanceof assert.AssertionError);
assert.strictEqual(err.message, message);
assert.strictEqual(err.name, 'AssertionError');
assert.strictEqual(err.actual, 1);
assert.strictEqual(err.expected, 2);
assert.strictEqual(err.code, 'ERR_ASSERTION');
assert.strictEqual(err.operator, 'strictEqual');
assert.strictEqual(err.generatedMessage, true);
}const assert = require('assert');
// Generate an AssertionError to compare the error message later:
const { message } = new assert.AssertionError({
actual: 1,
expected: 2,
operator: 'strictEqual'
});
// Verify error output:
try {
assert.strictEqual(1, 2);
} catch (err) {
assert(err instanceof assert.AssertionError);
assert.strictEqual(err.message, message);
assert.strictEqual(err.name, 'AssertionError');
assert.strictEqual(err.actual, 1);
assert.strictEqual(err.expected, 2);
assert.strictEqual(err.code, 'ERR_ASSERTION');
assert.strictEqual(err.operator, 'strictEqual');
assert.strictEqual(err.generatedMessage, true);
}
Class: assert.CallTracker#
This feature is currently experimental and behavior might still change.
new assert.CallTracker()#
Creates a new CallTracker object which can be used to track if functions
were called a specific number of times. The tracker.verify() must be called
for the verification to take place. The usual pattern would be to call it in a
process.on('exit') handler.
import assert from 'assert';
import process from 'process';
const tracker = new assert.CallTracker();
function func() {}
// callsfunc() must be called exactly 1 time before tracker.verify().
const callsfunc = tracker.calls(func, 1);
callsfunc();
// Calls tracker.verify() and verifies if all tracker.calls() functions have
// been called exact times.
process.on('exit', () => {
tracker.verify();
});const assert = require('assert');
const tracker = new assert.CallTracker();
function func() {}
// callsfunc() must be called exactly 1 time before tracker.verify().
const callsfunc = tracker.calls(func, 1);
callsfunc();
// Calls tracker.verify() and verifies if all tracker.calls() functions have
// been called exact times.
process.on('exit', () => {
tracker.verify();
});
tracker.calls([fn][, exact])#
fn<Function> Default: A no-op function.exact<number> Default:1.- Returns: <Function> that wraps
fn.
The wrapper function is expected to be called exactly exact times. If the
function has not been called exactly exact times when
tracker.verify() is called, then tracker.verify() will throw an
error.
import assert from 'assert';
// Creates call tracker.
const tracker = new assert.CallTracker();
function func() {}
// Returns a function that wraps func() that must be called exact times
// before tracker.verify().
const callsfunc = tracker.calls(func);const assert = require('assert');
// Creates call tracker.
const tracker = new assert.CallTracker();
function func() {}
// Returns a function that wraps func() that must be called exact times
// before tracker.verify().
const callsfunc = tracker.calls(func);
tracker.report()#
- Returns: <Array> of objects containing information about the wrapper functions
returned by
tracker.calls(). - Object <Object>
The arrays contains information about the expected and actual number of calls of the functions that have not been called the expected number of times.
import assert from 'assert';
// Creates call tracker.
const tracker = new assert.CallTracker();
function func() {}
function foo() {}
// Returns a function that wraps func() that must be called exact times
// before tracker.verify().
const callsfunc = tracker.calls(func, 2);
// Returns an array containing information on callsfunc()
tracker.report();
// [
// {
// message: 'Expected the func function to be executed 2 time(s) but was
// executed 0 time(s).',
// actual: 0,
// expected: 2,
// operator: 'func',
// stack: stack trace
// }
// ]const assert = require('assert');
// Creates call tracker.
const tracker = new assert.CallTracker();
function func() {}
function foo() {}
// Returns a function that wraps func() that must be called exact times
// before tracker.verify().
const callsfunc = tracker.calls(func, 2);
// Returns an array containing information on callsfunc()
tracker.report();
// [
// {
// message: 'Expected the func function to be executed 2 time(s) but was
// executed 0 time(s).',
// actual: 0,
// expected: 2,
// operator: 'func',
// stack: stack trace
// }
// ]
tracker.verify()#
Iterates through the list of functions passed to
tracker.calls() and will throw an error for functions that
have not been called the expected number of times.
import assert from 'assert';
// Creates call tracker.
const tracker = new assert.CallTracker();
function func() {}
// Returns a function that wraps func() that must be called exact times
// before tracker.verify().
const callsfunc = tracker.calls(func, 2);
callsfunc();
// Will throw an error since callsfunc() was only called once.
tracker.verify();const assert = require('assert');
// Creates call tracker.
const tracker = new assert.CallTracker();
function func() {}
// Returns a function that wraps func() that must be called exact times
// before tracker.verify().
const callsfunc = tracker.calls(func, 2);
callsfunc();
// Will throw an error since callsfunc() was only called once.
tracker.verify();
assert(value[, message])#
An alias of assert.ok().
assert.deepEqual(actual, expected[, message])#
Strict assertion mode
An alias of assert.deepStrictEqual().
Legacy assertion mode
assert.deepStrictEqual() instead.Tests for deep equality between the actual and expected parameters. Consider
using assert.deepStrictEqual() instead. assert.deepEqual() can have
surprising results.
Deep equality means that the enumerable "own" properties of child objects are also recursively evaluated by the following rules.
Comparison details#
- Primitive values are compared with the
==operator, with the exception ofNaN. It is treated as being identical in case both sides areNaN. - Type tags of objects should be the same.
- Only enumerable "own" properties are considered.
Errornames and messages are always compared, even if these are not enumerable properties.- Object wrappers are compared both as objects and unwrapped values.
Objectproperties are compared unordered.Mapkeys andSetitems are compared unordered.- Recursion stops when both sides differ or both sides encounter a circular reference.
- Implementation does not test the
[[Prototype]]of objects. Symbolproperties are not compared.WeakMapandWeakSetcomparison does not rely on their values.
The following example does not throw an AssertionError because the
primitives are compared using the == operator.
import assert from 'assert';
// WARNING: This does not throw an AssertionError!
assert.deepEqual('+00000000', false);const assert = require('assert');
// WARNING: This does not throw an AssertionError!
assert.deepEqual('+00000000', false);
"Deep" equality means that the enumerable "own" properties of child objects are evaluated also:
import assert from 'assert';
const obj1 = {
a: {
b: 1
}
};
const obj2 = {
a: {
b: 2
}
};
const obj3 = {
a: {
b: 1
}
};
const obj4 = Object.create(obj1);
assert.deepEqual(obj1, obj1);
// OK
// Values of b are different:
assert.deepEqual(obj1, obj2);
// AssertionError: { a: { b: 1 } } deepEqual { a: { b: 2 } }
assert.deepEqual(obj1, obj3);
// OK
// Prototypes are ignored:
assert.deepEqual(obj1, obj4);
// AssertionError: { a: { b: 1 } } deepEqual {}const assert = require('assert');
const obj1 = {
a: {
b: 1
}
};
const obj2 = {
a: {
b: 2
}
};
const obj3 = {
a: {
b: 1
}
};
const obj4 = Object.create(obj1);
assert.deepEqual(obj1, obj1);
// OK
// Values of b are different:
assert.deepEqual(obj1, obj2);
// AssertionError: { a: { b: 1 } } deepEqual { a: { b: 2 } }
assert.deepEqual(obj1, obj3);
// OK
// Prototypes are ignored:
assert.deepEqual(obj1, obj4);
// AssertionError: { a: { b: 1 } } deepEqual {}
If the values are not equal, an AssertionError is thrown with a message
property set equal to the value of the message parameter. If the message
parameter is undefined, a default error message is assigned. If the message
parameter is an instance of an Error then it will be thrown instead of the
AssertionError.
assert.deepStrictEqual(actual, expected[, message])#
Tests for deep equality between the actual and expected parameters.
"Deep" equality means that the enumerable "own" properties of child objects
are recursively evaluated also by the following rules.
Comparison details#
- Primitive values are compared using
Object.is(). - Type tags of objects should be the same.
[[Prototype]]of objects are compared using the===operator.- Only enumerable "own" properties are considered.
Errornames and messages are always compared, even if these are not enumerable properties.- Enumerable own
Symbolproperties are compared as well. - Object wrappers are compared both as objects and unwrapped values.
Objectproperties are compared unordered.Mapkeys andSetitems are compared unordered.- Recursion stops when both sides differ or both sides encounter a circular reference.
WeakMapandWeakSetcomparison does not rely on their values. See below for further details.
import assert from 'assert/strict';
// This fails because 1 !== '1'.
assert.deepStrictEqual({ a: 1 }, { a: '1' });
// AssertionError: Expected inputs to be strictly deep-equal:
// + actual - expected
//
// {
// + a: 1
// - a: '1'
// }
// The following objects don't have own properties
const date = new Date();
const object = {};
const fakeDate = {};
Object.setPrototypeOf(fakeDate, Date.prototype);
// Different [[Prototype]]:
assert.deepStrictEqual(object, fakeDate);
// AssertionError: Expected inputs to be strictly deep-equal:
// + actual - expected
//
// + {}
// - Date {}
// Different type tags:
assert.deepStrictEqual(date, fakeDate);
// AssertionError: Expected inputs to be strictly deep-equal:
// + actual - expected
//
// + 2018-04-26T00:49:08.604Z
// - Date {}
assert.deepStrictEqual(NaN, NaN);
// OK because Object.is(NaN, NaN) is true.
// Different unwrapped numbers:
assert.deepStrictEqual(new Number(1), new Number(2));
// AssertionError: Expected inputs to be strictly deep-equal:
// + actual - expected
//
// + [Number: 1]
// - [Number: 2]
assert.deepStrictEqual(new String('foo'), Object('foo'));
// OK because the object and the string are identical when unwrapped.
assert.deepStrictEqual(-0, -0);
// OK
// Different zeros:
assert.deepStrictEqual(0, -0);
// AssertionError: Expected inputs to be strictly deep-equal:
// + actual - expected
//
// + 0
// - -0
const symbol1 = Symbol();
const symbol2 = Symbol();
assert.deepStrictEqual({ [symbol1]: 1 }, { [symbol1]: 1 });
// OK, because it is the same symbol on both objects.
assert.deepStrictEqual({ [symbol1]: 1 }, { [symbol2]: 1 });
// AssertionError [ERR_ASSERTION]: Inputs identical but not reference equal:
//
// {
// [Symbol()]: 1
// }
const weakMap1 = new WeakMap();
const weakMap2 = new WeakMap([[{}, {}]]);
const weakMap3 = new WeakMap();
weakMap3.unequal = true;
assert.deepStrictEqual(weakMap1, weakMap2);
// OK, because it is impossible to compare the entries
// Fails because weakMap3 has a property that weakMap1 does not contain:
assert.deepStrictEqual(weakMap1, weakMap3);
// AssertionError: Expected inputs to be strictly deep-equal:
// + actual - expected
//
// WeakMap {
// + [items unknown]
// - [items unknown],
// - unequal: true
// }const assert = require('assert/strict');
// This fails because 1 !== '1'.
assert.deepStrictEqual({ a: 1 }, { a: '1' });
// AssertionError: Expected inputs to be strictly deep-equal:
// + actual - expected
//
// {
// + a: 1
// - a: '1'
// }
// The following objects don't have own properties
const date = new Date();
const object = {};
const fakeDate = {};
Object.setPrototypeOf(fakeDate, Date.prototype);
// Different [[Prototype]]:
assert.deepStrictEqual(object, fakeDate);
// AssertionError: Expected inputs to be strictly deep-equal:
// + actual - expected
//
// + {}
// - Date {}
// Different type tags:
assert.deepStrictEqual(date, fakeDate);
// AssertionError: Expected inputs to be strictly deep-equal:
// + actual - expected
//
// + 2018-04-26T00:49:08.604Z
// - Date {}
assert.deepStrictEqual(NaN, NaN);
// OK because Object.is(NaN, NaN) is true.
// Different unwrapped numbers:
assert.deepStrictEqual(new Number(1), new Number(2));
// AssertionError: Expected inputs to be strictly deep-equal:
// + actual - expected
//
// + [Number: 1]
// - [Number: 2]
assert.deepStrictEqual(new String('foo'), Object('foo'));
// OK because the object and the string are identical when unwrapped.
assert.deepStrictEqual(-0, -0);
// OK
// Different zeros:
assert.deepStrictEqual(0, -0);
// AssertionError: Expected inputs to be strictly deep-equal:
// + actual - expected
//
// + 0
// - -0
const symbol1 = Symbol();
const symbol2 = Symbol();
assert.deepStrictEqual({ [symbol1]: 1 }, { [symbol1]: 1 });
// OK, because it is the same symbol on both objects.
assert.deepStrictEqual({ [symbol1]: 1 }, { [symbol2]: 1 });
// AssertionError [ERR_ASSERTION]: Inputs identical but not reference equal:
//
// {
// [Symbol()]: 1
// }
const weakMap1 = new WeakMap();
const weakMap2 = new WeakMap([[{}, {}]]);
const weakMap3 = new WeakMap();
weakMap3.unequal = true;
assert.deepStrictEqual(weakMap1, weakMap2);
// OK, because it is impossible to compare the entries
// Fails because weakMap3 has a property that weakMap1 does not contain:
assert.deepStrictEqual(weakMap1, weakMap3);
// AssertionError: Expected inputs to be strictly deep-equal:
// + actual - expected
//
// WeakMap {
// + [items unknown]
// - [items unknown],
// - unequal: true
// }
If the values are not equal, an AssertionError is thrown with a message
property set equal to the value of the message parameter. If the message
parameter is undefined, a default error message is assigned. If the message
parameter is an instance of an Error then it will be thrown instead of the
AssertionError.
assert.doesNotMatch(string, regexp[, message])#
Expects the string input not to match the regular expression.
import assert from 'assert/strict';
assert.doesNotMatch('I will fail', /fail/);
// AssertionError [ERR_ASSERTION]: The input was expected to not match the ...
assert.doesNotMatch(123, /pass/);
// AssertionError [ERR_ASSERTION]: The "string" argument must be of type string.
assert.doesNotMatch('I will pass', /different/);
// OKconst assert = require('assert/strict');
assert.doesNotMatch('I will fail', /fail/);
// AssertionError [ERR_ASSERTION]: The input was expected to not match the ...
assert.doesNotMatch(123, /pass/);
// AssertionError [ERR_ASSERTION]: The "string" argument must be of type string.
assert.doesNotMatch('I will pass', /different/);
// OK
If the values do match, or if the string argument is of another type than
string, an AssertionError is thrown with a message property set equal
to the value of the message parameter. If the message parameter is
undefined, a default error message is assigned. If the message parameter is an
instance of an Error then it will be thrown instead of the
AssertionError.
assert.doesNotReject(asyncFn[, error][, message])#
asyncFn<Function> | <Promise>error<RegExp> | <Function>message<string>
Awaits the asyncFn promise or, if asyncFn is a function, immediately
calls the function and awaits the returned promise to complete. It will then
check that the promise is not rejected.
If asyncFn is a function and it throws an error synchronously,
assert.doesNotReject() will return a rejected Promise with that error. If
the function does not return a promise, assert.doesNotReject() will return a
rejected Promise with an ERR_INVALID_RETURN_VALUE error. In both cases
the error handler is skipped.
Using assert.doesNotReject() is actually not useful because there is little
benefit in catching a rejection and then rejecting it again. Instead, consider
adding a comment next to the specific code path that should not reject and keep
error messages as expressive as possible.
If specified, error can be a Class, RegExp or a validation
function. See assert.throws() for more details.
Besides the async nature to await the completion behaves identically to
assert.doesNotThrow().
import assert from 'assert/strict';
await assert.doesNotReject(
async () => {
throw new TypeError('Wrong value');
},
SyntaxError
);const assert = require('assert/strict');
(async () => {
await assert.doesNotReject(
async () => {
throw new TypeError('Wrong value');
},
SyntaxError
);
})();
import assert from 'assert/strict';
assert.doesNotReject(Promise.reject(new TypeError('Wrong value')))
.then(() => {
// ...
});const assert = require('assert/strict');
assert.doesNotReject(Promise.reject(new TypeError('Wrong value')))
.then(() => {
// ...
});
assert.doesNotThrow(fn[, error][, message])#
fn<Function>error<RegExp> | <Function>message<string>
Asserts that the function fn does not throw an error.
Using assert.doesNotThrow() is actually not useful because there
is no benefit in catching an error and then rethrowing it. Instead, consider
adding a comment next to the specific code path that should not throw and keep
error messages as expressive as possible.
When assert.doesNotThrow() is called, it will immediately call the fn
function.
If an error is thrown and it is the same type as that specified by the error
parameter, then an AssertionError is thrown. If the error is of a
different type, or if the error parameter is undefined, the error is
propagated back to the caller.
If specified, error can be a Class, RegExp or a validation
function. See assert.throws() for more details.
The following, for instance, will throw the TypeError because there is no
matching error type in the assertion:
import assert from 'assert/strict';
assert.doesNotThrow(
() => {
throw new TypeError('Wrong value');
},
SyntaxError
);const assert = require('assert/strict');
assert.doesNotThrow(
() => {
throw new TypeError('Wrong value');
},
SyntaxError
);
However, the following will result in an AssertionError with the message
'Got unwanted exception...':
import assert from 'assert/strict';
assert.doesNotThrow(
() => {
throw new TypeError('Wrong value');
},
TypeError
);const assert = require('assert/strict');
assert.doesNotThrow(
() => {
throw new TypeError('Wrong value');
},
TypeError
);
If an AssertionError is thrown and a value is provided for the message
parameter, the value of message will be appended to the AssertionError
message:
import assert from 'assert/strict';
assert.doesNotThrow(
() => {
throw new TypeError('Wrong value');
},
/Wrong value/,
'Whoops'
);
// Throws: AssertionError: Got unwanted exception: Whoopsconst assert = require('assert/strict');
assert.doesNotThrow(
() => {
throw new TypeError('Wrong value');
},
/Wrong value/,
'Whoops'
);
// Throws: AssertionError: Got unwanted exception: Whoops
assert.equal(actual, expected[, message])#
Strict assertion mode
An alias of assert.strictEqual().
Legacy assertion mode
assert.strictEqual() instead.Tests shallow, coercive equality between the actual and expected parameters
using the == operator. NaN is specially handled
and treated as being identical if both sides are NaN.
import assert from 'assert';
assert.equal(1, 1);
// OK, 1 == 1
assert.equal(1, '1');
// OK, 1 == '1'
assert.equal(NaN, NaN);
// OK
assert.equal(1, 2);
// AssertionError: 1 == 2
assert.equal({ a: { b: 1 } }, { a: { b: 1 } });
// AssertionError: { a: { b: 1 } } == { a: { b: 1 } }const assert = require('assert');
assert.equal(1, 1);
// OK, 1 == 1
assert.equal(1, '1');
// OK, 1 == '1'
assert.equal(NaN, NaN);
// OK
assert.equal(1, 2);
// AssertionError: 1 == 2
assert.equal({ a: { b: 1 } }, { a: { b: 1 } });
// AssertionError: { a: { b: 1 } } == { a: { b: 1 } }
If the values are not equal, an AssertionError is thrown with a message
property set equal to the value of the message parameter. If the message
parameter is undefined, a default error message is assigned. If the message
parameter is an instance of an Error then it will be thrown instead of the
AssertionError.
assert.fail([message])#
Throws an AssertionError with the provided error message or a default
error message. If the message parameter is an instance of an Error then
it will be thrown instead of the AssertionError.
import assert from 'assert/strict';
assert.fail();
// AssertionError [ERR_ASSERTION]: Failed
assert.fail('boom');
// AssertionError [ERR_ASSERTION]: boom
assert.fail(new TypeError('need array'));
// TypeError: need arrayconst assert = require('assert/strict');
assert.fail();
// AssertionError [ERR_ASSERTION]: Failed
assert.fail('boom');
// AssertionError [ERR_ASSERTION]: boom
assert.fail(new TypeError('need array'));
// TypeError: need array
Using assert.fail() with more than two arguments is possible but deprecated.
See below for further details.
assert.fail(actual, expected[, message[, operator[, stackStartFn]]])#
assert.fail([message]) or other assert
functions instead.actual<any>expected<any>message<string> | <Error>operator<string> Default:'!='stackStartFn<Function> Default:assert.fail
If message is falsy, the error message is set as the values of actual and
expected separated by the provided operator. If just the two actual and
expected arguments are provided, operator will default to '!='. If
message is provided as third argument it will be used as the error message and
the other arguments will be stored as properties on the thrown object. If
stackStartFn is provided, all stack frames above that function will be
removed from stacktrace (see Error.captureStackTrace). If no arguments are
given, the default message Failed will be used.
import assert from 'assert/strict';
assert.fail('a', 'b');
// AssertionError [ERR_ASSERTION]: 'a' != 'b'
assert.fail(1, 2, undefined, '>');
// AssertionError [ERR_ASSERTION]: 1 > 2
assert.fail(1, 2, 'fail');
// AssertionError [ERR_ASSERTION]: fail
assert.fail(1, 2, 'whoops', '>');
// AssertionError [ERR_ASSERTION]: whoops
assert.fail(1, 2, new TypeError('need array'));
// TypeError: need arrayconst assert = require('assert/strict');
assert.fail('a', 'b');
// AssertionError [ERR_ASSERTION]: 'a' != 'b'
assert.fail(1, 2, undefined, '>');
// AssertionError [ERR_ASSERTION]: 1 > 2
assert.fail(1, 2, 'fail');
// AssertionError [ERR_ASSERTION]: fail
assert.fail(1, 2, 'whoops', '>');
// AssertionError [ERR_ASSERTION]: whoops
assert.fail(1, 2, new TypeError('need array'));
// TypeError: need array
In the last three cases actual, expected, and operator have no
influence on the error message.
Example use of stackStartFn for truncating the exception's stacktrace:
import assert from 'assert/strict';
function suppressFrame() {
assert.fail('a', 'b', undefined, '!==', suppressFrame);
}
suppressFrame();
// AssertionError [ERR_ASSERTION]: 'a' !== 'b'
// at repl:1:1
// at ContextifyScript.Script.runInThisContext (vm.js:44:33)
// ...const assert = require('assert/strict');
function suppressFrame() {
assert.fail('a', 'b', undefined, '!==', suppressFrame);
}
suppressFrame();
// AssertionError [ERR_ASSERTION]: 'a' !== 'b'
// at repl:1:1
// at ContextifyScript.Script.runInThisContext (vm.js:44:33)
// ...
assert.ifError(value)#
value<any>
Throws value if value is not undefined or null. This is useful when
testing the error argument in callbacks. The stack trace contains all frames
from the error passed to ifError() including the potential new frames for
ifError() itself.
import assert from 'assert/strict';
assert.ifError(null);
// OK
assert.ifError(0);
// AssertionError [ERR_ASSERTION]: ifError got unwanted exception: 0
assert.ifError('error');
// AssertionError [ERR_ASSERTION]: ifError got unwanted exception: 'error'
assert.ifError(new Error());
// AssertionError [ERR_ASSERTION]: ifError got unwanted exception: Error
// Create some random error frames.
let err;
(function errorFrame() {
err = new Error('test error');
})();
(function ifErrorFrame() {
assert.ifError(err);
})();
// AssertionError [ERR_ASSERTION]: ifError got unwanted exception: test error
// at ifErrorFrame
// at errorFrameconst assert = require('assert/strict');
assert.ifError(null);
// OK
assert.ifError(0);
// AssertionError [ERR_ASSERTION]: ifError got unwanted exception: 0
assert.ifError('error');
// AssertionError [ERR_ASSERTION]: ifError got unwanted exception: 'error'
assert.ifError(new Error());
// AssertionError [ERR_ASSERTION]: ifError got unwanted exception: Error
// Create some random error frames.
let err;
(function errorFrame() {
err = new Error('test error');
})();
(function ifErrorFrame() {
assert.ifError(err);
})();
// AssertionError [ERR_ASSERTION]: ifError got unwanted exception: test error
// at ifErrorFrame
// at errorFrame
assert.match(string, regexp[, message])#
Expects the string input to match the regular expression.
import assert from 'assert/strict';
assert.match('I will fail', /pass/);
// AssertionError [ERR_ASSERTION]: The input did not match the regular ...
assert.match(123, /pass/);
// AssertionError [ERR_ASSERTION]: The "string" argument must be of type string.
assert.match('I will pass', /pass/);
// OKconst assert = require('assert/strict');
assert.match('I will fail', /pass/);
// AssertionError [ERR_ASSERTION]: The input did not match the regular ...
assert.match(123, /pass/);
// AssertionError [ERR_ASSERTION]: The "string" argument must be of type string.
assert.match('I will pass', /pass/);
// OK
If the values do not match, or if the string argument is of another type than
string, an AssertionError is thrown with a message property set equal
to the value of the message parameter. If the message parameter is
undefined, a default error message is assigned. If the message parameter is an
instance of an Error then it will be thrown instead of the
AssertionError.
assert.notDeepEqual(actual, expected[, message])#
Strict assertion mode
An alias of assert.notDeepStrictEqual().
Legacy assertion mode
assert.notDeepStrictEqual() instead.Tests for any deep inequality. Opposite of assert.deepEqual().
import assert from 'assert';
const obj1 = {
a: {
b: 1
}
};
const obj2 = {
a: {
b: 2
}
};
const obj3 = {
a: {
b: 1
}
};
const obj4 = Object.create(obj1);
assert.notDeepEqual(obj1, obj1);
// AssertionError: { a: { b: 1 } } notDeepEqual { a: { b: 1 } }
assert.notDeepEqual(obj1, obj2);
// OK
assert.notDeepEqual(obj1, obj3);
// AssertionError: { a: { b: 1 } } notDeepEqual { a: { b: 1 } }
assert.notDeepEqual(obj1, obj4);
// OKconst assert = require('assert');
const obj1 = {
a: {
b: 1
}
};
const obj2 = {
a: {
b: 2
}
};
const obj3 = {
a: {
b: 1
}
};
const obj4 = Object.create(obj1);
assert.notDeepEqual(obj1, obj1);
// AssertionError: { a: { b: 1 } } notDeepEqual { a: { b: 1 } }
assert.notDeepEqual(obj1, obj2);
// OK
assert.notDeepEqual(obj1, obj3);
// AssertionError: { a: { b: 1 } } notDeepEqual { a: { b: 1 } }
assert.notDeepEqual(obj1, obj4);
// OK
If the values are deeply equal, an AssertionError is thrown with a
message property set equal to the value of the message parameter. If the
message parameter is undefined, a default error message is assigned. If the
message parameter is an instance of an Error then it will be thrown
instead of the AssertionError.
assert.notDeepStrictEqual(actual, expected[, message])#
Tests for deep strict inequality. Opposite of assert.deepStrictEqual().
import assert from 'assert/strict';
assert.notDeepStrictEqual({ a: 1 }, { a: '1' });
// OKconst assert = require('assert/strict');
assert.notDeepStrictEqual({ a: 1 }, { a: '1' });
// OK
If the values are deeply and strictly equal, an AssertionError is thrown
with a message property set equal to the value of the message parameter. If
the message parameter is undefined, a default error message is assigned. If
the message parameter is an instance of an Error then it will be thrown
instead of the AssertionError.
assert.notEqual(actual, expected[, message])#
Strict assertion mode
An alias of assert.notStrictEqual().
Legacy assertion mode
assert.notStrictEqual() instead.Tests shallow, coercive inequality with the != operator. NaN is
specially handled and treated as being identical if both sides are NaN.
import assert from 'assert';
assert.notEqual(1, 2);
// OK
assert.notEqual(1, 1);
// AssertionError: 1 != 1
assert.notEqual(1, '1');
// AssertionError: 1 != '1'const assert = require('assert');
assert.notEqual(1, 2);
// OK
assert.notEqual(1, 1);
// AssertionError: 1 != 1
assert.notEqual(1, '1');
// AssertionError: 1 != '1'
If the values are equal, an AssertionError is thrown with a message
property set equal to the value of the message parameter. If the message
parameter is undefined, a default error message is assigned. If the message
parameter is an instance of an Error then it will be thrown instead of the
AssertionError.
assert.notStrictEqual(actual, expected[, message])#
Tests strict inequality between the actual and expected parameters as
determined by Object.is().
import assert from 'assert/strict';
assert.notStrictEqual(1, 2);
// OK
assert.notStrictEqual(1, 1);
// AssertionError [ERR_ASSERTION]: Expected "actual" to be strictly unequal to:
//
// 1
assert.notStrictEqual(1, '1');
// OKconst assert = require('assert/strict');
assert.notStrictEqual(1, 2);
// OK
assert.notStrictEqual(1, 1);
// AssertionError [ERR_ASSERTION]: Expected "actual" to be strictly unequal to:
//
// 1
assert.notStrictEqual(1, '1');
// OK
If the values are strictly equal, an AssertionError is thrown with a
message property set equal to the value of the message parameter. If the
message parameter is undefined, a default error message is assigned. If the
message parameter is an instance of an Error then it will be thrown
instead of the AssertionError.
assert.ok(value[, message])#
Tests if value is truthy. It is equivalent to
assert.equal(!!value, true, message).
If value is not truthy, an AssertionError is thrown with a message
property set equal to the value of the message parameter. If the message
parameter is undefined, a default error message is assigned. If the message
parameter is an instance of an Error then it will be thrown instead of the
AssertionError.
If no arguments are passed in at all message will be set to the string:
'No value argument passed to `assert.ok()`'.
Be aware that in the repl the error message will be different to the one
thrown in a file! See below for further details.
import assert from 'assert/strict';
assert.ok(true);
// OK
assert.ok(1);
// OK
assert.ok();
// AssertionError: No value argument passed to `assert.ok()`
assert.ok(false, 'it\'s false');
// AssertionError: it's false
// In the repl:
assert.ok(typeof 123 === 'string');
// AssertionError: false == true
// In a file (e.g. test.js):
assert.ok(typeof 123 === 'string');
// AssertionError: The expression evaluated to a falsy value:
//
// assert.ok(typeof 123 === 'string')
assert.ok(false);
// AssertionError: The expression evaluated to a falsy value:
//
// assert.ok(false)
assert.ok(0);
// AssertionError: The expression evaluated to a falsy value:
//
// assert.ok(0)const assert = require('assert/strict');
assert.ok(true);
// OK
assert.ok(1);
// OK
assert.ok();
// AssertionError: No value argument passed to `assert.ok()`
assert.ok(false, 'it\'s false');
// AssertionError: it's false
// In the repl:
assert.ok(typeof 123 === 'string');
// AssertionError: false == true
// In a file (e.g. test.js):
assert.ok(typeof 123 === 'string');
// AssertionError: The expression evaluated to a falsy value:
//
// assert.ok(typeof 123 === 'string')
assert.ok(false);
// AssertionError: The expression evaluated to a falsy value:
//
// assert.ok(false)
assert.ok(0);
// AssertionError: The expression evaluated to a falsy value:
//
// assert.ok(0)
import assert from 'assert/strict';
// Using `assert()` works the same:
assert(0);
// AssertionError: The expression evaluated to a falsy value:
//
// assert(0)const assert = require('assert');
// Using `assert()` works the same:
assert(0);
// AssertionError: The expression evaluated to a falsy value:
//
// assert(0)
assert.rejects(asyncFn[, error][, message])#
asyncFn<Function> | <Promise>error<RegExp> | <Function> | <Object> | <Error>message<string>
Awaits the asyncFn promise or, if asyncFn is a function, immediately
calls the function and awaits the returned promise to complete. It will then
check that the promise is rejected.
If asyncFn is a function and it throws an error synchronously,
assert.rejects() will return a rejected Promise with that error. If the
function does not return a promise, assert.rejects() will return a rejected
Promise with an ERR_INVALID_RETURN_VALUE error. In both cases the error
handler is skipped.
Besides the async nature to await the completion behaves identically to
assert.throws().
If specified, error can be a Class, RegExp, a validation function,
an object where each property will be tested for, or an instance of error where
each property will be tested for including the non-enumerable message and
name properties.
If specified, message will be the message provided by the AssertionError
if the asyncFn fails to reject.
import assert from 'assert/strict';
await assert.rejects(
async () => {
throw new TypeError('Wrong value');
},
{
name: 'TypeError',
message: 'Wrong value'
}
);const assert = require('assert/strict');
(async () => {
await assert.rejects(
async () => {
throw new TypeError('Wrong value');
},
{
name: 'TypeError',
message: 'Wrong value'
}
);
})();
import assert from 'assert/strict';
await assert.rejects(
async () => {
throw new TypeError('Wrong value');
},
(err) => {
assert.strictEqual(err.name, 'TypeError');
assert.strictEqual(err.message, 'Wrong value');
return true;
}
);const assert = require('assert/strict');
(async () => {
await assert.rejects(
async () => {
throw new TypeError('Wrong value');
},
(err) => {
assert.strictEqual(err.name, 'TypeError');
assert.strictEqual(err.message, 'Wrong value');
return true;
}
);
})();
import assert from 'assert/strict';
assert.rejects(
Promise.reject(new Error('Wrong value')),
Error
).then(() => {
// ...
});const assert = require('assert/strict');
assert.rejects(
Promise.reject(new Error('Wrong value')),
Error
).then(() => {
// ...
});
error cannot be a string. If a string is provided as the second
argument, then error is assumed to be omitted and the string will be used for
message instead. This can lead to easy-to-miss mistakes. Please read the
example in assert.throws() carefully if using a string as the second
argument gets considered.
assert.strictEqual(actual, expected[, message])#
Tests strict equality between the actual and expected parameters as
determined by Object.is().
import assert from 'assert/strict';
assert.strictEqual(1, 2);
// AssertionError [ERR_ASSERTION]: Expected inputs to be strictly equal:
//
// 1 !== 2
assert.strictEqual(1, 1);
// OK
assert.strictEqual('Hello foobar', 'Hello World!');
// AssertionError [ERR_ASSERTION]: Expected inputs to be strictly equal:
// + actual - expected
//
// + 'Hello foobar'
// - 'Hello World!'
// ^
const apples = 1;
const oranges = 2;
assert.strictEqual(apples, oranges, `apples ${apples} !== oranges ${oranges}`);
// AssertionError [ERR_ASSERTION]: apples 1 !== oranges 2
assert.strictEqual(1, '1', new TypeError('Inputs are not identical'));
// TypeError: Inputs are not identicalconst assert = require('assert/strict');
assert.strictEqual(1, 2);
// AssertionError [ERR_ASSERTION]: Expected inputs to be strictly equal:
//
// 1 !== 2
assert.strictEqual(1, 1);
// OK
assert.strictEqual('Hello foobar', 'Hello World!');
// AssertionError [ERR_ASSERTION]: Expected inputs to be strictly equal:
// + actual - expected
//
// + 'Hello foobar'
// - 'Hello World!'
// ^
const apples = 1;
const oranges = 2;
assert.strictEqual(apples, oranges, `apples ${apples} !== oranges ${oranges}`);
// AssertionError [ERR_ASSERTION]: apples 1 !== oranges 2
assert.strictEqual(1, '1', new TypeError('Inputs are not identical'));
// TypeError: Inputs are not identical
If the values are not strictly equal, an AssertionError is thrown with a
message property set equal to the value of the message parameter. If the
message parameter is undefined, a default error message is assigned. If the
message parameter is an instance of an Error then it will be thrown
instead of the AssertionError.
assert.throws(fn[, error][, message])#
fn<Function>error<RegExp> | <Function> | <Object> | <Error>message<string>
Expects the function fn to throw an error.
If specified, error can be a Class, RegExp, a validation function,
a validation object where each property will be tested for strict deep equality,
or an instance of error where each property will be tested for strict deep
equality including the non-enumerable message and name properties. When
using an object, it is also possible to use a regular expression, when
validating against a string property. See below for examples.
If specified, message will be appended to the message provided by the
AssertionError if the fn call fails to throw or in case the error validation
fails.
Custom validation object/error instance:
import assert from 'assert/strict';
const err = new TypeError('Wrong value');
err.code = 404;
err.foo = 'bar';
err.info = {
nested: true,
baz: 'text'
};
err.reg = /abc/i;
assert.throws(
() => {
throw err;
},
{
name: 'TypeError',
message: 'Wrong value',
info: {
nested: true,
baz: 'text'
}
// Only properties on the validation object will be tested for.
// Using nested objects requires all properties to be present. Otherwise
// the validation is going to fail.
}
);
// Using regular expressions to validate error properties:
throws(
() => {
throw err;
},
{
// The `name` and `message` properties are strings and using regular
// expressions on those will match against the string. If they fail, an
// error is thrown.
name: /^TypeError$/,
message: /Wrong/,
foo: 'bar',
info: {
nested: true,
// It is not possible to use regular expressions for nested properties!
baz: 'text'
},
// The `reg` property contains a regular expression and only if the
// validation object contains an identical regular expression, it is going
// to pass.
reg: /abc/i
}
);
// Fails due to the different `message` and `name` properties:
throws(
() => {
const otherErr = new Error('Not found');
// Copy all enumerable properties from `err` to `otherErr`.
for (const [key, value] of Object.entries(err)) {
otherErr[key] = value;
}
throw otherErr;
},
// The error's `message` and `name` properties will also be checked when using
// an error as validation object.
err
);const assert = require('assert/strict');
const err = new TypeError('Wrong value');
err.code = 404;
err.foo = 'bar';
err.info = {
nested: true,
baz: 'text'
};
err.reg = /abc/i;
assert.throws(
() => {
throw err;
},
{
name: 'TypeError',
message: 'Wrong value',
info: {
nested: true,
baz: 'text'
}
// Only properties on the validation object will be tested for.
// Using nested objects requires all properties to be present. Otherwise
// the validation is going to fail.
}
);
// Using regular expressions to validate error properties:
throws(
() => {
throw err;
},
{
// The `name` and `message` properties are strings and using regular
// expressions on those will match against the string. If they fail, an
// error is thrown.
name: /^TypeError$/,
message: /Wrong/,
foo: 'bar',
info: {
nested: true,
// It is not possible to use regular expressions for nested properties!
baz: 'text'
},
// The `reg` property contains a regular expression and only if the
// validation object contains an identical regular expression, it is going
// to pass.
reg: /abc/i
}
);
// Fails due to the different `message` and `name` properties:
throws(
() => {
const otherErr = new Error('Not found');
// Copy all enumerable properties from `err` to `otherErr`.
for (const [key, value] of Object.entries(err)) {
otherErr[key] = value;
}
throw otherErr;
},
// The error's `message` and `name` properties will also be checked when using
// an error as validation object.
err
);
Validate instanceof using constructor:
import assert from 'assert/strict';
assert.throws(
() => {
throw new Error('Wrong value');
},
Error
);const assert = require('assert/strict');
assert.throws(
() => {
throw new Error('Wrong value');
},
Error
);
Validate error message using RegExp:
Using a regular expression runs .toString on the error object, and will
therefore also include the error name.
import assert from 'assert/strict';
assert.throws(
() => {
throw new Error('Wrong value');
},
/^Error: Wrong value$/
);const assert = require('assert/strict');
assert.throws(
() => {
throw new Error('Wrong value');
},
/^Error: Wrong value$/
);
Custom error validation:
The function must return true to indicate all internal validations passed.
It will otherwise fail with an AssertionError.
import assert from 'assert/strict';
assert.throws(
() => {
throw new Error('Wrong value');
},
(err) => {
assert(err instanceof Error);
assert(/value/.test(err));
// Avoid returning anything from validation functions besides `true`.
// Otherwise, it's not clear what part of the validation failed. Instead,
// throw an error about the specific validation that failed (as done in this
// example) and add as much helpful debugging information to that error as
// possible.
return true;
},
'unexpected error'
);const assert = require('assert/strict');
assert.throws(
() => {
throw new Error('Wrong value');
},
(err) => {
assert(err instanceof Error);
assert(/value/.test(err));
// Avoid returning anything from validation functions besides `true`.
// Otherwise, it's not clear what part of the validation failed. Instead,
// throw an error about the specific validation that failed (as done in this
// example) and add as much helpful debugging information to that error as
// possible.
return true;
},
'unexpected error'
);
error cannot be a string. If a string is provided as the second
argument, then error is assumed to be omitted and the string will be used for
message instead. This can lead to easy-to-miss mistakes. Using the same
message as the thrown error message is going to result in an
ERR_AMBIGUOUS_ARGUMENT error. Please read the example below carefully if using
a string as the second argument gets considered:
import assert from 'assert/strict';
function throwingFirst() {
throw new Error('First');
}
function throwingSecond() {
throw new Error('Second');
}
function notThrowing() {}
// The second argument is a string and the input function threw an Error.
// The first case will not throw as it does not match for the error message
// thrown by the input function!
assert.throws(throwingFirst, 'Second');
// In the next example the message has no benefit over the message from the
// error and since it is not clear if the user intended to actually match
// against the error message, Node.js throws an `ERR_AMBIGUOUS_ARGUMENT` error.
assert.throws(throwingSecond, 'Second');
// TypeError [ERR_AMBIGUOUS_ARGUMENT]
// The string is only used (as message) in case the function does not throw:
assert.throws(notThrowing, 'Second');
// AssertionError [ERR_ASSERTION]: Missing expected exception: Second
// If it was intended to match for the error message do this instead:
// It does not throw because the error messages match.
assert.throws(throwingSecond, /Second$/);
// If the error message does not match, an AssertionError is thrown.
assert.throws(throwingFirst, /Second$/);
// AssertionError [ERR_ASSERTION]const assert = require('assert/strict');
function throwingFirst() {
throw new Error('First');
}
function throwingSecond() {
throw new Error('Second');
}
function notThrowing() {}
// The second argument is a string and the input function threw an Error.
// The first case will not throw as it does not match for the error message
// thrown by the input function!
assert.throws(throwingFirst, 'Second');
// In the next example the message has no benefit over the message from the
// error and since it is not clear if the user intended to actually match
// against the error message, Node.js throws an `ERR_AMBIGUOUS_ARGUMENT` error.
assert.throws(throwingSecond, 'Second');
// TypeError [ERR_AMBIGUOUS_ARGUMENT]
// The string is only used (as message) in case the function does not throw:
assert.throws(notThrowing, 'Second');
// AssertionError [ERR_ASSERTION]: Missing expected exception: Second
// If it was intended to match for the error message do this instead:
// It does not throw because the error messages match.
assert.throws(throwingSecond, /Second$/);
// If the error message does not match, an AssertionError is thrown.
assert.throws(throwingFirst, /Second$/);
// AssertionError [ERR_ASSERTION]
Due to the confusing error-prone notation, avoid a string as the second argument.
Asynchronous context tracking#
Source Code: lib/async_hooks.js
Introduction#
These classes are used to associate state and propagate it throughout callbacks and promise chains. They allow storing data throughout the lifetime of a web request or any other asynchronous duration. It is similar to thread-local storage in other languages.
The AsyncLocalStorage and AsyncResource classes are part of the
async_hooks module:
import { AsyncLocalStorage, AsyncResource } from 'async_hooks';const { AsyncLocalStorage, AsyncResource } = require('async_hooks');
Class: AsyncLocalStorage#
This class creates stores that stay coherent through asynchronous operations.
While you can create your own implementation on top of the async_hooks module,
AsyncLocalStorage should be preferred as it is a performant and memory safe
implementation that involves significant optimizations that are non-obvious to
implement.
The following example uses AsyncLocalStorage to build a simple logger
that assigns IDs to incoming HTTP requests and includes them in messages
logged within each request.
import http from 'http';
import { AsyncLocalStorage } from 'async_hooks';
const asyncLocalStorage = new AsyncLocalStorage();
function logWithId(msg) {
const id = asyncLocalStorage.getStore();
console.log(`${id !== undefined ? id : '-'}:`, msg);
}
let idSeq = 0;
http.createServer((req, res) => {
asyncLocalStorage.run(idSeq++, () => {
logWithId('start');
// Imagine any chain of async operations here
setImmediate(() => {
logWithId('finish');
res.end();
});
});
}).listen(8080);
http.get('http://localhost:8080');
http.get('http://localhost:8080');
// Prints:
// 0: start
// 1: start
// 0: finish
// 1: finishconst http = require('http');
const { AsyncLocalStorage } = require('async_hooks');
const asyncLocalStorage = new AsyncLocalStorage();
function logWithId(msg) {
const id = asyncLocalStorage.getStore();
console.log(`${id !== undefined ? id : '-'}:`, msg);
}
let idSeq = 0;
http.createServer((req, res) => {
asyncLocalStorage.run(idSeq++, () => {
logWithId('start');
// Imagine any chain of async operations here
setImmediate(() => {
logWithId('finish');
res.end();
});
});
}).listen(8080);
http.get('http://localhost:8080');
http.get('http://localhost:8080');
// Prints:
// 0: start
// 1: start
// 0: finish
// 1: finish
Each instance of AsyncLocalStorage maintains an independent storage context.
Multiple instances can safely exist simultaneously without risk of interfering
with each other's data.
new AsyncLocalStorage()#
Creates a new instance of AsyncLocalStorage. Store is only provided within a
run() call or after an enterWith() call.
asyncLocalStorage.disable()#
Disables the instance of AsyncLocalStorage. All subsequent calls
to asyncLocalStorage.getStore() will return undefined until
asyncLocalStorage.run() or asyncLocalStorage.enterWith() is called again.
When calling asyncLocalStorage.disable(), all current contexts linked to the
instance will be exited.
Calling asyncLocalStorage.disable() is required before the
asyncLocalStorage can be garbage collected. This does not apply to stores
provided by the asyncLocalStorage, as those objects are garbage collected
along with the corresponding async resources.
Use this method when the asyncLocalStorage is not in use anymore
in the current process.
asyncLocalStorage.getStore()#
- Returns: <any>
Returns the current store.
If called outside of an asynchronous context initialized by
calling asyncLocalStorage.run()