Node.js v26.0.0 documentation
- Node.js v26.0.0
- Table of contents
- 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:
- Crypto
- Determining if crypto support is unavailable
- Asymmetric key types
- Class:
Certificate - Class:
Cipheriv - Class:
Decipheriv - 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.validFromDatex509.validTox509.validToDatex509.signatureAlgorithmx509.signatureAlgorithmOidx509.verify(publicKey)
node:cryptomodule methods and propertiescrypto.argon2(algorithm, parameters, callback)crypto.argon2Sync(algorithm, parameters)crypto.checkPrime(candidate[, options], callback)crypto.checkPrimeSync(candidate[, options])crypto.constantscrypto.createCipheriv(algorithm, key, iv[, 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.decapsulate(key, ciphertext[, callback])crypto.diffieHellman(options[, callback])crypto.encapsulate(key[, callback])crypto.fipscrypto.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.hash(algorithm, data[, options])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.randomFill(buffer[, offset][, size], callback)crypto.randomFillSync(buffer[, offset][, size])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
- 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('node: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('node:sys') - DEP0026:
util.print() - DEP0027:
util.puts() - DEP0028:
util.debug() - DEP0029:
util.error() - DEP0030:
SlowBuffer - DEP0031:
ecdh.setPublicKey() - DEP0032:
node: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:
node: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('node: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('node:_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) - DEP0159:
ERR_INVALID_CALLBACK - DEP0160:
process.on('multipleResolves', handler) - DEP0161:
process._getActiveRequests()andprocess._getActiveHandles() - DEP0162:
fs.write(),fs.writeFileSync()coercion to string - DEP0163:
channel.subscribe(onMessage),channel.unsubscribe(onMessage) - DEP0164:
process.exit(code),process.exitCodecoercion to integer - DEP0165:
--trace-atomics-wait - DEP0166: Double slashes in imports and exports targets
- DEP0167: Weak
DiffieHellmanGroupinstances (modp1,modp2,modp5) - DEP0168: Unhandled exception in Node-API callbacks
- DEP0169: Insecure url.parse()
- DEP0170: Invalid port when using
url.parse() - DEP0171: Setters for
http.IncomingMessageheaders and trailers - DEP0172: The
asyncResourceproperty ofAsyncResourcebound functions - DEP0173: the
assert.CallTrackerclass - DEP0174: calling
promisifyon a function that returns aPromise - DEP0175:
util.toUSVString - DEP0176:
fs.F_OK,fs.R_OK,fs.W_OK,fs.X_OK - DEP0177:
util.types.isWebAssemblyCompiledModule - DEP0178:
dirent.path - DEP0179:
Hashconstructor - DEP0180:
fs.Statsconstructor - DEP0181:
Hmacconstructor - DEP0182: Short GCM authentication tags without explicit
authTagLength - DEP0183: OpenSSL engine-based APIs
- DEP0184: Instantiating
node:zlibclasses withoutnew - DEP0185: Instantiating
node:replclasses withoutnew - DEP0187: Passing invalid argument types to
fs.existsSync - DEP0188:
process.features.ipv6andprocess.features.uv - DEP0189:
process.features.tls_* - DEP0190: Passing
argstonode:child_processexecFile/spawnwithshelloptiontrue - DEP0191:
repl.builtinModules - DEP0192:
require('node:_tls_common')andrequire('node:_tls_wrap') - DEP0193:
require('node:_stream_*') - DEP0194: HTTP/2 priority signaling
- DEP0195: Instantiating
node:httpclasses withoutnew - DEP0196: Calling
node:child_processfunctions withoptions.shellas an empty string - DEP0197:
util.types.isNativeError() - DEP0198: Creating SHAKE-128 and SHAKE-256 digests without an explicit
options.outputLength - DEP0199:
require('node:_http_*') - DEP0200: Closing fs.Dir on garbage collection
- DEP0201: Passing
options.typetoDuplex.toWeb() - DEP0202:
Http1IncomingMessageandHttp1ServerResponseoptions of HTTP/2 servers
- DEP0001:
- Diagnostics Channel
- Public API
- Overview
- Class:
Channel - Class:
TracingChanneltracingChannel.subscribe(subscribers)tracingChannel.unsubscribe(subscribers)tracingChannel.traceSync(fn[, context[, thisArg[, ...args]]])tracingChannel.tracePromise(fn[, context[, thisArg[, ...args]]])tracingChannel.traceCallback(fn[, position[, context[, thisArg[, ...args]]]])tracingChannel.hasSubscribers
- TracingChannel Channels
- Built-in Channels
- Public API
- 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.resolveTlsa(hostname, callback)dns.resolveTxt(hostname, callback)dns.reverse(ip, callback)dns.setDefaultResultOrder(order)dns.getDefaultResultOrder()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.resolveTlsa(hostname)dnsPromises.resolveTxt(hostname)dnsPromises.reverse(ip)dnsPromises.setDefaultResultOrder(order)dnsPromises.getDefaultResultOrder()dnsPromises.setServers(servers)
- Class:
- Error codes
- Implementation considerations
- Class:
- 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_ACCESS_DENIEDERR_AMBIGUOUS_ARGUMENTERR_ARG_NOT_ITERABLEERR_ASSERTIONERR_ASYNC_CALLBACKERR_ASYNC_LOADER_REQUEST_NEVER_SETTLEDERR_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_CPU_PROFILE_ALREADY_STARTEDERR_CPU_PROFILE_NOT_STARTEDERR_CPU_PROFILE_TOO_MANYERR_CRYPTO_ARGON2_NOT_SUPPORTEDERR_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_KEYLENERR_CRYPTO_INVALID_KEYPAIRERR_CRYPTO_INVALID_KEYTYPEERR_CRYPTO_INVALID_KEY_OBJECT_TYPEERR_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_KEM_NOT_SUPPORTEDERR_CRYPTO_OPERATION_FAILEDERR_CRYPTO_PBKDF2_ERRORERR_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_DIR_CLOSEDERR_DIR_CONCURRENT_OPERATIONERR_DLOPEN_DISABLEDERR_DLOPEN_FAILEDERR_DNS_SET_SERVERS_FAILEDERR_DOMAIN_CALLBACK_NOT_AVAILABLEERR_DOMAIN_CANNOT_SET_UNCAUGHT_EXCEPTION_CAPTUREERR_DUPLICATE_STARTUP_SNAPSHOT_MAIN_FUNCTIONERR_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_WATCH_QUEUE_OVERFLOWERR_HTTP2_ALTSVC_INVALID_ORIGINERR_HTTP2_ALTSVC_LENGTHERR_HTTP2_CONNECT_AUTHORITYERR_HTTP2_CONNECT_PATHERR_HTTP2_CONNECT_SCHEMEERR_HTTP2_ERRORERR_HTTP2_GOAWAY_SESSIONERR_HTTP2_HEADERS_AFTER_RESPONDERR_HTTP2_HEADERS_SENTERR_HTTP2_HEADER_SINGLE_VALUEERR_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_CUSTOM_SETTINGSERR_HTTP2_TOO_MANY_INVALID_FRAMESERR_HTTP2_TRAILERS_ALREADY_SENTERR_HTTP2_TRAILERS_NOT_READYERR_HTTP2_UNSUPPORTED_PROTOCOLERR_HTTP_BODY_NOT_ALLOWEDERR_HTTP_CONTENT_LENGTH_MISMATCHERR_HTTP_HEADERS_SENTERR_HTTP_INVALID_HEADER_VALUEERR_HTTP_INVALID_STATUS_CODEERR_HTTP_REQUEST_TIMEOUTERR_HTTP_SOCKET_ASSIGNEDERR_HTTP_SOCKET_ENCODINGERR_HTTP_TRAILER_INVALIDERR_ILLEGAL_CONSTRUCTORERR_IMPORT_ATTRIBUTE_MISSINGERR_IMPORT_ATTRIBUTE_TYPE_INCOMPATIBLEERR_IMPORT_ATTRIBUTE_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_ADDRESSERR_INVALID_ADDRESS_FAMILYERR_INVALID_ARG_TYPEERR_INVALID_ARG_VALUEERR_INVALID_ASYNC_IDERR_INVALID_BUFFER_SIZEERR_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_MIME_SYNTAXERR_INVALID_MODULEERR_INVALID_MODULE_SPECIFIERERR_INVALID_OBJECT_DEFINE_PROPERTYERR_INVALID_PACKAGE_CONFIGERR_INVALID_PACKAGE_TARGETERR_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_TUPLEERR_INVALID_TYPESCRIPT_SYNTAXERR_INVALID_URIERR_INVALID_URLERR_INVALID_URL_PATTERNERR_INVALID_URL_SCHEMEERR_IPC_CHANNEL_CLOSEDERR_IPC_DISCONNECTEDERR_IPC_ONE_PIPEERR_IPC_SYNC_FORKERR_IP_BLOCKEDERR_LOADER_CHAIN_INCOMPLETEERR_LOAD_SQLITE_EXTENSIONERR_MEMORY_ALLOCATION_FAILEDERR_MESSAGE_TARGET_CONTEXT_UNAVAILABLEERR_METHOD_NOT_IMPLEMENTEDERR_MISSING_ARGSERR_MISSING_OPTIONERR_MISSING_PASSPHRASEERR_MISSING_PLATFORM_FOR_WORKERERR_MODULE_LINK_MISMATCHERR_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_NON_CONTEXT_AWARE_DISABLEDERR_NOT_BUILDING_SNAPSHOTERR_NOT_IN_SINGLE_EXECUTABLE_APPLICATIONERR_NOT_SUPPORTED_IN_SNAPSHOTERR_NO_CRYPTOERR_NO_ICUERR_NO_TYPESCRIPTERR_OPERATION_FAILEDERR_OPTIONS_BEFORE_BOOTSTRAPPINGERR_OUT_OF_RANGEERR_PACKAGE_IMPORT_NOT_DEFINEDERR_PACKAGE_PATH_NOT_EXPORTEDERR_PARSE_ARGS_INVALID_OPTION_VALUEERR_PARSE_ARGS_UNEXPECTED_POSITIONALERR_PARSE_ARGS_UNKNOWN_OPTIONERR_PERFORMANCE_INVALID_TIMESTAMPERR_PERFORMANCE_MEASURE_INVALID_OPTIONSERR_PROTO_ACCESSERR_PROXY_INVALID_CONFIGERR_PROXY_TUNNELERR_QUIC_APPLICATION_ERRORERR_QUIC_CONNECTION_FAILEDERR_QUIC_ENDPOINT_CLOSEDERR_QUIC_OPEN_STREAM_FAILEDERR_QUIC_TRANSPORT_ERRORERR_QUIC_VERSION_NEGOTIATION_ERRORERR_REQUIRE_ASYNC_MODULEERR_REQUIRE_CYCLE_MODULEERR_REQUIRE_ESMERR_SCRIPT_EXECUTION_INTERRUPTEDERR_SCRIPT_EXECUTION_TIMEOUTERR_SERVER_ALREADY_LISTENERR_SERVER_NOT_RUNNINGERR_SINGLE_EXECUTABLE_APPLICATION_ASSET_NOT_FOUNDERR_SOCKET_ALREADY_BOUNDERR_SOCKET_BAD_BUFFER_SIZEERR_SOCKET_BAD_PORTERR_SOCKET_BAD_TYPEERR_SOCKET_BUFFER_SIZEERR_SOCKET_CLOSEDERR_SOCKET_CLOSED_BEFORE_CONNECTIONERR_SOCKET_CONNECTION_TIMEOUTERR_SOCKET_DGRAM_IS_CONNECTEDERR_SOCKET_DGRAM_NOT_CONNECTEDERR_SOCKET_DGRAM_NOT_RUNNINGERR_SOURCE_MAP_CORRUPTERR_SOURCE_MAP_MISSING_SOURCEERR_SOURCE_PHASE_NOT_DEFINEDERR_SQLITE_ERRORERR_SRI_PARSEERR_STREAM_ALREADY_FINISHEDERR_STREAM_CANNOT_PIPEERR_STREAM_DESTROYEDERR_STREAM_NULL_VALUESERR_STREAM_PREMATURE_CLOSEERR_STREAM_PUSH_AFTER_EOFERR_STREAM_UNABLE_TO_PIPEERR_STREAM_UNSHIFT_AFTER_END_EVENTERR_STREAM_WRAPERR_STREAM_WRITE_AFTER_ENDERR_STRING_TOO_LONGERR_SYNTHETICERR_SYSTEM_ERRORERR_TEST_FAILUREERR_TLS_ALPN_CALLBACK_INVALID_RESULTERR_TLS_ALPN_CALLBACK_WITH_PROTOCOLSERR_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_IDENTITY_HINT_FAILEDERR_TLS_RENEGOTIATION_DISABLEDERR_TLS_REQUIRED_SERVER_NAMEERR_TLS_SESSION_ATTACKERR_TLS_SNI_FROM_SERVERERR_TRACE_EVENTS_CATEGORY_REQUIREDERR_TRACE_EVENTS_UNAVAILABLEERR_TRAILING_JUNK_AFTER_STREAM_ENDERR_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_UNSUPPORTED_NODE_MODULES_TYPE_STRIPPINGERR_UNSUPPORTED_RESOLVE_REQUESTERR_UNSUPPORTED_TYPESCRIPT_SYNTAXERR_USE_AFTER_CLOSEERR_VALID_PERFORMANCE_ENTRY_TYPEERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSINGERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING_FLAGERR_VM_MODULE_ALREADY_LINKEDERR_VM_MODULE_CACHED_DATA_REJECTEDERR_VM_MODULE_CANNOT_CREATE_CACHED_DATAERR_VM_MODULE_DIFFERENT_CONTEXTERR_VM_MODULE_LINK_FAILUREERR_VM_MODULE_NOT_MODULEERR_VM_MODULE_STATUSERR_WASI_ALREADY_STARTEDERR_WASI_NOT_STARTEDERR_WEBASSEMBLY_NOT_SUPPORTEDERR_WEBASSEMBLY_RESPONSEERR_WORKER_INIT_FAILEDERR_WORKER_INVALID_EXEC_ARGVERR_WORKER_MESSAGING_ERROREDERR_WORKER_MESSAGING_FAILEDERR_WORKER_MESSAGING_SAME_THREADERR_WORKER_MESSAGING_TIMEOUTERR_WORKER_NOT_RUNNINGERR_WORKER_OUT_OF_MEMORYERR_WORKER_PATHERR_WORKER_UNSERIALIZABLE_ERRORERR_WORKER_UNSUPPORTED_OPERATIONERR_ZLIB_INITIALIZATION_FAILEDERR_ZSTD_INVALID_PARAMHPE_CHUNK_EXTENSIONS_OVERFLOWHPE_HEADER_OVERFLOWHPE_UNEXPECTED_CONTENT_LENGTHMODULE_NOT_FOUND
- Legacy Node.js error codes
ERR_CANNOT_TRANSFER_OBJECTERR_CPU_USAGEERR_CRYPTO_HASH_DIGEST_NO_UTF16ERR_CRYPTO_SCRYPT_INVALID_PARAMETERERR_FS_INVALID_SYMLINK_TYPEERR_HTTP2_FRAME_ERRORERR_HTTP2_HEADERS_OBJECTERR_HTTP2_HEADER_REQUIREDERR_HTTP2_INFO_HEADERS_AFTER_RESPONDERR_HTTP2_STREAM_CLOSEDERR_HTTP_INVALID_CHARERR_IMPORT_ASSERTION_TYPE_FAILEDERR_IMPORT_ASSERTION_TYPE_MISSINGERR_IMPORT_ASSERTION_TYPE_UNSUPPORTEDERR_INDEX_OUT_OF_RANGEERR_INVALID_OPT_VALUEERR_INVALID_OPT_VALUE_ENCODINGERR_INVALID_PERFORMANCE_MARKERR_INVALID_TRANSFER_OBJECTERR_MANIFEST_ASSERT_INTEGRITYERR_MANIFEST_DEPENDENCY_MISSINGERR_MANIFEST_INTEGRITY_MISMATCHERR_MANIFEST_INVALID_RESOURCE_FIELDERR_MANIFEST_INVALID_SPECIFIERERR_MANIFEST_PARSE_POLICYERR_MANIFEST_TDZERR_MANIFEST_UNKNOWN_ONERRORERR_MISSING_MESSAGE_PORT_IN_TRANSFER_LISTERR_MISSING_TRANSFERABLE_IN_TRANSFER_LISTERR_NAPI_CONS_PROTOTYPE_OBJECTERR_NAPI_TSFN_START_IDLE_LOOPERR_NAPI_TSFN_STOP_IDLE_LOOPERR_NO_LONGER_SUPPORTEDERR_OUTOFMEMORYERR_PARSE_HISTORY_DATAERR_SOCKET_CANNOT_SENDERR_STDERR_CLOSEERR_STDOUT_CLOSEERR_STREAM_READ_NOT_IMPLEMENTEDERR_TAP_LEXER_ERRORERR_TAP_PARSER_ERRORERR_TAP_VALIDATION_ERRORERR_TLS_RENEGOTIATION_FAILEDERR_TRANSFERRING_EXTERNALIZED_SHAREDARRAYBUFFERERR_UNKNOWN_STDIN_TYPEERR_UNKNOWN_STREAM_TYPEERR_V8BREAKITERATORERR_VALUE_OUT_OF_RANGEERR_VM_MODULE_LINKING_ERROREDERR_VM_MODULE_NOT_LINKEDERR_WORKER_UNSUPPORTED_EXTENSIONERR_ZLIB_BINDING_CLOSED
- OpenSSL Error Codes
- Modules: CommonJS modules
- Enabling
- Accessing the main module
- Package manager tips
- Loading ECMAScript modules using
require() - All together
- Caching
- Built-in 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: Packages
- Net
- IPC support
- Class:
net.BlockList - Class:
net.SocketAddress - Class:
net.Servernew net.Server([options][, connectionListener])- Event:
'close' - Event:
'connection' - Event:
'error' - Event:
'listening' - Event:
'drop' server.address()server.close([callback])server[Symbol.asyncDispose]()server.getConnections(callback)server.listen()server.listeningserver.maxConnectionsserver.dropMaxConnectionserver.ref()server.unref()
- Class:
net.Socketnew net.Socket([options])- Event:
'close' - Event:
'connect' - Event:
'connectionAttempt' - Event:
'connectionAttemptFailed' - Event:
'connectionAttemptTimeout' - Event:
'data' - Event:
'drain' - Event:
'end' - Event:
'error' - Event:
'lookup' - Event:
'ready' - Event:
'timeout' socket.address()socket.autoSelectFamilyAttemptedAddressessocket.bufferSizesocket.bytesReadsocket.bytesWrittensocket.connect()socket.connectingsocket.destroy([error])socket.destroyedsocket.destroySoon()socket.end([data[, encoding]][, callback])socket.localAddresssocket.localPortsocket.localFamilysocket.pause()socket.pendingsocket.ref()socket.remoteAddresssocket.remoteFamilysocket.remotePortsocket.resetAndDestroy()socket.resume()socket.setEncoding([encoding])socket.setKeepAlive([enable][, initialDelay])socket.setNoDelay([noDelay])socket.setTimeout(timeout[, callback])socket.getTypeOfService()socket.setTypeOfService(tos)socket.timeoutsocket.unref()socket.write(data[, encoding][, callback])socket.readyState
net.connect()net.createConnection()net.createServer([options][, connectionListener])net.getDefaultAutoSelectFamily()net.setDefaultAutoSelectFamily(value)net.getDefaultAutoSelectFamilyAttemptTimeout()net.setDefaultAutoSelectFamilyAttemptTimeout(value)net.isIP(input)net.isIPv4(input)net.isIPv6(input)
- Node-API
- Writing addons in various programming languages
- 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_objectnode_api_create_object_with_propertiesnapi_create_symbolnode_api_symbol_fornapi_create_typedarraynode_api_create_buffer_from_arraybuffernapi_create_dataview
- Functions to convert from C types to Node-API
- Functions to create optimized property keys
- 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
napi_coerce_to_boolnapi_coerce_to_numbernapi_coerce_to_objectnapi_coerce_to_stringnapi_typeofnapi_instanceofnapi_is_arraynapi_is_arraybuffernapi_is_buffernapi_is_datenapi_is_errornapi_is_typedarraynapi_is_dataviewnapi_strict_equalsnapi_detach_arraybuffernapi_is_detached_arraybuffernode_api_is_sharedarraybuffernode_api_create_sharedarraybuffer
- 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_sealnode_api_set_prototype
- 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
- OS
os.EOLos.availableParallelism()os.arch()os.constantsos.cpus()os.devNullos.endianness()os.freemem()os.getPriority([pid])os.homedir()os.hostname()os.loadavg()os.machine()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[, suffix])path.delimiterpath.dirname(path)path.extname(path)path.format(pathObject)path.matchesGlob(path, pattern)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.clearResourceTimings([name])performance.eventLoopUtilization([utilization1[, utilization2]])performance.getEntries()performance.getEntriesByName(name[, type])performance.getEntriesByType(type)performance.mark(name[, options])performance.markResourceTiming(timingInfo, requestedUrl, initiatorType, global, cacheMode, bodyInfo, responseStatus[, deliveryType])performance.measure(name[, startMarkOrOptions[, endMark]])performance.nodeTimingperformance.now()performance.setResourceTimingBufferSize(maxSize)performance.timeOriginperformance.timerify(fn[, options])performance.toJSON()
- Class:
PerformanceEntry - Class:
PerformanceMark - Class:
PerformanceMeasure - Class:
PerformanceNodeEntry - Class:
PerformanceNodeTiming - Class:
PerformanceResourceTimingperformanceResourceTiming.workerStartperformanceResourceTiming.redirectStartperformanceResourceTiming.redirectEndperformanceResourceTiming.fetchStartperformanceResourceTiming.domainLookupStartperformanceResourceTiming.domainLookupEndperformanceResourceTiming.connectStartperformanceResourceTiming.connectEndperformanceResourceTiming.secureConnectionStartperformanceResourceTiming.requestStartperformanceResourceTiming.responseEndperformanceResourceTiming.transferSizeperformanceResourceTiming.encodedBodySizeperformanceResourceTiming.decodedBodySizeperformanceResourceTiming.toJSON()
- Class:
PerformanceObserver - Class:
PerformanceObserverEntryList perf_hooks.createHistogram([options])perf_hooks.eventLoopUtilization([utilization1[, utilization2]])perf_hooks.monitorEventLoopDelay([options])perf_hooks.timerify(fn[, 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
- TLS (SSL)
- Determining if crypto support is unavailable
- TLS/SSL concepts
- Modifying the default TLS cipher suite
- OpenSSL security level
- X509 certificate error codes
- 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:
'secure' - 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.setKeyCert(context)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.createServer([options][, secureConnectionListener])tls.setDefaultCACertificates(certs)tls.getCACertificates([type])tls.getCiphers()tls.rootCertificatestls.DEFAULT_ECDH_CURVEtls.DEFAULT_MAX_VERSIONtls.DEFAULT_MIN_VERSIONtls.DEFAULT_CIPHERS
- TTY
- Class:
tty.ReadStream - Class:
tty.WriteStreamnew tty.ReadStream(fd[, options])new tty.WriteStream(fd)- 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
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[Symbol.asyncDispose]()socket.connect(port[, address][, callback])socket.disconnect()socket.dropMembership(multicastAddress[, multicastInterface])socket.dropSourceSpecificMembership(sourceAddress, groupAddress[, multicastInterface])socket.getRecvBufferSize()socket.getSendBufferSize()socket.getSendQueueSize()socket.getSendQueueCount()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:
node:dgrammodule functions
- Class:
- URL
- URL strings and URL objects
- The WHATWG URL API
- Class:
URL - Class:
URLPattern - Class:
URLSearchParamsnew URLSearchParams()new URLSearchParams(string)new URLSearchParams(obj)new URLSearchParams(iterable)urlSearchParams.append(name, value)urlSearchParams.delete(name[, value])urlSearchParams.entries()urlSearchParams.forEach(fn[, thisArg])urlSearchParams.get(name)urlSearchParams.getAll(name)urlSearchParams.has(name[, value])urlSearchParams.keys()urlSearchParams.set(name, value)urlSearchParams.sizeurlSearchParams.sort()urlSearchParams.toString()urlSearchParams.values()urlSearchParams[Symbol.iterator]()
url.domainToASCII(domain)url.domainToUnicode(domain)url.fileURLToPath(url[, options])url.fileURLToPathBuffer(url[, options])url.format(URL[, options])url.pathToFileURL(path[, options])url.urlToHttpOptions(url)
- Class:
- Legacy URL API
- Percent-encoding in URLs
- Util
util.callbackify(original)util.convertProcessSignalToExitCode(signalCode)util.debuglog(section[, callback])util.debug(section)util.deprecate(fn, msg[, code[, options]])util.diff(actual, expected)util.format(format[, ...args])util.formatWithOptions(inspectOptions, format[, ...args])util.getCallSites([frameCount][, options])util.getSystemErrorName(err)util.getSystemErrorMap()util.getSystemErrorMessage(err)util.setTraceSigInt(enable)util.inherits(constructor, superConstructor)util.inspect(object[, options])util.inspect(object[, showHidden[, depth[, colors]]])util.isDeepStrictEqual(val1, val2[, options])- Class:
util.MIMEType - Class:
util.MIMEParams util.parseArgs([config])util.parseEnv(content)util.promisify(original)util.stripVTControlCharacters(str)util.styleText(format, text[, options])- Class:
util.TextDecoder - Class:
util.TextEncoder util.toUSVString(string)util.transferableAbortController()util.transferableAbortSignal(signal)util.aborted(signal, resource)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.isBigIntObject(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.isFloat16Array(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)
- Deprecated APIs
- V8
v8.cachedDataVersionTag()v8.getHeapCodeStatistics()v8.getHeapSnapshot([options])v8.getHeapSpaceStatistics()v8.getHeapStatistics()v8.getCppHeapStatistics([detailLevel])v8.queryObjects(ctor[, options])v8.setFlagsFromString(flags)v8.stopCoverage()v8.takeCoverage()v8.writeHeapSnapshot([filename[,options]])v8.setHeapSnapshotNearHeapLimit(limit)- 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.Deserializer - Class:
v8.DefaultSerializer - Class:
v8.DefaultDeserializer
- Promise hooks
- Startup Snapshot API
- Class:
v8.GCProfiler - Class:
SyncCPUProfileHandle - Class:
CPUProfileHandle - Class:
HeapProfileHandle v8.isStringOneByteRepresentation(content)v8.startCpuProfile()
- VM (executing JavaScript)
- Class:
vm.Script - Class:
vm.Module - Class:
vm.SourceTextModule - Class:
vm.SyntheticModule - Type:
ModuleRequest vm.compileFunction(code[, params[, options]])vm.constantsvm.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
- Support of dynamic
import()in compilation APIs
- Class:
- Assert
- Strict assertion mode
- Legacy assertion mode
- Class:
assert.AssertionError - Class:
assert.Assert 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.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])assert.partialDeepStrictEqual(actual, expected[, message])
- Async hooks
- Asynchronous context tracking
- Introduction
- Class:
AsyncLocalStoragenew AsyncLocalStorage([options])- Static method:
AsyncLocalStorage.bind(fn) - Static method:
AsyncLocalStorage.snapshot() asyncLocalStorage.disable()asyncLocalStorage.getStore()asyncLocalStorage.enterWith(store)asyncLocalStorage.nameasyncLocalStorage.run(store, callback[, ...args])asyncLocalStorage.exit(callback[, ...args])- Usage with
async/await - Troubleshooting: Context loss
- 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
- 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.copyBytesFrom(view[, offset[, length]]) - 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) Buffer.poolSizebuf[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:
- Class:
File node:buffermodule APIsBuffer.from(),Buffer.alloc(), andBuffer.allocUnsafe()
- 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[Symbol.dispose]()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--allow-addons--allow-child-process--allow-fs-read--allow-fs-write--allow-inspector--allow-net--allow-wasi--allow-worker--build-sea=config--build-snapshot--build-snapshot-config-c,--check--completion-bash-C condition,--conditions=condition--cpu-prof--cpu-prof-dir--cpu-prof-interval--cpu-prof-name--diagnostic-dir=directory--disable-proto=mode--disable-sigusr1--disable-warning=code-or-type--disable-wasm-trap-handler--disallow-code-generation-from-strings--dns-result-order=order--enable-fips--enable-source-maps--entry-url--env-file-if-exists=file--env-file=file-e,--eval "script"--experimental-addon-modules--experimental-config-file=config--experimental-default-config-file--experimental-eventsource--experimental-import-meta-resolve--experimental-inspector-network-resource--experimental-loader=module--experimental-network-inspection--experimental-print-required-tla--experimental-quic--experimental-sea-config--experimental-shadow-realm--experimental-storage-inspection--experimental-test-coverage--experimental-test-module-mocks--experimental-vm-modules--experimental-wasi-unstable-preview1--experimental-worker-inspection--expose-gc--force-context-aware--force-fips--force-node-api-uncaught-exceptions-policy--frozen-intrinsics--heap-prof--heap-prof-dir--heap-prof-interval--heap-prof-name--heapsnapshot-near-heap-limit=max_count--heapsnapshot-signal=signal-h,--help--icu-data-dir=file--import=module--input-type=type--insecure-http-parser--inspect-brk[=[host:]port]--inspect-port=[host:]port--inspect-publish-uid=stderr,http--inspect-wait[=[host:]port]--inspect[=[host:]port]-i,--interactive--jitless--localstorage-file=file--max-http-header-size=size--max-old-space-size-percentage=percentage--napi-modules--network-family-autoselection-attempt-timeout--no-addons--no-async-context-frame--no-deprecation--no-experimental-detect-module--no-experimental-global-navigator--no-experimental-repl-await--no-experimental-require-module--no-experimental-sqlite--no-experimental-websocket--no-experimental-webstorage--no-extra-info-on-fatal-exception--no-force-async-hooks-checks--no-global-search-paths--no-network-family-autoselection--no-require-module--no-strip-types--no-warnings--node-memory-debug--openssl-config=file--openssl-legacy-provider--openssl-shared-config--pending-deprecation--permission--permission-audit--preserve-symlinks--preserve-symlinks-main-p,--print "script"--prof--prof-process--redirect-warnings=file--report-compact--report-dir=directory,--report-directory=directory--report-exclude-env--report-exclude-network--report-filename=filename--report-on-fatalerror--report-on-signal--report-signal=signal--report-uncaught-exception-r,--require module--run--secure-heap-min=n--secure-heap=n--snapshot-blob=path--test--test-concurrency--test-coverage-branches=threshold--test-coverage-exclude--test-coverage-functions=threshold--test-coverage-include--test-coverage-lines=threshold--test-force-exit--test-global-setup=module--test-isolation=mode--test-name-pattern--test-only--test-reporter--test-reporter-destination--test-rerun-failures--test-shard--test-skip-pattern--test-timeout--test-update-snapshots--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-deprecation--trace-env--trace-env-js-stack--trace-env-native-stack--trace-event-categories--trace-event-file-pattern--trace-events-enabled--trace-exit--trace-require-module=mode--trace-sigint--trace-sync-io--trace-tls--trace-uncaught--trace-warnings--track-heap-objects--unhandled-rejections=mode--use-bundled-ca,--use-openssl-ca--use-env-proxy--use-largepages=mode--use-system-ca--v8-options--v8-pool-size=num-v,--version--watch--watch-kill-signal--watch-path--watch-preserve-output--zero-fill-buffers
- Environment variables
FORCE_COLOR=[1, 2, 3]NODE_COMPILE_CACHE=dirNODE_COMPILE_CACHE_PORTABLE=1NODE_DEBUG=module[,…]NODE_DEBUG_NATIVE=module[,…]NODE_DISABLE_COLORS=1NODE_DISABLE_COMPILE_CACHE=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_EXTERNAL_MODULE=fileNODE_REPL_HISTORY=fileNODE_SKIP_PLATFORM_CHECK=valueNODE_TEST_CONTEXT=valueNODE_TLS_REJECT_UNAUTHORIZED=valueNODE_USE_ENV_PROXY=1NODE_USE_SYSTEM_CA=1NODE_V8_COVERAGE=dirNO_COLOR=<any>OPENSSL_CONF=fileSSL_CERT_DIR=dirSSL_CERT_FILE=fileTZUV_THREADPOOL_SIZE=size
- Useful V8 options
--abort-on-uncaught-exception--disallow-code-generation-from-strings--enable-etw-stack-walking--expose-gc--harmony-shadow-realm--heap-snapshot-on-oom--interpreted-frames-native-stack--jitless--max-heap-size--max-old-space-size=SIZE(in MiB)--max-semi-space-size=SIZE(in MiB)--perf-basic-prof--perf-basic-prof-only-functions--perf-prof--perf-prof-unwinding-info--prof--security-revert--stack-trace-limit=limit
- Web Crypto API
- Modern Algorithms in the Web Cryptography API
- Secure Curves in the Web Cryptography API
- Examples
- Algorithm matrix
- Class:
Crypto - Class:
CryptoKey - Class:
CryptoKeyPair - Class:
SubtleCrypto- Static method:
SubtleCrypto.supports(operation, algorithm[, lengthOrAdditionalAlgorithm]) subtle.decapsulateBits(decapsulationAlgorithm, decapsulationKey, ciphertext)subtle.decapsulateKey(decapsulationAlgorithm, decapsulationKey, ciphertext, sharedKeyAlgorithm, extractable, usages)subtle.decrypt(algorithm, key, data)subtle.deriveBits(algorithm, baseKey[, length])subtle.deriveKey(algorithm, baseKey, derivedKeyAlgorithm, extractable, keyUsages)subtle.digest(algorithm, data)subtle.encapsulateBits(encapsulationAlgorithm, encapsulationKey)subtle.encapsulateKey(encapsulationAlgorithm, encapsulationKey, sharedKeyAlgorithm, extractable, usages)subtle.encrypt(algorithm, key, data)subtle.exportKey(format, key)subtle.getPublicKey(key, keyUsages)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)
- Static method:
- Algorithm parameters
- Class:
Algorithm - Class:
AeadParams - Class:
AesDerivedKeyParams - Class:
AesCbcParams - Class:
AesCtrParams - Class:
AesKeyAlgorithm - Class:
AesKeyGenParams - Class:
Argon2Params - Class:
ContextParams - Class:
CShakeParams - Class:
EcdhKeyDeriveParams - Class:
EcdsaParams - Class:
EcKeyAlgorithm - Class:
EcKeyGenParams - Class:
EcKeyImportParams - Class:
EncapsulatedBits - Class:
EncapsulatedKey - Class:
HkdfParams - Class:
HmacImportParams - Class:
HmacKeyAlgorithm - Class:
HmacKeyGenParams - Class:
KeyAlgorithm - Class:
KmacImportParams - Class:
KmacKeyAlgorithm - Class:
KmacKeyGenParams - Class:
KmacParams - Class:
Pbkdf2Params - Class:
RsaHashedImportParams - Class:
RsaHashedKeyAlgorithm - Class:
RsaHashedKeyGenParams - Class:
RsaOaepParams - Class:
RsaPssParams
- Class:
- 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()
ReadableStream.from(iterable)- 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_threads.getEnvironmentData(key)worker_threads.isInternalThreadworker_threads.isMainThreadworker_threads.markAsUntransferable(object)worker_threads.isMarkedAsUntransferable(object)worker_threads.markAsUncloneable(object)worker_threads.moveMessagePortToContext(port, contextifiedSandbox)worker_threads.parentPortworker_threads.postMessageToThread(threadId, value[, transferList][, timeout])worker_threads.receiveMessageOnPort(port)worker_threads.resourceLimitsworker_threads.SHARE_ENVworker_threads.setEnvironmentData(key[, value])worker_threads.threadIdworker_threads.threadNameworker_threads.workerDataworker_threads.locks- Class:
BroadcastChannel extends EventTarget - Class:
MessageChannel - Class:
MessagePort - Class:
Workernew Worker(filename[, options])- Event:
'error' - Event:
'exit' - Event:
'message' - Event:
'messageerror' - Event:
'online' worker.cpuUsage([prev])worker.getHeapSnapshot([options])worker.getHeapStatistics()worker.performanceworker.postMessage(value[, transferList])worker.ref()worker.resourceLimitsworker.startCpuProfile()worker.startHeapProfile()worker.stderrworker.stdinworker.stdoutworker.terminate()worker.threadIdworker.threadNameworker.unref()worker[Symbol.asyncDispose]()
- 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 - Class:
ZstdOptions - Class:
zlib.ZstdCompress - Class:
zlib.ZstdDecompress zlib.constantszlib.crc32(data[, value])zlib.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])zlib.createZstdCompress([options])zlib.createZstdDecompress([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])zlib.zstdCompress(buffer[, options], callback)zlib.zstdCompressSync(buffer[, options])zlib.zstdDecompress(buffer[, options], callback)zlib.zstdDecompressSync(buffer[, options])
- Process
- Process events
process.abort()process.allowedNodeEnvironmentFlagsprocess.archprocess.argvprocess.argv0process.availableMemory()process.channelprocess.chdir(directory)process.configprocess.connectedprocess.constrainedMemory()process.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.execve(file[, args[, env]])process.exit([code])process.exitCodeprocess.features.cached_builtinsprocess.features.debugprocess.features.inspectorprocess.features.ipv6process.features.require_moduleprocess.features.tlsprocess.features.tls_alpnprocess.features.tls_ocspprocess.features.tls_sniprocess.features.typescriptprocess.features.uvprocess.finalization.register(ref, callback)process.finalization.registerBeforeExit(ref, callback)process.finalization.unregister(ref)process.getActiveResourcesInfo()process.getBuiltinModule(id)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.loadEnvFile(path)process.mainModuleprocess.memoryUsage()process.memoryUsage.rss()process.nextTick(callback[, ...args])process.noDeprecationprocess.permissionprocess.pidprocess.platformprocess.ppidprocess.ref(maybeRefable)process.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.sourceMapsEnabledprocess.stderrprocess.stdinprocess.stdoutprocess.throwDeprecationprocess.threadCpuUsage([previousValue])process.titleprocess.traceDeprecationprocess.traceProcessWarningsprocess.umask()process.umask(mask)process.unref(maybeRefable)process.uptime()process.versionprocess.versions- Exit codes
- Readline
- Class:
InterfaceConstructor- Event:
'close' - Event:
'error' - Event:
'line' - Event:
'history' - Event:
'pause' - Event:
'resume' - Event:
'SIGCONT' - Event:
'SIGINT' - Event:
'SIGTSTP' rl.close()rl[Symbol.dispose]()rl.pause()rl.prompt([preserveCursor])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:
- Single executable applications
- Generating single executable applications with
--build-sea - Single-executable application API
- In the injected main script
- Module format of the injected main script
- Module loading in the injected main script
require()in the injected main script__filenameandmodule.filenamein the injected main script__dirnamein the injected main scriptimport.metain the injected main scriptimport()in the injected main script- Using native addons in the injected main script
- Notes
- Generating single executable applications with
- SQLite
- Class:
DatabaseSyncnew DatabaseSync(path[, options])database.aggregate(name, options)database.close()database.loadExtension(path)database.enableLoadExtension(allow)database.enableDefensive(active)database.location([dbName])database.exec(sql)database.function(name[, options], fn)database.setAuthorizer(callback)database.isOpendatabase.isTransactiondatabase.limitsdatabase.open()database.prepare(sql[, options])database.createTagStore([maxSize])database.createSession([options])database.applyChangeset(changeset[, options])database[Symbol.dispose]()
- Class:
Session - Class:
StatementSyncstatement.all([namedParameters][, ...anonymousParameters])statement.columns()statement.expandedSQLstatement.get([namedParameters][, ...anonymousParameters])statement.iterate([namedParameters][, ...anonymousParameters])statement.run([namedParameters][, ...anonymousParameters])statement.setAllowBareNamedParameters(enabled)statement.setAllowUnknownNamedParameters(enabled)statement.setReturnArrays(enabled)statement.setReadBigInts(enabled)statement.sourceSQL
- Class:
SQLTagStoresqlTagStore.all(stringElements[, ...boundParameters])sqlTagStore.get(stringElements[, ...boundParameters])sqlTagStore.iterate(stringElements[, ...boundParameters])sqlTagStore.run(stringElements[, ...boundParameters])sqlTagStore.sizesqlTagStore.capacitysqlTagStore.dbsqlTagStore.clear()- Type conversion between JavaScript and SQLite
sqlite.backup(sourceDb, path[, options])sqlite.constants
- Class:
- Stream
- Organization of this document
- Types of streams
- API for stream consumers
- Writable streams
- Readable streams
- Duplex and transform streams
stream.finished(stream[, options], callback)stream.pipeline(source[, ...transforms], destination, callback)stream.pipeline(streams, callback)stream.compose(...streams)stream.isErrored(stream)stream.isReadable(stream)stream.isWritable(stream)stream.Readable.from(iterable[, options])stream.Readable.fromWeb(readableStream[, options])stream.Readable.isDisturbed(stream)stream.Readable.toWeb(streamReadable[, options])stream.Writable.fromWeb(writableStream[, options])stream.Writable.toWeb(streamWritable)stream.Duplex.from(src)stream.Duplex.fromWeb(pair[, options])stream.Duplex.toWeb(streamDuplex[, options])stream.addAbortSignal(signal, stream)stream.getDefaultHighWaterMark(objectMode)stream.setDefaultHighWaterMark(objectMode, value)
- API for stream implementers
- Additional notes
- Test runner
- Subtests
- Rerunning failed tests
describe()andit()aliases- Skipping tests
- TODO tests
- Expecting tests to fail
onlytests- Filtering tests by name
- Extraneous asynchronous activity
- Watch mode
- Global setup and teardown
- Running tests from the command line
- Collecting code coverage
- Mocking
- Snapshot testing
- Test reporters
run([options])suite([name][, options][, fn])suite.skip([name][, options][, fn])suite.todo([name][, options][, fn])suite.only([name][, options][, fn])test([name][, options][, fn])test.skip([name][, options][, fn])test.todo([name][, options][, fn])test.only([name][, options][, fn])describe([name][, options][, fn])describe.skip([name][, options][, fn])describe.todo([name][, options][, fn])describe.only([name][, options][, fn])it([name][, options][, fn])it.skip([name][, options][, fn])it.todo([name][, options][, fn])it.only([name][, options][, fn])before([fn][, options])after([fn][, options])beforeEach([fn][, options])afterEach([fn][, options])assertsnapshot- Class:
MockFunctionContext - Class:
MockModuleContext - Class:
MockPropertyContext - Class:
MockTrackermock.fn([original[, implementation]][, options])mock.getter(object, methodName[, implementation][, options])mock.method(object, methodName[, implementation][, options])mock.module(specifier[, options])mock.property(object, propertyName[, value])mock.reset()mock.restoreAll()mock.setter(object, methodName[, implementation][, options])
- Class:
MockTimers - Class:
TestsStream- Event:
'test:coverage' - Event:
'test:complete' - Event:
'test:dequeue' - Event:
'test:diagnostic' - Event:
'test:enqueue' - Event:
'test:fail' - Event:
'test:interrupted' - Event:
'test:pass' - Event:
'test:plan' - Event:
'test:start' - Event:
'test:stderr' - Event:
'test:stdout' - Event:
'test:summary' - Event:
'test:watch:drained' - Event:
'test:watch:restarted'
- Event:
- Class:
TestContextcontext.before([fn][, options])context.beforeEach([fn][, options])context.after([fn][, options])context.afterEach([fn][, options])context.assertcontext.diagnostic(message)context.filePathcontext.fullNamecontext.namecontext.passedcontext.errorcontext.attemptcontext.workerIdcontext.plan(count[,options])context.runOnly(shouldRunOnlyTests)context.signalcontext.skip([message])context.todo([message])context.test([name][, options][, fn])context.waitFor(condition[, options])
- Class:
SuiteContext
- 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[, listener])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.getMaxListeners(emitterOrTarget)events.once(emitter, name[, options])events.captureRejectionsevents.captureRejectionSymbolevents.listenerCount(emitterOrTarget, eventName)events.on(emitter, eventName[, options])events.setMaxListeners(n[, ...eventTargets])events.addAbortListener(signal, listener)- Class:
events.EventEmitterAsyncResource extends EventEmitter EventTargetandEventAPI- Node.js
EventTargetvs. DOMEventTarget NodeEventTargetvs.EventEmitter- Event listener
EventTargeterror handling- Class:
Eventevent.bubblesevent.cancelBubbleevent.cancelableevent.composedevent.composedPath()event.currentTargetevent.defaultPreventedevent.eventPhaseevent.initEvent(type[, bubbles[, cancelable]])event.isTrustedevent.preventDefault()event.returnValueevent.srcElementevent.stopImmediatePropagation()event.stopPropagation()event.targetevent.timeStampevent.type
- Class:
EventTarget - Class:
CustomEvent - Class:
NodeEventTargetnodeEventTarget.addListener(type, listener)nodeEventTarget.emit(type, arg)nodeEventTarget.eventNames()nodeEventTarget.listenerCount(type)nodeEventTarget.setMaxListeners(n)nodeEventTarget.getMaxListeners()nodeEventTarget.off(type, listener[, options])nodeEventTarget.on(type, listener)nodeEventTarget.once(type, listener)nodeEventTarget.removeAllListeners([type])nodeEventTarget.removeListener(type, listener[, options])
- 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.read(buffer[, options])filehandle.readableWebStream([options])filehandle.readFile(options)filehandle.readLines([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(buffer[, options])filehandle.write(string[, position[, encoding]])filehandle.writeFile(data, options)filehandle.writev(buffers[, position])filehandle[Symbol.asyncDispose]()
- 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.glob(pattern[, 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.mkdtempDisposable(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.statfs(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])fsPromises.constants
- 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.glob(pattern[, options], 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.openAsBlob(path[, options])fs.opendir(path[, options], callback)fs.read(fd, buffer, offset, length, position, callback)fs.read(fd[, options], callback)fs.read(fd, buffer[, 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.statfs(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, buffer[, options], 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.globSync(pattern[, options])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.mkdtempDisposableSync(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.statfsSync(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, buffer[, options])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.StatFs - Class:
fs.Utf8Stream- Event:
'close' - Event:
'drain' - Event:
'drop' - Event:
'error' - Event:
'finish' - Event:
'ready' - Event:
'write' new fs.Utf8Stream([options])utf8Stream.appendutf8Stream.contentModeutf8Stream.destroy()utf8Stream.end()utf8Stream.fdutf8Stream.fileutf8Stream.flush(callback)utf8Stream.flushSync()utf8Stream.fsyncutf8Stream.maxLengthutf8Stream.minLengthutf8Stream.mkdirutf8Stream.modeutf8Stream.periodicFlushutf8Stream.reopen(file)utf8Stream.syncutf8Stream.write(data)utf8Stream.writingutf8Stream[Symbol.dispose]()
- Event:
- Class:
fs.WriteStream fs.constants
- Class:
- Notes
- Global objects
__dirname__filename- Class:
AbortController - Class:
AbortSignal atob(data)- Class:
Blob - Class:
BroadcastChannel btoa(data)- Class:
Buffer - Class:
ByteLengthQueuingStrategy clearImmediate(immediateObject)clearInterval(intervalObject)clearTimeout(timeoutObject)- Class:
CloseEvent - Class:
CompressionStream console- Class:
CountQueuingStrategy - Class:
Crypto crypto- Class:
CryptoKey - Class:
CustomEvent - Class:
DecompressionStream - Class:
DOMException ErrorEvent- Class:
Event - Class:
EventSource - Class:
EventTarget exportsfetch- Class:
File - Class:
FormData global- Class:
Headers localStorage- Class:
MessageChannel - Class:
MessageEvent - Class:
MessagePort module- Class:
Navigator navigatorperformance- Class:
PerformanceEntry - Class:
PerformanceMark - Class:
PerformanceMeasure - Class:
PerformanceObserver - Class:
PerformanceObserverEntryList - Class:
PerformanceResourceTiming processqueueMicrotask(callback)- Class:
ReadableByteStreamController - Class:
ReadableStream - Class:
ReadableStreamBYOBReader - Class:
ReadableStreamBYOBRequest - Class:
ReadableStreamDefaultController - Class:
ReadableStreamDefaultReader - Class:
Request require()- Class:
Response sessionStoragesetImmediate(callback[, ...args])setInterval(callback, delay[, ...args])setTimeout(callback, delay[, ...args])- Class:
Storage structuredClone(value[, options])- Class:
SubtleCrypto - Class:
TextDecoder - Class:
TextDecoderStream - Class:
TextEncoder - Class:
TextEncoderStream - Class:
TransformStream - Class:
TransformStreamDefaultController - Class:
URL - Class:
URLPattern - Class:
URLSearchParams - Class:
WebAssembly - Class:
WebSocket - Class:
WritableStream - Class:
WritableStreamDefaultController - Class:
WritableStreamDefaultWriter
- HTTP
- Class:
http.Agent - Class:
http.ClientRequest- Event:
'abort' - Event:
'close' - Event:
'connect' - Event:
'continue' - Event:
'finish' - Event:
'information' - Event:
'response' - Event:
'socket' - Event:
'timeout' - Event:
'upgrade' request.abort()request.abortedrequest.connectionrequest.cork()request.end([data[, encoding]][, callback])request.destroy([error])request.finishedrequest.flushHeaders()request.getHeader(name)request.getHeaderNames()request.getHeaders()request.getRawHeaderNames()request.hasHeader(name)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.uncork()request.writableEndedrequest.writableFinishedrequest.write(chunk[, encoding][, callback])
- Event:
- Class:
http.Server- Event:
'checkContinue' - Event:
'checkExpectation' - Event:
'clientError' - Event:
'close' - Event:
'connect' - Event:
'connection' - Event:
'dropRequest' - Event:
'request' - Event:
'upgrade' server.close([callback])server.closeAllConnections()server.closeIdleConnections()server.headersTimeoutserver.listen()server.listeningserver.maxHeadersCountserver.requestTimeoutserver.setTimeout([msecs][, callback])server.maxRequestsPerSocketserver.timeoutserver.keepAliveTimeoutserver.keepAliveTimeoutBufferserver[Symbol.asyncDispose]()
- 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.strictContentLengthresponse.uncork()response.writableEndedresponse.writableFinishedresponse.write(chunk[, encoding][, callback])response.writeContinue()response.writeEarlyHints(hints[, callback])response.writeHead(statusCode[, statusMessage][, headers])response.writeProcessing()
- Event:
- Class:
http.IncomingMessage- Event:
'aborted' - Event:
'close' message.abortedmessage.completemessage.connectionmessage.destroy([error])message.headersmessage.headersDistinctmessage.httpVersionmessage.methodmessage.rawHeadersmessage.rawTrailersmessage.setTimeout(msecs[, callback])message.socketmessage.statusCodemessage.statusMessagemessage.trailersmessage.trailersDistinctmessage.url
- Event:
- Class:
http.OutgoingMessage- Event:
'drain' - Event:
'finish' - Event:
'prefinish' outgoingMessage.addTrailers(headers)outgoingMessage.appendHeader(name, value)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(name)outgoingMessage.setHeader(name, value)outgoingMessage.setHeaders(headers)outgoingMessage.setTimeout(msecs[, 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[, label])http.validateHeaderValue(name, value)http.setMaxIdleHTTPParsers(max)http.setGlobalProxyFromEnv([proxyEnv])- Class:
WebSocket - Built-in Proxy Support
- 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.performServerHandshake(socket[, options])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.appendHeader(name, value)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)response.reqresponse.sendDateresponse.setHeader(name, value)response.setTimeout(msecs[, callback])response.socketresponse.statusCoderesponse.statusMessageresponse.streamresponse.writableEndedresponse.write(chunk[, encoding][, callback])response.writeContinue()response.writeEarlyHints(hints)response.writeHead(statusCode[, statusMessage][, headers])
- Event:
- Collecting HTTP/2 performance metrics
- Note on
:authorityandhost
- HTTPS
- Inspector
- Promises API
- Callback API
- Common Objects
- Integration with DevTools
inspector.Network.dataReceived([params])inspector.Network.dataSent([params])inspector.Network.requestWillBeSent([params])inspector.Network.responseReceived([params])inspector.Network.loadingFinished([params])inspector.Network.loadingFailed([params])inspector.Network.webSocketCreated([params])inspector.Network.webSocketHandshakeResponseReceived([params])inspector.Network.webSocketClosed([params])inspector.NetworkResources.putinspector.DOMStorage.domStorageItemAddedinspector.DOMStorage.domStorageItemRemovedinspector.DOMStorage.domStorageItemUpdatedinspector.DOMStorage.domStorageItemsClearedinspector.DOMStorage.registerStorage
- Support of breakpoints
- Modules:
node:moduleAPI- The
Moduleobject - Module compile cache
- Customization Hooks
- Synchronous customization hooks
- Asynchronous customization hooks
- Caveats of asynchronous customization hooks
- Registration of asynchronous customization hooks
- Chaining of asynchronous customization hooks
- Communication with asynchronous module customization hooks
- Asynchronous hooks accepted by
module.register() initialize()- Asynchronous
resolve(specifier, context, nextResolve) - Asynchronous
load(url, context, nextLoad)
- Examples
- Source Map Support
- The
- Console
- Other versions
- Options
Console#
Stability: 2 - Stable
The node:console module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers.
The module exports two specific components:
- A
Consoleclass with methods such asconsole.log(),console.error(), andconsole.warn()that can be used to write to any Node.js stream. - A global
consoleinstance configured to write toprocess.stdoutandprocess.stderr. The globalconsolecan be used without callingrequire('node:console').
Warning: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. Programs that desire to depend on the synchronous / asynchronous behavior of the console functions should first figure out the nature of console's backing stream. This is because the stream is dependent on the underlying platform and standard stream configuration of the current process. See the note on process I/O for more information.
Example using the global console:
console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
Example using the Console class:
const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
Class: Console#
The Console class can be used to create a simple logger with configurable output streams and can be accessed using either require('node:console').Console or console.Console (or their destructured counterparts):
import { Console } from 'node:console';const { Console } = require('node:console');
const { Console } = console;
new Console(stdout[, stderr][, ignoreErrors])#
new Console(options)#
options<Object>stdout<stream.Writable>stderr<stream.Writable>ignoreErrors<boolean>Ignore errors when writing to the underlying streams. Default:true.colorMode<boolean>|<string>Set color support for thisConsoleinstance. Setting totrueenables coloring while inspecting values. Setting tofalsedisables coloring while inspecting values. Setting to'auto'makes color support depend on the value of theisTTYproperty and the value returned bygetColorDepth()on the respective stream. This option can not be used, ifinspectOptions.colorsis set as well. Default:'auto'.inspectOptions<Object>|<Map>Specifies options that are passed along toutil.inspect(). Can be an options object or, if different options for stdout and stderr are desired, aMapfrom stream objects to options.groupIndentation<number>Set group indentation. Default:2.
Creates a new Console with one or two writable stream instances. stdout is a writable stream to print log or info output. stderr is used for warning or error output. If stderr is not provided, stdout is used for stderr.
import { createWriteStream } from 'node:fs'; import { Console } from 'node:console'; // Alternatively // const { Console } = console; const output = createWriteStream('./stdout.log'); const errorOutput = createWriteStream('./stderr.log'); // Custom simple logger const logger = new Console({ stdout: output, stderr: errorOutput }); // use it like console const count = 5; logger.log('count: %d', count); // In stdout.log: count 5const fs = require('node:fs'); const { Console } = require('node:console'); // Alternatively // const { Console } = console; const output = fs.createWriteStream('./stdout.log'); const errorOutput = fs.createWriteStream('./stderr.log'); // Custom simple logger const logger = new Console({ stdout: output, stderr: errorOutput }); // use it like console const count = 5; logger.log('count: %d', count); // In stdout.log: count 5
The global console is a special Console whose output is sent to process.stdout and process.stderr. It is equivalent to calling:
new Console({ stdout: process.stdout, stderr: process.stderr });
console.assert(value[, ...message])#
value<any>The value tested for being truthy....message<any>All arguments besidesvalueare used as error message.
console.assert() writes a message if value is falsy or omitted. It only writes a message and does not otherwise affect execution. The output always starts with "Assertion failed". If provided, message is formatted using util.format().
If value is truthy, nothing happens.
console.assert(true, 'does nothing');
console.assert(false, 'Whoops %s work', 'didn\'t');
// Assertion failed: Whoops didn't work
console.assert();
// Assertion failed
console.clear()#
When stdout is a TTY, calling console.clear() will attempt to clear the TTY. When stdout is not a TTY, this method does nothing.
The specific operation of console.clear() can vary across operating systems and terminal types. For most Linux operating systems, console.clear() operates similarly to the clear shell command. On Windows, console.clear() will clear only the output in the current terminal viewport for the Node.js binary.
console.count([label])#
label<string>The display label for the counter. Default:'default'.
Maintains an internal counter specific to label and outputs to stdout the number of times console.count() has been called with the given label.
> console.count()
default: 1
undefined
> console.count('default')
default: 2
undefined
> console.count('abc')
abc: 1
undefined
> console.count('xyz')
xyz: 1
undefined
> console.count('abc')
abc: 2
undefined
> console.count()
default: 3
undefined
>
console.countReset([label])#
label<string>The display label for the counter. Default:'default'.
Resets the internal counter specific to label.
> console.count('abc');
abc: 1
undefined
> console.countReset('abc');
undefined
> console.count('abc');
abc: 1
undefined
>
console.debug(data[, ...args])#
The console.debug() function is an alias for console.log().
console.dir(obj[, options])#
obj<any>options<Object>showHidden<boolean>Iftruethen the object's non-enumerable and symbol properties will be shown too. Default:false.depth<number>Tellsutil.inspect()how many times to recurse while formatting the object. This is useful for inspecting large complicated objects. To make it recurse indefinitely, passnull. Default:2.colors<boolean>Iftrue, then the output will be styled with ANSI color codes. Colors are customizable; see customizingutil.inspect()colors. Default:false.
Uses util.inspect() on obj and prints the resulting string to stdout. This function bypasses any custom inspect() function defined on obj.
console.dirxml(...data)#
...data<any>
This method calls console.log() passing it the arguments received. This method does not produce any XML formatting.
console.error([data][, ...args])#
Prints to stderr with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to printf(3) (the arguments are all passed to util.format()).
const code = 5;
console.error('error #%d', code);
// Prints: error #5, to stderr
console.error('error', code);
// Prints: error 5, to stderr
If formatting elements (e.g. %d) are not found in the first string then util.inspect() is called on each argument and the resulting string values are concatenated. See util.format() for more information.
console.group([...label])#
...label<any>
Increases indentation of subsequent lines by spaces for groupIndentation length.
If one or more labels are provided, those are printed first without the additional indentation.
console.groupCollapsed()#
An alias for console.group().
console.groupEnd()#
Decreases indentation of subsequent lines by spaces for groupIndentation length.
console.info([data][, ...args])#
The console.info() function is an alias for console.log().
console.log([data][, ...args])#
Prints to stdout with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to printf(3) (the arguments are all passed to util.format()).
const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout
See util.format() for more information.
console.table(tabularData[, properties])#
tabularData<any>properties<string[]>Alternate properties for constructing the table.
Try to construct a table with the columns of the properties of tabularData (or use properties) and rows of tabularData and log it. Falls back to just logging the argument if it can't be parsed as tabular.
// These can't be parsed as tabular data
console.table(Symbol());
// Symbol()
console.table(undefined);
// undefined
console.table([{ a: 1, b: 'Y' }, { a: 'Z', b: 2 }]);
// ┌─────────┬─────┬─────┐
// │ (index) │ a │ b │
// ├─────────┼─────┼─────┤
// │ 0 │ 1 │ 'Y' │
// │ 1 │ 'Z' │ 2 │
// └─────────┴─────┴─────┘
console.table([{ a: 1, b: 'Y' }, { a: 'Z', b: 2 }], ['a']);
// ┌─────────┬─────┐
// │ (index) │ a │
// ├─────────┼─────┤
// │ 0 │ 1 │
// │ 1 │ 'Z' │
// └─────────┴─────┘
console.time([label])#
label<string>Default:'default'
Starts a timer that can be used to compute the duration of an operation. Timers are identified by a unique label. Use the same label when calling console.timeEnd() to stop the timer and output the elapsed time in suitable time units to stdout. For example, if the elapsed time is 3869ms, console.timeEnd() displays "3.869s".
console.timeEnd([label])#
label<string>Default:'default'
Stops a timer that was previously started by calling console.time() and prints the result to stdout:
console.time('bunch-of-stuff');
// Do a bunch of stuff.
console.timeEnd('bunch-of-stuff');
// Prints: bunch-of-stuff: 225.438ms
console.timeLog([label][, ...data])#
For a timer that was previously started by calling console.time(), prints the elapsed time and other data arguments to stdout:
console.time('process');
const value = expensiveProcess1(); // Returns 42
console.timeLog('process', value);
// Prints "process: 365.227ms 42".
doExpensiveProcess2(value);
console.timeEnd('process');
console.trace([message][, ...args])#
Prints to stderr the string 'Trace: ', followed by the util.format() formatted message and stack trace to the current position in the code.
console.trace('Show me');
// Prints: (stack trace will vary based on where trace is called)
// Trace: Show me
// at repl:2:9
// at REPLServer.defaultEval (repl.js:248:27)
// at bound (domain.js:287:14)
// at REPLServer.runBound [as eval] (domain.js:300:12)
// at REPLServer.<anonymous> (repl.js:412:12)
// at emitOne (events.js:82:20)
// at REPLServer.emit (events.js:169:7)
// at REPLServer.Interface._onLine (readline.js:210:10)
// at REPLServer.Interface._line (readline.js:549:8)
// at REPLServer.Interface._ttyWrite (readline.js:826:14)
console.warn([data][, ...args])#
The console.warn() function is an alias for console.error().
Inspector only methods#
The following methods are exposed by the V8 engine in the general API but do not display anything unless used in conjunction with the inspector (--inspect flag).
console.profile([label])#
label<string>
This method does not display anything unless used in the inspector. The console.profile() method starts a JavaScript CPU profile with an optional label until console.profileEnd() is called. The profile is then added to the Profile panel of the inspector.
console.profile('MyLabel');
// Some code
console.profileEnd('MyLabel');
// Adds the profile 'MyLabel' to the Profiles panel of the inspector.
console.profileEnd([label])#
label<string>
This method does not display anything unless used in the inspector. Stops the current JavaScript CPU profiling session if one has been started and prints the report to the Profiles panel of the inspector. See console.profile() for an example.
If this method is called without a label, the most recently started profile is stopped.
console.timeStamp([label])#
label<string>
This method does not display anything unless used in the inspector. The console.timeStamp() method adds an event with the label 'label' to the Timeline panel of the inspector.
Crypto#
Stability: 2 - Stable
The node:crypto module provides cryptographic functionality that includes a set of wrappers for OpenSSL's hash, HMAC, cipher, decipher, sign, and verify functions.
const { createHmac } = await import('node:crypto'); const secret = 'abcdefg'; const hash = createHmac('sha256', secret) .update('I love cupcakes') .digest('hex'); console.log(hash); // Prints: // c0fa1bc00531bd78ef38c628449c5102aeabd49b5dc3a2a516ea6ea959d6658econst { createHmac } = require('node:crypto'); const secret = 'abcdefg'; const hash = createHmac('sha256', secret) .update('I love cupcakes') .digest('hex'); console.log(hash); // Prints: // c0fa1bc00531bd78ef38c628449c5102aeabd49b5dc3a2a516ea6ea959d6658e
Determining if crypto support is unavailable#
It is possible for Node.js to be built without including support for the node:crypto module. In such cases, attempting to import from crypto or calling require('node:crypto') will result in an error being thrown.
When using CommonJS, the error thrown can be caught using try/catch:
let crypto;
try {
crypto = require('node:crypto');
} catch (err) {
console.error('crypto support is disabled!');
}
When using the lexical ESM import keyword, the error can only be caught if a handler for process.on('uncaughtException') is registered before any attempt to load the module is made (using, for instance, a preload module).
When using ESM, if there is a chance that the code may be run on a build of Node.js where crypto support is not enabled, consider using the import() function instead of the lexical import keyword:
let crypto;
try {
crypto = await import('node:crypto');
} catch (err) {
console.error('crypto support is disabled!');
}
Asymmetric key types#
The following table lists the asymmetric key types recognized by the KeyObject API:
| Key Type | Description | OID |
|---|---|---|
'dh' | Diffie-Hellman | 1.2.840.113549.1.3.1 |
'dsa' | DSA | 1.2.840.10040.4.1 |
'ec' | Elliptic curve | 1.2.840.10045.2.1 |
'ed25519' | Ed25519 | 1.3.101.112 |
'ed448' | Ed448 | 1.3.101.113 |
'ml-dsa-44'1 | ML-DSA-44 | 2.16.840.1.101.3.4.3.17 |
'ml-dsa-65'1 | ML-DSA-65 | 2.16.840.1.101.3.4.3.18 |
'ml-dsa-87'1 | ML-DSA-87 | 2.16.840.1.101.3.4.3.19 |
'ml-kem-512'1 | ML-KEM-512 | 2.16.840.1.101.3.4.4.1 |
'ml-kem-768'1 | ML-KEM-768 | 2.16.840.1.101.3.4.4.2 |
'ml-kem-1024'1 | ML-KEM-1024 | 2.16.840.1.101.3.4.4.3 |
'rsa-pss' | RSA PSS | 1.2.840.113549.1.1.10 |
'rsa' | RSA | 1.2.840.113549.1.1.1 |
'slh-dsa-sha2-128f'1 | SLH-DSA-SHA2-128f | 2.16.840.1.101.3.4.3.21 |
'slh-dsa-sha2-128s'1 | SLH-DSA-SHA2-128s | 2.16.840.1.101.3.4.3.20 |
'slh-dsa-sha2-192f'1 | SLH-DSA-SHA2-192f | 2.16.840.1.101.3.4.3.23 |
'slh-dsa-sha2-192s'1 | SLH-DSA-SHA2-192s | 2.16.840.1.101.3.4.3.22 |
'slh-dsa-sha2-256f'1 | SLH-DSA-SHA2-256f | 2.16.840.1.101.3.4.3.25 |
'slh-dsa-sha2-256s'1 | SLH-DSA-SHA2-256s | 2.16.840.1.101.3.4.3.24 |
'slh-dsa-shake-128f'1 | SLH-DSA-SHAKE-128f | 2.16.840.1.101.3.4.3.27 |
'slh-dsa-shake-128s'1 | SLH-DSA-SHAKE-128s | 2.16.840.1.101.3.4.3.26 |
'slh-dsa-shake-192f'1 | SLH-DSA-SHAKE-192f | 2.16.840.1.101.3.4.3.29 |
'slh-dsa-shake-192s'1 | SLH-DSA-SHAKE-192s | 2.16.840.1.101.3.4.3.28 |
'slh-dsa-shake-256f'1 | SLH-DSA-SHAKE-256f | 2.16.840.1.101.3.4.3.31 |
'slh-dsa-shake-256s'1 | SLH-DSA-SHAKE-256s | 2.16.840.1.101.3.4.3.30 |
'x25519' | X25519 | 1.3.101.110 |
'x448' | X448 | 1.3.101.111 |
Class: Certificate#
SPKAC is a Certificate Signing Request mechanism originally implemented by Netscape and was specified formally as part of HTML5's keygen element.
<keygen> is deprecated since HTML 5.2 and new projects should not use this element anymore.
The node:crypto module provides the Certificate class for working with SPKAC data. The most common usage is handling output generated by the HTML5 <keygen> element. Node.js uses OpenSSL's SPKAC implementation internally.
Static method: Certificate.exportChallenge(spkac[, encoding])#
spkac<string>|<ArrayBuffer>|<Buffer>|<TypedArray>|<DataView>encoding<string>The encoding of thespkacstring.- Returns:
<Buffer>The challenge component of thespkacdata structure, which includes a public key and a challenge.
const { Certificate } = await import('node:crypto'); const spkac = getSpkacSomehow(); const challenge = Certificate.exportChallenge(spkac); console.log(challenge.toString('utf8')); // Prints: the challenge as a UTF8 stringconst { Certificate } = require('node:crypto'); const spkac = getSpkacSomehow(); const challenge = Certificate.exportChallenge(spkac); console.log(challenge.toString('utf8')); // Prints: the challenge as a UTF8 string
Static method: Certificate.exportPublicKey(spkac[, encoding])#
spkac<string>|<ArrayBuffer>|<Buffer>|<TypedArray>|<DataView>encoding<string>The encoding of thespkacstring.- Returns:
<Buffer>The public key component of thespkacdata structure, which includes a public key and a challenge.
const { Certificate } = await import('node:crypto'); const spkac = getSpkacSomehow(); const publicKey = Certificate.exportPublicKey(spkac); console.log(publicKey); // Prints: the public key as <Buffer ...>const { Certificate } = require('node:crypto'); const spkac = getSpkacSomehow(); const publicKey = Certificate.exportPublicKey(spkac); console.log(publicKey); // Prints: the public key as <Buffer ...>
Static method: Certificate.verifySpkac(spkac[, encoding])#
spkac<string>|<ArrayBuffer>|<Buffer>|<TypedArray>|<DataView>encoding<string>The encoding of thespkacstring.- Returns:
<boolean>trueif the givenspkacdata structure is valid,falseotherwise.
import { Buffer } from 'node:buffer'; const { Certificate } = await import('node:crypto'); const spkac = getSpkacSomehow(); console.log(Certificate.verifySpkac(Buffer.from(spkac))); // Prints: true or falseconst { Buffer } = require('node:buffer'); const { Certificate } = require('node:crypto'); const spkac = getSpkacSomehow(); console.log(Certificate.verifySpkac(Buffer.from(spkac))); // Prints: true or false
Legacy API#
Stability: 0 - Deprecated
As a legacy interface, it is possible to create new instances of the crypto.Certificate class as illustrated in the examples below.
new crypto.Certificate()#
Instances of the Certificate class can be created using the new keyword or by calling crypto.Certificate() as a function:
const { Certificate } = await import('node:crypto'); const cert1 = new Certificate(); const cert2 = Certificate();const { Certificate } = require('node:crypto'); const cert1 = new Certificate(); const cert2 = Certificate();
certificate.exportChallenge(spkac[, encoding])#
spkac<string>|<ArrayBuffer>|<Buffer>|<TypedArray>|<DataView>encoding<string>The encoding of thespkacstring.- Returns:
<Buffer>The challenge component of thespkacdata structure, which includes a public key and a challenge.
const { Certificate } = await import('node:crypto'); const cert = Certificate(); const spkac = getSpkacSomehow(); const challenge = cert.exportChallenge(spkac); console.log(challenge.toString('utf8')); // Prints: the challenge as a UTF8 stringconst { Certificate } = require('node:crypto'); const cert = Certificate(); const spkac = getSpkacSomehow(); const challenge = cert.exportChallenge(spkac); console.log(challenge.toString('utf8')); // Prints: the challenge as a UTF8 string
certificate.exportPublicKey(spkac[, encoding])#
spkac<string>|<ArrayBuffer>|<Buffer>|<TypedArray>|<DataView>encoding<string>The encoding of thespkacstring.- Returns:
<Buffer>The public key component of thespkacdata structure, which includes a public key and a challenge.
const { Certificate } = await import('node:crypto'); const cert = Certificate(); const spkac = getSpkacSomehow(); const publicKey = cert.exportPublicKey(spkac); console.log(publicKey); // Prints: the public key as <Buffer ...>const { Certificate } = require('node:crypto'); const cert = Certificate(); const spkac = getSpkacSomehow(); const publicKey = cert.exportPublicKey(spkac); console.log(publicKey); // Prints: the public key as <Buffer ...>
certificate.verifySpkac(spkac[, encoding])#
spkac<string>|<ArrayBuffer>|<Buffer>|<TypedArray>|<DataView>encoding<string>The encoding of thespkacstring.- Returns:
<boolean>trueif the givenspkacdata structure is valid,falseotherwise.
import { Buffer } from 'node:buffer'; const { Certificate } = await import('node:crypto'); const cert = Certificate(); const spkac = getSpkacSomehow(); console.log(cert.verifySpkac(Buffer.from(spkac))); // Prints: true or falseconst { Buffer } = require('node:buffer'); const { Certificate } = require('node:crypto'); const cert = Certificate(); const spkac = getSpkacSomehow(); console.log(cert.verifySpkac(Buffer.from(spkac))); // Prints: true or false
Class: Cipheriv#
- Extends:
<stream.Transform>
Instances of the Cipheriv class are used to encrypt data. The class can be used in one of two ways:
- As a stream that is both readable and writable, where plain unencrypted data is written to produce encrypted data on the readable side, or
- Using the
cipher.update()andcipher.final()methods to produce the encrypted data.
The crypto.createCipheriv() method is used to create Cipheriv instances. Cipheriv objects are not to be created directly using the new keyword.
Example: Using Cipheriv objects as streams:
const { scrypt, randomFill, createCipheriv, } = await import('node:crypto'); const algorithm = 'aes-192-cbc'; const password = 'Password used to generate key'; // First, we'll generate the key. The key length is dependent on the algorithm. // In this case for aes192, it is 24 bytes (192 bits). scrypt(password, 'salt', 24, (err, key) => { if (err) throw err; // Then, we'll generate a random initialization vector randomFill(new Uint8Array(16), (err, iv) => { if (err) throw err; // Once we have the key and iv, we can create and use the cipher... const cipher = createCipheriv(algorithm, key, iv); let encrypted = ''; cipher.setEncoding('hex'); cipher.on('data', (chunk) => encrypted += chunk); cipher.on('end', () => console.log(encrypted)); cipher.write('some clear text data'); cipher.end(); }); });const { scrypt, randomFill, createCipheriv, } = require('node:crypto'); const algorithm = 'aes-192-cbc'; const password = 'Password used to generate key'; // First, we'll generate the key. The key length is dependent on the algorithm. // In this case for aes192, it is 24 bytes (192 bits). scrypt(password, 'salt', 24, (err, key) => { if (err) throw err; // Then, we'll generate a random initialization vector randomFill(new Uint8Array(16), (err, iv) => { if (err) throw err; // Once we have the key and iv, we can create and use the cipher... const cipher = createCipheriv(algorithm, key, iv); let encrypted = ''; cipher.setEncoding('hex'); cipher.on('data', (chunk) => encrypted += chunk); cipher.on('end', () => console.log(encrypted)); cipher.write('some clear text data'); cipher.end(); }); });
Example: Using Cipheriv and piped streams:
import { createReadStream, createWriteStream, } from 'node:fs'; import { pipeline, } from 'node:stream'; const { scrypt, randomFill, createCipheriv, } = await import('node:crypto'); const algorithm = 'aes-192-cbc'; const password = 'Password used to generate key'; // First, we'll generate the key. The key length is dependent on the algorithm. // In this case for aes192, it is 24 bytes (192 bits). scrypt(password, 'salt', 24, (err, key) => { if (err) throw err; // Then, we'll generate a random initialization vector randomFill(new Uint8Array(16), (err, iv) => { if (err) throw err; const cipher = createCipheriv(algorithm, key, iv); const input = createReadStream('test.js'); const output = createWriteStream('test.enc'); pipeline(input, cipher, output, (err) => { if (err) throw err; }); }); });const { createReadStream, createWriteStream, } = require('node:fs'); const { pipeline, } = require('node:stream'); const { scrypt, randomFill, createCipheriv, } = require('node:crypto'); const algorithm = 'aes-192-cbc'; const password = 'Password used to generate key'; // First, we'll generate the key. The key length is dependent on the algorithm. // In this case for aes192, it is 24 bytes (192 bits). scrypt(password, 'salt', 24, (err, key) => { if (err) throw err; // Then, we'll generate a random initialization vector randomFill(new Uint8Array(16), (err, iv) => { if (err) throw err; const cipher = createCipheriv(algorithm, key, iv); const input = createReadStream('test.js'); const output = createWriteStream('test.enc'); pipeline(input, cipher, output, (err) => { if (err) throw err; }); }); });
Example: Using the cipher.update() and cipher.final() methods:
const { scrypt, randomFill, createCipheriv, } = await import('node:crypto'); const algorithm = 'aes-192-cbc'; const password = 'Password used to generate key'; // First, we'll generate the key. The key length is dependent on the algorithm. // In this case for aes192, it is 24 bytes (192 bits). scrypt(password, 'salt', 24, (err, key) => { if (err) throw err; // Then, we'll generate a random initialization vector randomFill(new Uint8Array(16), (err, iv) => { if (err) throw err; const cipher = createCipheriv(algorithm, key, iv); let encrypted = cipher.update('some clear text data', 'utf8', 'hex'); encrypted += cipher.final('hex'); console.log(encrypted); }); });const { scrypt, randomFill, createCipheriv, } = require('node:crypto'); const algorithm = 'aes-192-cbc'; const password = 'Password used to generate key'; // First, we'll generate the key. The key length is dependent on the algorithm. // In this case for aes192, it is 24 bytes (192 bits). scrypt(password, 'salt', 24, (err, key) => { if (err) throw err; // Then, we'll generate a random initialization vector randomFill(new Uint8Array(16), (err, iv) => { if (err) throw err; const cipher = createCipheriv(algorithm, key, iv); let encrypted = cipher.update('some clear text data', 'utf8', 'hex'); encrypted += cipher.final('hex'); console.log(encrypted); }); });
cipher.final([outputEncoding])#
outputEncoding<string>The encoding of the return value.- Returns:
<Buffer>|<string>Any remaining enciphered contents. IfoutputEncodingis specified, a string is returned. If anoutputEncodingis not provided, aBufferis returned.
Once the cipher.final() method has been called, the Cipheriv object can no longer be used to encrypt data. Attempts to call cipher.final() more than once will result in an error being thrown.
cipher.getAuthTag()#
- Returns:
<Buffer>When using an authenticated encryption mode (GCM,CCM,OCB, andchacha20-poly1305are currently supported), thecipher.getAuthTag()method returns aBuffercontaining the authentication tag that has been computed from the given data.
The cipher.getAuthTag() method should only be called after encryption has been completed using the cipher.final() method.
If the authTagLength option was set during the cipher instance's creation, this function will return exactly authTagLength bytes.
cipher.setAAD(buffer[, options])#
buffer<string>|<ArrayBuffer>|<Buffer>|<TypedArray>|<DataView>options<Object>stream.transformoptions- Returns:
<Cipheriv>The sameCipherivinstance for method chaining.
When using an authenticated encryption mode (GCM, CCM, OCB, and chacha20-poly1305 are currently supported), the cipher.setAAD() method sets the value used for the additional authenticated data (AAD) input parameter.
The plaintextLength option is optional for GCM and OCB. When using CCM, the plaintextLength option must be specified and its value must match the length of the plaintext in bytes. See CCM mode.
The cipher.setAAD() method must be called before cipher.update().
cipher.setAutoPadding([autoPadding])#
autoPadding<boolean>Default:true- Returns:
<Cipheriv>The sameCipherivinstance for method chaining.
When using block encryption algorithms, the Cipheriv class will automatically add padding to the input data to the appropriate block size. To disable the default padding call cipher.setAutoPadding(false).
When autoPadding is false, the length of the entire input data must be a multiple of the cipher's block size or cipher.final() will throw an error. Disabling automatic padding is useful for non-standard padding, for instance using 0x0 instead of PKCS padding.
The cipher.setAutoPadding() method must be called before cipher.final().
cipher.update(data[, inputEncoding][, outputEncoding])#
data<string>|<Buffer>|<TypedArray>|<DataView>inputEncoding<string>The encoding of the data.outputEncoding<string>The encoding of the return value.- Returns:
<Buffer>|<string>
Updates the cipher with data. If the inputEncoding argument is given, the data argument is a string using the specified encoding. If the inputEncoding argument is not given, data must be a Buffer, TypedArray, or DataView. If data is a Buffer, TypedArray, or DataView, then inputEncoding is ignored.
The outputEncoding specifies the output format of the enciphered data. If the outputEncoding is specified, a string using the specified encoding is returned. If no outputEncoding is provided, a Buffer is returned.
The cipher.update() method can be called multiple times with new data until cipher.final() is called. Calling cipher.update() after cipher.final() will result in an error being thrown.
Class: Decipheriv#
- Extends:
<stream.Transform>
Instances of the Decipheriv class are used to decrypt data. The class can be used in one of two ways:
- As a stream that is both readable and writable, where plain encrypted data is written to produce unencrypted data on the readable side, or
- Using the
decipher.update()anddecipher.final()methods to produce the unencrypted data.
The crypto.createDecipheriv() method is used to create Decipheriv instances. Decipheriv objects are not to be created directly using the new keyword.
Example: Using Decipheriv objects as streams:
import { Buffer } from 'node:buffer'; const { scryptSync, createDecipheriv, } = await import('node:crypto'); const algorithm = 'aes-192-cbc'; const password = 'Password used to generate key'; // Key length is dependent on the algorithm. In this case for aes192, it is // 24 bytes (192 bits). // Use the async `crypto.scrypt()` instead. const key = scryptSync(password, 'salt', 24); // The IV is usually passed along with the ciphertext. const iv = Buffer.alloc(16, 0); // Initialization vector. const decipher = createDecipheriv(algorithm, key, iv); let decrypted = ''; decipher.on('readable', () => { let chunk; while (null !== (chunk = decipher.read())) { decrypted += chunk.toString('utf8'); } }); decipher.on('end', () => { console.log(decrypted); // Prints: some clear text data }); // Encrypted with same algorithm, key and iv. const encrypted = 'e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa'; decipher.write(encrypted, 'hex'); decipher.end();const { scryptSync, createDecipheriv, } = require('node:crypto'); const { Buffer } = require('node:buffer'); const algorithm = 'aes-192-cbc'; const password = 'Password used to generate key'; // Key length is dependent on the algorithm. In this case for aes192, it is // 24 bytes (192 bits). // Use the async `crypto.scrypt()` instead. const key = scryptSync(password, 'salt', 24); // The IV is usually passed along with the ciphertext. const iv = Buffer.alloc(16, 0); // Initialization vector. const decipher = createDecipheriv(algorithm, key, iv); let decrypted = ''; decipher.on('readable', () => { let chunk; while (null !== (chunk = decipher.read())) { decrypted += chunk.toString('utf8'); } }); decipher.on('end', () => { console.log(decrypted); // Prints: some clear text data }); // Encrypted with same algorithm, key and iv. const encrypted = 'e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa'; decipher.write(encrypted, 'hex'); decipher.end();
Example: Using Decipheriv and piped streams:
import { createReadStream, createWriteStream, } from 'node:fs'; import { Buffer } from 'node:buffer'; const { scryptSync, createDecipheriv, } = await import('node:crypto'); const algorithm = 'aes-192-cbc'; const password = 'Password used to generate key'; // Use the async `crypto.scrypt()` instead. const key = scryptSync(password, 'salt', 24); // The IV is usually passed along with the ciphertext. const iv = Buffer.alloc(16, 0); // Initialization vector. const decipher = createDecipheriv(algorithm, key, iv); const input = createReadStream('test.enc'); const output = createWriteStream('test.js'); input.pipe(decipher).pipe(output);const { createReadStream, createWriteStream, } = require('node:fs'); const { scryptSync, createDecipheriv, } = require('node:crypto'); const { Buffer } = require('node:buffer'); const algorithm = 'aes-192-cbc'; const password = 'Password used to generate key'; // Use the async `crypto.scrypt()` instead. const key = scryptSync(password, 'salt', 24); // The IV is usually passed along with the ciphertext. const iv = Buffer.alloc(16, 0); // Initialization vector. const decipher = createDecipheriv(algorithm, key, iv); const input = createReadStream('test.enc'); const output = createWriteStream('test.js'); input.pipe(decipher).pipe(output);
Example: Using the decipher.update() and decipher.final() methods:
import { Buffer } from 'node:buffer'; const { scryptSync, createDecipheriv, } = await import('node:crypto'); const algorithm = 'aes-192-cbc'; const password = 'Password used to generate key'; // Use the async `crypto.scrypt()` instead. const key = scryptSync(password, 'salt', 24); // The IV is usually passed along with the ciphertext. const iv = Buffer.alloc(16, 0); // Initialization vector. const decipher = createDecipheriv(algorithm, key, iv); // Encrypted using same algorithm, key and iv. const encrypted = 'e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa'; let decrypted = decipher.update(encrypted, 'hex', 'utf8'); decrypted += decipher.final('utf8'); console.log(decrypted); // Prints: some clear text dataconst { scryptSync, createDecipheriv, } = require('node:crypto'); const { Buffer } = require('node:buffer'); const algorithm = 'aes-192-cbc'; const password = 'Password used to generate key'; // Use the async `crypto.scrypt()` instead. const key = scryptSync(password, 'salt', 24); // The IV is usually passed along with the ciphertext. const iv = Buffer.alloc(16, 0); // Initialization vector. const decipher = createDecipheriv(algorithm, key, iv); // Encrypted using same algorithm, key and iv. const encrypted = 'e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa'; let decrypted = decipher.update(encrypted, 'hex', 'utf8'); decrypted += decipher.final('utf8'); console.log(decrypted); // Prints: some clear text data
decipher.final([outputEncoding])#
outputEncoding<string>The encoding of the return value.- Returns:
<Buffer>|<string>Any remaining deciphered contents. IfoutputEncodingis specified, a string is returned. If anoutputEncodingis not provided, aBufferis returned.
Once the decipher.final() method has been called, the Decipheriv object can no longer be used to decrypt data. Attempts to call decipher.final() more than once will result in an error being thrown.
decipher.setAAD(buffer[, options])#
buffer<string>|<ArrayBuffer>|<Buffer>|<TypedArray>|<DataView>options<Object>stream.transformoptions- Returns:
<Decipheriv>The same Decipher for method chaining.
When using an authenticated encryption mode (GCM, CCM, OCB, and chacha20-poly1305 are currently supported), the decipher.setAAD() method sets the value used for the additional authenticated data (AAD) input parameter.
The options argument is optional for GCM. When using CCM, the plaintextLength option must be specified and its value must match the length of the ciphertext in bytes. See CCM mode.
The decipher.setAAD() method must be called before decipher.update().
When passing a string as the buffer, please consider caveats when using strings as inputs to cryptographic APIs.
decipher.setAuthTag(buffer[, encoding])#
buffer<string>|<Buffer>|<ArrayBuffer>|<TypedArray>|<DataView>encoding<string>String encoding to use whenbufferis a string.- Returns:
<Decipheriv>The same Decipher for method chaining.
When using an authenticated encryption mode (GCM, CCM, OCB, and chacha20-poly1305 are currently supported), the decipher.setAuthTag() method is used to pass in the received authentication tag. If no tag is provided, or if the cipher text has been tampered with, decipher.final() will throw, indicating that the cipher text should be discarded due to failed authentication. If the tag length is invalid according to NIST SP 800-38D or does not match the value of the authTagLength option, decipher.setAuthTag() will throw an error.
The decipher.setAuthTag() method must be called before decipher.update() for CCM mode or before decipher.final() for GCM and OCB modes and chacha20-poly1305. decipher.setAuthTag() can only be called once.
When passing a string as the authentication tag, please consider caveats when using strings as inputs to cryptographic APIs.
decipher.setAutoPadding([autoPadding])#
autoPadding<boolean>Default:true- Returns:
<Decipheriv>The same Decipher for method chaining.
When data has been encrypted without standard block padding, calling decipher.setAutoPadding(false) will disable automatic padding to prevent decipher.final() from checking for and removing padding.
Turning auto padding off will only work if the input data's length is a multiple of the ciphers block size.
The decipher.setAutoPadding() method must be called before decipher.final().
decipher.update(data[, inputEncoding][, outputEncoding])#
data<string>|<Buffer>|<TypedArray>|<DataView>inputEncoding<string>The encoding of thedatastring.outputEncoding<string>The encoding of the return value.- Returns:
<Buffer>|<string>
Updates the decipher with data. If the inputEncoding argument is given, the data argument is a string using the specified encoding. If the inputEncoding argument is not given, data must be a Buffer. If data is a Buffer then inputEncoding is ignored.
The outputEncoding specifies the output format of the enciphered data. If the outputEncoding is specified, a string using the specified encoding is returned. If no outputEncoding is provided, a Buffer is returned.
The decipher.update() method can be called multiple times with new data until decipher.final() is called. Calling decipher.update() after decipher.final() will result in an error being thrown.
Even if the underlying cipher implements authentication, the authenticity and integrity of the plaintext returned from this function may be uncertain at this time. For authenticated encryption algorithms, authenticity is generally only established when the application calls decipher.final().
Class: DiffieHellman#
The DiffieHellman class is a utility for creating Diffie-Hellman key exchanges.
Instances of the DiffieHellman class can be created using the crypto.createDiffieHellman() function.
import assert from 'node:assert'; const { createDiffieHellman, } = await import('node:crypto'); // Generate Alice's keys... const alice = createDiffieHellman(2048); const aliceKey = alice.generateKeys(); // Generate Bob's keys... const bob = createDiffieHellman(alice.getPrime(), alice.getGenerator()); const bobKey = bob.generateKeys(); // Exchange and generate the secret... const aliceSecret = alice.computeSecret(bobKey); const bobSecret = bob.computeSecret(aliceKey); // OK assert.strictEqual(aliceSecret.toString('hex'), bobSecret.toString('hex'));const assert = require('node:assert'); const { createDiffieHellman, } = require('node:crypto'); // Generate Alice's keys... const alice = createDiffieHellman(2048); const aliceKey = alice.generateKeys(); // Generate Bob's keys... const bob = createDiffieHellman(alice.getPrime(), alice.getGenerator()); const bobKey = bob.generateKeys(); // Exchange and generate the secret... const aliceSecret = alice.computeSecret(bobKey); const bobSecret = bob.computeSecret(aliceKey); // OK assert.strictEqual(aliceSecret.toString('hex'), bobSecret.toString('hex'));
diffieHellman.computeSecret(otherPublicKey[, inputEncoding][, outputEncoding])#
otherPublicKey<string>|<ArrayBuffer>|<Buffer>|<TypedArray>|<DataView>inputEncoding<string>The encoding of anotherPublicKeystring.outputEncoding<string>The encoding of the return value.- Returns:
<Buffer>|<string>
Computes the shared secret using otherPublicKey as the other party's public key and returns the computed shared secret. The supplied key is interpreted using the specified inputEncoding, and secret is encoded using specified outputEncoding. If the inputEncoding is not provided, otherPublicKey is expected to be a Buffer, TypedArray, or DataView.
If outputEncoding is given a string is returned; otherwise, a Buffer is returned.
diffieHellman.generateKeys([encoding])#
Generates private and public Diffie-Hellman key values unless they have been generated or computed already, and returns the public key in the specified encoding. This key should be transferred to the other party. If encoding is provided a string is returned; otherwise a Buffer is returned.
This function is a thin wrapper around DH_generate_key(). In particular, once a private key has been generated or set, calling this function only updates the public key but does not generate a new private key.
diffieHellman.getGenerator([encoding])#
Returns the Diffie-Hellman generator in the specified encoding. If encoding is provided a string is returned; otherwise a Buffer is returned.
diffieHellman.getPrime([encoding])#
Returns the Diffie-Hellman prime in the specified encoding. If encoding is provided a string is returned; otherwise a Buffer is returned.
diffieHellman.getPrivateKey([encoding])#
Returns the Diffie-Hellman private key in the specified encoding. If encoding is provided a string is returned; otherwise a Buffer is returned.
diffieHellman.getPublicKey([encoding])#
Returns the Diffie-Hellman public key in the specified encoding. If encoding is provided a string is returned; otherwise a Buffer is returned.
diffieHellman.setPrivateKey(privateKey[, encoding])#
privateKey<string>|<ArrayBuffer>|<Buffer>|<TypedArray>|<DataView>encoding<string>The encoding of theprivateKeystring.
Sets the Diffie-Hellman private key. If the encoding argument is provided, privateKey is expected to be a string. If no encoding is provided, privateKey is expected to be a Buffer, TypedArray, or DataView.
This function does not automatically compute the associated public key. Either diffieHellman.setPublicKey() or diffieHellman.generateKeys() can be used to manually provide the public key or to automatically derive it.
diffieHellman.setPublicKey(publicKey[, encoding])#
publicKey<string>|<ArrayBuffer>|<Buffer>|<TypedArray>|<DataView>encoding<string>The encoding of thepublicKeystring.
Sets the Diffie-Hellman public key. If the encoding argument is provided, publicKey is expected to be a string. If no encoding is provided, publicKey is expected to be a Buffer, TypedArray, or DataView.
diffieHellman.verifyError#
A bit field containing any warnings and/or errors resulting from a check performed during initialization of the DiffieHellman object.
The following values are valid for this property (as defined in node:constants module):
DH_CHECK_P_NOT_SAFE_PRIMEDH_CHECK_P_NOT_PRIMEDH_UNABLE_TO_CHECK_GENERATORDH_NOT_SUITABLE_GENERATOR
Class: DiffieHellmanGroup#
The DiffieHellmanGroup class takes a well-known modp group as its argument. It works the same as DiffieHellman, except that it does not allow changing its keys after creation. In other words, it does not implement setPublicKey() or setPrivateKey() methods.
const { createDiffieHellmanGroup } = await import('node:crypto'); const dh = createDiffieHellmanGroup('modp16');const { createDiffieHellmanGroup } = require('node:crypto'); const dh = createDiffieHellmanGroup('modp16');
The following groups are supported:
'modp14'(2048 bits, RFC 3526 Section 3)'modp15'(3072 bits, RFC 3526 Section 4)'modp16'(4096 bits, RFC 3526 Section 5)'modp17'(6144 bits, RFC 3526 Section 6)'modp18'(8192 bits, RFC 3526 Section 7)
The following groups are still supported but deprecated (see Caveats):
'modp1'(768 bits, RFC 2409 Section 6.1)'modp2'(1024 bits, RFC 2409 Section 6.2)'modp5'(1536 bits, RFC 3526 Section 2)
These deprecated groups might be removed in future versions of Node.js.
Class: ECDH#
The ECDH class is a utility for creating Elliptic Curve Diffie-Hellman (ECDH) key exchanges.
Instances of the ECDH class can be created using the crypto.createECDH() function.
import assert from 'node:assert'; const { createECDH, } = await import('node:crypto'); // Generate Alice's keys... const alice = createECDH('secp521r1'); const aliceKey = alice.generateKeys(); // Generate Bob's keys... const bob = createECDH('secp521r1'); const bobKey = bob.generateKeys(); // Exchange and generate the secret... const aliceSecret = alice.computeSecret(bobKey); const bobSecret = bob.computeSecret(aliceKey); assert.strictEqual(aliceSecret.toString('hex'), bobSecret.toString('hex')); // OKconst assert = require('node:assert'); const { createECDH, } = require('node:crypto'); // Generate Alice's keys... const alice = createECDH('secp521r1'); const aliceKey = alice.generateKeys(); // Generate Bob's keys... const bob = createECDH('secp521r1'); const bobKey = bob.generateKeys(); // Exchange and generate the secret... const aliceSecret = alice.computeSecret(bobKey); const bobSecret = bob.computeSecret(aliceKey); assert.strictEqual(aliceSecret.toString('hex'), bobSecret.toString('hex')); // OK
Static method: ECDH.convertKey(key, curve[, inputEncoding[, outputEncoding[, format]]])#
key<string>|<ArrayBuffer>|<Buffer>|<TypedArray>|<DataView>curve<string>inputEncoding<string>The encoding of thekeystring.outputEncoding<string>The encoding of the return value.format<string>Default:'uncompressed'- Returns:
<Buffer>|<string>
Converts the EC Diffie-Hellman public key specified by key and curve to the format specified by format. The format argument specifies point encoding and can be 'compressed', 'uncompressed' or 'hybrid'. The supplied key is interpreted using the specified inputEncoding, and the returned key is encoded using the specified outputEncoding.
Use crypto.getCurves() to obtain a list of available curve names. On recent OpenSSL releases, openssl ecparam -list_curves will also display the name and description of each available elliptic curve.
If format is not specified the point will be returned in 'uncompressed' format.
If the inputEncoding is not provided, key is expected to be a Buffer, TypedArray, or DataView.
Example (uncompressing a key):
const { createECDH, ECDH, } = await import('node:crypto'); const ecdh = createECDH('secp256k1'); ecdh.generateKeys(); const compressedKey = ecdh.getPublicKey('hex', 'compressed'); const uncompressedKey = ECDH.convertKey(compressedKey, 'secp256k1', 'hex', 'hex', 'uncompressed'); // The converted key and the uncompressed public key should be the same console.log(uncompressedKey === ecdh.getPublicKey('hex'));const { createECDH, ECDH, } = require('node:crypto'); const ecdh = createECDH('secp256k1'); ecdh.generateKeys(); const compressedKey = ecdh.getPublicKey('hex', 'compressed'); const uncompressedKey = ECDH.convertKey(compressedKey, 'secp256k1', 'hex', 'hex', 'uncompressed'); // The converted key and the uncompressed public key should be the same console.log(uncompressedKey === ecdh.getPublicKey('hex'));
ecdh.computeSecret(otherPublicKey[, inputEncoding][, outputEncoding])#
otherPublicKey<string>|<ArrayBuffer>|<Buffer>|<TypedArray>|<DataView>inputEncoding<string>The encoding of theotherPublicKeystring.outputEncoding<string>The encoding of the return value.- Returns:
<Buffer>|<string>
Computes the shared secret using otherPublicKey as the other party's public key and returns the computed shared secret. The supplied key is interpreted using specified inputEncoding, and the returned secret is encoded using the specified outputEncoding. If the inputEncoding is not provided, otherPublicKey is expected to be a Buffer, TypedArray, or DataView.
If outputEncoding is given a string will be returned; otherwise a Buffer is returned.
ecdh.computeSecret will throw an ERR_CRYPTO_ECDH_INVALID_PUBLIC_KEY error when otherPublicKey lies outside of the elliptic curve. Since otherPublicKey is usually supplied from a remote user over an insecure network, be sure to handle this exception accordingly.
ecdh.generateKeys([encoding[, format]])#
encoding<string>The encoding of the return value.format<string>Default:'uncompressed'- Returns:
<Buffer>|<string>
Generates private and public EC Diffie-Hellman key values, and returns the public key in the specified format and encoding. This key should be transferred to the other party.
The format argument specifies point encoding and can be 'compressed' or 'uncompressed'. If format is not specified, the point will be returned in 'uncompressed' format.
If encoding is provided a string is returned; otherwise a Buffer is returned.
ecdh.getPrivateKey([encoding])#
encoding<string>The encoding of the return value.- Returns:
<Buffer>|<string>The EC Diffie-Hellman in the specifiedencoding.
If encoding is specified, a string is returned; otherwise a Buffer is returned.
ecdh.getPublicKey([encoding][, format])#
encoding<string>The encoding of the return value.format<string>Default:'uncompressed'- Returns:
<Buffer>|<string>The EC Diffie-Hellman public key in the specifiedencodingandformat.
The format argument specifies point encoding and can be 'compressed' or 'uncompressed'. If format is not specified the point will be returned in 'uncompressed' format.
If encoding is specified, a string is returned; otherwise a Buffer is returned.
ecdh.setPrivateKey(privateKey[, encoding])#
privateKey<string>|<ArrayBuffer>|<Buffer>|<TypedArray>|<DataView>encoding<string>The encoding of theprivateKeystring.
Sets the EC Diffie-Hellman private key. If encoding is provided, privateKey is expected to be a string; otherwise privateKey is expected to be a Buffer, TypedArray, or DataView.
If privateKey is not valid for the curve specified when the ECDH object was created, an error is thrown. Upon setting the private key, the associated public point (key) is also generated and set in the ECDH object.
ecdh.setPublicKey(publicKey[, encoding])#
Stability: 0 - Deprecated
publicKey<string>|<ArrayBuffer>|<Buffer>|<TypedArray>|<DataView>encoding<string>The encoding of thepublicKeystring.
Sets the EC Diffie-Hellman public key. If encoding is provided publicKey is expected to be a string; otherwise a Buffer, TypedArray, or DataView is expected.
There is not normally a reason to call this method because ECDH only requires a private key and the other party's public key to compute the shared secret. Typically either ecdh.generateKeys() or ecdh.setPrivateKey() will be called. The ecdh.setPrivateKey() method attempts to generate the public point/key associated with the private key being set.
Example (obtaining a shared secret):
const { createECDH, createHash, } = await import('node:crypto'); const alice = createECDH('secp256k1'); const bob = createECDH('secp256k1'); // This is a shortcut way of specifying one of Alice's previous private // keys. It would be unwise to use such a predictable private key in a real // application. alice.setPrivateKey( createHash('sha256').update('alice', 'utf8').digest(), ); // Bob uses a newly generated cryptographically strong // pseudorandom key pair bob.generateKeys(); const aliceSecret = alice.computeSecret(bob.getPublicKey(), null, 'hex'); const bobSecret = bob.computeSecret(alice.getPublicKey(), null, 'hex'); // aliceSecret and bobSecret should be the same shared secret value console.log(aliceSecret === bobSecret);const { createECDH, createHash, } = require('node:crypto'); const alice = createECDH('secp256k1'); const bob = createECDH('secp256k1'); // This is a shortcut way of specifying one of Alice's previous private // keys. It would be unwise to use such a predictable private key in a real // application. alice.setPrivateKey( createHash('sha256').update('alice', 'utf8').digest(), ); // Bob uses a newly generated cryptographically strong // pseudorandom key pair bob.generateKeys(); const aliceSecret = alice.computeSecret(bob.getPublicKey(), null, 'hex'); const bobSecret = bob.computeSecret(alice.getPublicKey(), null, 'hex'); // aliceSecret and bobSecret should be the same shared secret value console.log(aliceSecret === bobSecret);
Class: Hash#
- Extends:
<stream.Transform>
The Hash class is a utility for creating hash digests of data. It can be used in one of two ways:
- As a stream that is both readable and writable, where data is written to produce a computed hash digest on the readable side, or
- Using the
hash.update()andhash.digest()methods to produce the computed hash.
The crypto.createHash() method is used to create Hash instances. Hash objects are not to be created directly using the new keyword.
Example: Using Hash objects as streams:
const { createHash, } = await import('node:crypto'); const hash = createHash('sha256'); hash.on('readable', () => { // Only one element is going to be produced by the // hash stream. const data = hash.read(); if (data) { console.log(data.toString('hex')); // Prints: // 6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50 } }); hash.write('some data to hash'); hash.end();const { createHash, } = require('node:crypto'); const hash = createHash('sha256'); hash.on('readable', () => { // Only one element is going to be produced by the // hash stream. const data = hash.read(); if (data) { console.log(data.toString('hex')); // Prints: // 6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50 } }); hash.write('some data to hash'); hash.end();
Example: Using Hash and piped streams:
import { createReadStream } from 'node:fs'; import { stdout } from 'node:process'; const { createHash } = await import('node:crypto'); const hash = createHash('sha256'); const input = createReadStream('test.js'); input.pipe(hash).setEncoding('hex').pipe(stdout);const { createReadStream } = require('node:fs'); const { createHash } = require('node:crypto'); const { stdout } = require('node:process'); const hash = createHash('sha256'); const input = createReadStream('test.js'); input.pipe(hash).setEncoding('hex').pipe(stdout);
Example: Using the hash.update() and hash.digest() methods:
const { createHash, } = await import('node:crypto'); const hash = createHash('sha256'); hash.update('some data to hash'); console.log(hash.digest('hex')); // Prints: // 6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50const { createHash, } = require('node:crypto'); const hash = createHash('sha256'); hash.update('some data to hash'); console.log(hash.digest('hex')); // Prints: // 6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50
hash.copy([options])#
options<Object>stream.transformoptions- Returns:
<Hash>
Creates a new Hash object that contains a deep copy of the internal state of the current Hash object.
The optional options argument controls stream behavior. For XOF hash functions such as 'shake256', the outputLength option can be used to specify the desired output length in bytes.
An error is thrown when an attempt is made to copy the Hash object after its hash.digest() method has been called.
// Calculate a rolling hash. const { createHash, } = await import('node:crypto'); const hash = createHash('sha256'); hash.update('one'); console.log(hash.copy().digest('hex')); hash.update('two'); console.log(hash.copy().digest('hex')); hash.update('three'); console.log(hash.copy().digest('hex')); // Etc.// Calculate a rolling hash. const { createHash, } = require('node:crypto'); const hash = createHash('sha256'); hash.update('one'); console.log(hash.copy().digest('hex')); hash.update('two'); console.log(hash.copy().digest('hex')); hash.update('three'); console.log(hash.copy().digest('hex')); // Etc.
hash.digest([encoding])#
Calculates the digest of all of the data passed to be hashed (using the hash.update() method). If encoding is provided a string will be returned; otherwise a Buffer is returned.
The Hash object can not be used again after hash.digest() method has been called. Multiple calls will cause an error to be thrown.
hash.update(data[, inputEncoding])#
data<string>|<Buffer>|<TypedArray>|<DataView>inputEncoding<string>The encoding of thedatastring.
Updates the hash content with the given data, the encoding of which is given in inputEncoding. If encoding is not provided, and the data is a string, an encoding of 'utf8' is enforced. If data is a Buffer, TypedArray, or DataView, then inputEncoding is ignored.
This can be called many times with new data as it is streamed.
Class: Hmac#
- Extends:
<stream.Transform>
The Hmac class is a utility for creating cryptographic HMAC digests. It can be used in one of two ways:
- As a stream that is both readable and writable, where data is written to produce a computed HMAC digest on the readable side, or
- Using the
hmac.update()andhmac.digest()methods to produce the computed HMAC digest.
The crypto.createHmac() method is used to create Hmac instances. Hmac objects are not to be created directly using the new keyword.
Example: Using Hmac objects as streams:
const { createHmac, } = await import('node:crypto'); const hmac = createHmac('sha256', 'a secret'); hmac.on('readable', () => { // Only one element is going to be produced by the // hash stream. const data = hmac.read(); if (data) { console.log(data.toString('hex')); // Prints: // 7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e } }); hmac.write('some data to hash'); hmac.end();const { createHmac, } = require('node:crypto'); const hmac = createHmac('sha256', 'a secret'); hmac.on('readable', () => { // Only one element is going to be produced by the // hash stream. const data = hmac.read(); if (data) { console.log(data.toString('hex')); // Prints: // 7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e } }); hmac.write('some data to hash'); hmac.end();
Example: Using Hmac and piped streams:
import { createReadStream } from 'node:fs'; import { stdout } from 'node:process'; const { createHmac, } = await import('node:crypto'); const hmac = createHmac('sha256', 'a secret'); const input = createReadStream('test.js'); input.pipe(hmac).pipe(stdout);const { createReadStream, } = require('node:fs'); const { createHmac, } = require('node:crypto'); const { stdout } = require('node:process'); const hmac = createHmac('sha256', 'a secret'); const input = createReadStream('test.js'); input.pipe(hmac).pipe(stdout);
Example: Using the hmac.update() and hmac.digest() methods:
const { createHmac, } = await import('node:crypto'); const hmac = createHmac('sha256', 'a secret'); hmac.update('some data to hash'); console.log(hmac.digest('hex')); // Prints: // 7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77econst { createHmac, } = require('node:crypto'); const hmac = createHmac('sha256', 'a secret'); hmac.update('some data to hash'); console.log(hmac.digest('hex')); // Prints: // 7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e
hmac.digest([encoding])#
Calculates the HMAC digest of all of the data passed using hmac.update(). If encoding is provided a string is returned; otherwise a Buffer is returned;
The Hmac object can not be used again after hmac.digest() has been called. Multiple calls to hmac.digest() will result in an error being thrown.
hmac.update(data[, inputEncoding])#
data<string>|<Buffer>|<TypedArray>|<DataView>inputEncoding<string>The encoding of thedatastring.
Updates the Hmac content with the given data, the encoding of which is given in inputEncoding. If encoding is not provided, and the data is a string, an encoding of 'utf8' is enforced. If data is a Buffer, TypedArray, or DataView, then inputEncoding is ignored.
This can be called many times with new data as it is streamed.
Class: KeyObject#
Node.js uses a KeyObject class to represent a symmetric or asymmetric key, and each kind of key exposes different functions. The crypto.createSecretKey(), crypto.createPublicKey() and crypto.createPrivateKey() methods are used to create KeyObject instances. KeyObject objects are not to be created directly using the new keyword.
Most applications should consider using the new KeyObject API instead of passing keys as strings or Buffers due to improved security features.
KeyObject instances can be passed to other threads via postMessage(). The receiver obtains a cloned KeyObject, and the KeyObject does not need to be listed in the transferList argument.
Static method: KeyObject.from(key)#
key<CryptoKey>- Returns:
<KeyObject>
Example: Converting a CryptoKey instance to a KeyObject:
const { KeyObject } = await import('node:crypto'); const { subtle } = globalThis.crypto; const key = await subtle.generateKey({ name: 'HMAC', hash: 'SHA-256', length: 256, }, true, ['sign', 'verify']); const keyObject = KeyObject.from(key); console.log(keyObject.symmetricKeySize); // Prints: 32 (symmetric key size in bytes)const { KeyObject } = require('node:crypto'); const { subtle } = globalThis.crypto; (async function() { const key = await subtle.generateKey({ name: 'HMAC', hash: 'SHA-256', length: 256, }, true, ['sign', 'verify']); const keyObject = KeyObject.from(key); console.log(keyObject.symmetricKeySize); // Prints: 32 (symmetric key size in bytes) })();
keyObject.asymmetricKeyDetails#
- Type:
<Object>modulusLength<number>Key size in bits (RSA, DSA).publicExponent<bigint>Public exponent (RSA).hashAlgorithm<string>Name of the message digest (RSA-PSS).mgf1HashAlgorithm<string>Name of the message digest used by MGF1 (RSA-PSS).saltLength<number>Minimal salt length in bytes (RSA-PSS).divisorLength<number>Size ofqin bits (DSA).namedCurve<string>Name of the curve (EC).
This property exists only on asymmetric keys. Depending on the type of the key, this object contains information about the key. None of the information obtained through this property can be used to uniquely identify a key or to compromise the security of the key.
For RSA-PSS keys, if the key material contains a RSASSA-PSS-params sequence, the hashAlgorithm, mgf1HashAlgorithm, and saltLength properties will be set.
Other key details might be exposed via this API using additional attributes.
keyObject.asymmetricKeyType#
- Type:
<string>
For asymmetric keys, this property represents the type of the key. See the supported asymmetric key types.
This property is undefined for unrecognized KeyObject types and symmetric keys.
keyObject.equals(otherKeyObject)#
otherKeyObject<KeyObject>AKeyObjectwith which to comparekeyObject.- Returns:
<boolean>
Returns true or false depending on whether the keys have exactly the same type, value, and parameters. This method is not constant time.
keyObject.export([options])#
For symmetric keys, the following encoding options can be used:
format<string>Must be'buffer'(default) or'jwk'.
For public keys, the following encoding options can be used:
type<string>Must be one of'pkcs1'(RSA only) or'spki'.format<string>Must be'pem','der', or'jwk'.
For private keys, the following encoding options can be used:
type<string>Must be one of'pkcs1'(RSA only),'pkcs8'or'sec1'(EC only).format<string>Must be'pem','der', or'jwk'.cipher<string>If specified, the private key will be encrypted with the givencipherandpassphraseusing PKCS#5 v2.0 password based encryption.passphrase<string>|<Buffer>The passphrase to use for encryption, seecipher.
The result type depends on the selected encoding format, when PEM the result is a string, when DER it will be a buffer containing the data encoded as DER, when JWK it will be an object.
When JWK encoding format was selected, all other encoding options are ignored.
PKCS#1, SEC1, and PKCS#8 type keys can be encrypted by using a combination of the cipher and format options. The PKCS#8 type can be used with any format to encrypt any key algorithm (RSA, EC, or DH) by specifying a cipher. PKCS#1 and SEC1 can only be encrypted by specifying a cipher when the PEM format is used. For maximum compatibility, use PKCS#8 for encrypted private keys. Since PKCS#8 defines its own encryption mechanism, PEM-level encryption is not supported when encrypting a PKCS#8 key. See RFC 5208 for PKCS#8 encryption and RFC 1421 for PKCS#1 and SEC1 encryption.
keyObject.symmetricKeySize#
- Type:
<number>
For secret keys, this property represents the size of the key in bytes. This property is undefined for asymmetric keys.
keyObject.toCryptoKey(algorithm, extractable, keyUsages)#
algorithm<string>|<Algorithm>|<RsaHashedImportParams>|<EcKeyImportParams>|<HmacImportParams>
extractable<boolean>keyUsages<string[]>See Key usages.- Returns:
<CryptoKey>
Converts a KeyObject instance to a CryptoKey.
keyObject.type#
- Type:
<string>
Depending on the type of this KeyObject, this property is either 'secret' for secret (symmetric) keys, 'public' for public (asymmetric) keys or 'private' for private (asymmetric) keys.
Class: Sign#
- Extends:
<stream.Writable>
The Sign class is a utility for generating signatures. It can be used in one of two ways:
- As a writable stream, where data to be signed is written and the
sign.sign()method is used to generate and return the signature, or - Using the
sign.update()andsign.sign()methods to produce the signature.
The crypto.createSign() method is used to create Sign instances. The argument is the string name of the hash function to use. Sign objects are not to be created directly using the new keyword.
Example: Using Sign and Verify objects as streams:
const { generateKeyPairSync, createSign, createVerify, } = await import('node:crypto'); const { privateKey, publicKey } = generateKeyPairSync('ec', { namedCurve: 'sect239k1', }); const sign = createSign('SHA256'); sign.write('some data to sign'); sign.end(); const signature = sign.sign(privateKey, 'hex'); const verify = createVerify('SHA256'); verify.write('some data to sign'); verify.end(); console.log(verify.verify(publicKey, signature, 'hex')); // Prints: trueconst { generateKeyPairSync, createSign, createVerify, } = require('node:crypto'); const { privateKey, publicKey } = generateKeyPairSync('ec', { namedCurve: 'sect239k1', }); const sign = createSign('SHA256'); sign.write('some data to sign'); sign.end(); const signature = sign.sign(privateKey, 'hex'); const verify = createVerify('SHA256'); verify.write('some data to sign'); verify.end(); console.log(verify.verify(publicKey, signature, 'hex')); // Prints: true
Example: Using the sign.update() and verify.update() methods:
const { generateKeyPairSync, createSign, createVerify, } = await import('node:crypto'); const { privateKey, publicKey } = generateKeyPairSync('rsa', { modulusLength: 2048, }); const sign = createSign('SHA256'); sign.update('some data to sign'); sign.end(); const signature = sign.sign(privateKey); const verify = createVerify('SHA256'); verify.update('some data to sign'); verify.end(); console.log(verify.verify(publicKey, signature)); // Prints: trueconst { generateKeyPairSync, createSign, createVerify, } = require('node:crypto'); const { privateKey, publicKey } = generateKeyPairSync('rsa', { modulusLength: 2048, }); const sign = createSign('SHA256'); sign.update('some data to sign'); sign.end(); const signature = sign.sign(privateKey); const verify = createVerify('SHA256'); verify.update('some data to sign'); verify.end(); console.log(verify.verify(publicKey, signature)); // Prints: true
sign.sign(privateKey[, outputEncoding])#
privateKey<Object>|<string>|<ArrayBuffer>|<Buffer>|<TypedArray>|<DataView>|<KeyObject>|<CryptoKey>outputEncoding<string>The encoding of the return value.- Returns:
<Buffer>|<string>
Calculates the signature on all the data passed through using either sign.update() or sign.write().
If privateKey is not a KeyObject, this function behaves as if privateKey had been passed to crypto.createPrivateKey(). If it is an object, the following additional properties can be passed:
dsaEncoding<string>For DSA and ECDSA, this option specifies the format of the generated signature. It can be one of the following:'der'(default): DER-encoded ASN.1 signature structure encoding(r, s).'ieee-p1363': Signature formatr || sas proposed in IEEE-P1363.
padding<integer>Optional padding value for RSA, one of the following:crypto.constants.RSA_PKCS1_PADDING(default)crypto.constants.RSA_PKCS1_PSS_PADDING
RSA_PKCS1_PSS_PADDINGwill use MGF1 with the same hash function used to sign the message as specified in section 3.1 of RFC 4055, unless an MGF1 hash function has been specified as part of the key in compliance with section 3.3 of RFC 4055.saltLength<integer>Salt length for when padding isRSA_PKCS1_PSS_PADDING. The special valuecrypto.constants.RSA_PSS_SALTLEN_DIGESTsets the salt length to the digest size,crypto.constants.RSA_PSS_SALTLEN_MAX_SIGN(default) sets it to the maximum permissible value.
If outputEncoding is provided a string is returned; otherwise a Buffer is returned.
The Sign object can not be again used after sign.sign() method has been called. Multiple calls to sign.sign() will result in an error being thrown.
sign.update(data[, inputEncoding])#
data<string>|<Buffer>|<TypedArray>|<DataView>inputEncoding<string>The encoding of thedatastring.
Updates the Sign content with the given data, the encoding of which is given in inputEncoding. If encoding is not provided, and the data is a string, an encoding of 'utf8' is enforced. If data is a Buffer, TypedArray, or DataView, then inputEncoding is ignored.
This can be called many times with new data as it is streamed.
Class: Verify#
- Extends:
<stream.Writable>
The Verify class is a utility for verifying signatures. It can be used in one of two ways:
- As a writable stream where written data is used to validate against the supplied signature, or
- Using the
verify.update()andverify.verify()methods to verify the signature.
The crypto.createVerify() method is used to create Verify instances. Verify objects are not to be created directly using the new keyword.
See Sign for examples.
verify.update(data[, inputEncoding])#
data<string>|<Buffer>|<TypedArray>|<DataView>inputEncoding<string>The encoding of thedatastring.
Updates the Verify content with the given data, the encoding of which is given in inputEncoding. If inputEncoding is not provided, and the data is a string, an encoding of 'utf8' is enforced. If data is a Buffer, TypedArray, or DataView, then inputEncoding is ignored.
This can be called many times with new data as it is streamed.
verify.verify(object, signature[, signatureEncoding])#
object<Object>|<string>|<ArrayBuffer>|<Buffer>|<TypedArray>|<DataView>|<KeyObject>|<CryptoKey>signature<string>|<ArrayBuffer>|<Buffer>|<TypedArray>|<DataView>signatureEncoding<string>The encoding of thesignaturestring.- Returns:
<boolean>trueorfalsedepending on the validity of the signature for the data and public key.
Verifies the provided data using the given object and signature.
If object is not a KeyObject, this function behaves as if object had been passed to crypto.createPublicKey(). If it is an object, the following additional properties can be passed:
dsaEncoding<string>For DSA and ECDSA, this option specifies the format of the signature. It can be one of the following:'der'(default): DER-encoded ASN.1 signature structure encoding(r, s).'ieee-p1363': Signature formatr || sas proposed in IEEE-P1363.
padding<integer>Optional padding value for RSA, one of the following:crypto.constants.RSA_PKCS1_PADDING(default)crypto.constants.RSA_PKCS1_PSS_PADDING
RSA_PKCS1_PSS_PADDINGwill use MGF1 with the same hash function used to verify the message as specified in section 3.1 of RFC 4055, unless an MGF1 hash function has been specified as part of the key in compliance with section 3.3 of RFC 4055.saltLength<integer>Salt length for when padding isRSA_PKCS1_PSS_PADDING. The special valuecrypto.constants.RSA_PSS_SALTLEN_DIGESTsets the salt length to the digest size,crypto.constants.RSA_PSS_SALTLEN_AUTO(default) causes it to be determined automatically.
The signature argument is the previously calculated signature for the data, in the signatureEncoding. If a signatureEncoding is specified, the signature is expected to be a string; otherwise signature is expected to be a Buffer, TypedArray, or DataView.
The verify object can not be used again after verify.verify() has been called. Multiple calls to verify.verify() will result in an error being thrown.
Because public keys can be derived from private keys, a private key may be passed instead of a public key.
Class: X509Certificate#
Encapsulates an X509 certificate and provides read-only access to its information.
const { X509Certificate } = await import('node:crypto'); const x509 = new X509Certificate('{... pem encoded cert ...}'); console.log(x509.subject);const { X509Certificate } = require('node:crypto'); const x509 = new X509Certificate('{... pem encoded cert ...}'); console.log(x509.subject);
new X509Certificate(buffer)#
buffer<string>|<TypedArray>|<Buffer>|<DataView>A PEM or DER encoded X509 Certificate.
x509.ca#
- Type:
<boolean>Will betrueif this is a Certificate Authority (CA) certificate.
x509.checkEmail(email[, options])#
email<string>options<Object>subject<string>'default','always', or'never'. Default:'default'.
- Returns:
<string>|<undefined>Returnsemailif the certificate matches,undefinedif it does not.
Checks whether the certificate matches the given email address.
If the 'subject' option is undefined or set to 'default', the certificate subject is only considered if the subject alternative name extension either does not exist or does not contain any email addresses.
If the 'subject' option is set to 'always' and if the subject alternative name extension either does not exist or does not contain a matching email address, the certificate subject is considered.
If the 'subject' option is set to 'never', the certificate subject is never considered, even if the certificate contains no subject alternative names.
x509.checkHost(name[, options])#
name<string>options<Object>- Returns:
<string>|<undefined>Returns a subject name that matchesname, orundefinedif no subject name matchesname.
Checks whether the certificate matches the given host name.
If the certificate matches the given host name, the matching subject name is returned. The returned name might be an exact match (e.g., foo.example.com) or it might contain wildcards (e.g., *.example.com). Because host name comparisons are case-insensitive, the returned subject name might also differ from the given name in capitalization.
If the 'subject' option is undefined or set to 'default', the certificate subject is only considered if the subject alternative name extension either does not exist or does not contain any DNS names. This behavior is consistent with RFC 2818 ("HTTP Over TLS").
If the 'subject' option is set to 'always' and if the subject alternative name extension either does not exist or does not contain a matching DNS name, the certificate subject is considered.
If the 'subject' option is set to 'never', the certificate subject is never considered, even if the certificate contains no subject alternative names.
x509.checkIP(ip)#
ip<string>- Returns:
<string>|<undefined>Returnsipif the certificate matches,undefinedif it does not.
Checks whether the certificate matches the given IP address (IPv4 or IPv6).
Only RFC 5280 iPAddress subject alternative names are considered, and they must match the given ip address exactly. Other subject alternative names as well as the subject field of the certificate are ignored.
x509.checkIssued(otherCert)#
otherCert<X509Certificate>- Returns:
<boolean>
Checks whether this certificate was potentially issued by the given otherCert by comparing the certificate metadata.
This is useful for pruning a list of possible issuer certificates which have been selected using a more rudimentary filtering routine, i.e. just based on subject and issuer names.
Finally, to verify that this certificate's signature was produced by a private key corresponding to otherCert's public key use x509.verify(publicKey) with otherCert's public key represented as a KeyObject like so
if (!x509.verify(otherCert.publicKey)) {
throw new Error('otherCert did not issue x509');
}
x509.checkPrivateKey(privateKey)#
privateKey<KeyObject>A private key.- Returns:
<boolean>
Checks whether the public key for this certificate is consistent with the given private key.
x509.fingerprint#
- Type:
<string>
The SHA-1 fingerprint of this certificate.
Because SHA-1 is cryptographically broken and because the security of SHA-1 is significantly worse than that of algorithms that are commonly used to sign certificates, consider using x509.fingerprint256 instead.
x509.fingerprint256#
- Type:
<string>
The SHA-256 fingerprint of this certificate.
x509.fingerprint512#
- Type:
<string>
The SHA-512 fingerprint of this certificate.
Because computing the SHA-256 fingerprint is usually faster and because it is only half the size of the SHA-512 fingerprint, x509.fingerprint256 may be a better choice. While SHA-512 presumably provides a higher level of security in general, the security of SHA-256 matches that of most algorithms that are commonly used to sign certificates.
x509.infoAccess#
- Type:
<string>
A textual representation of the certificate's authority information access extension.
This is a line feed separated list of access descriptions. Each line begins with the access method and the kind of the access location, followed by a colon and the value associated with the access location.
After the prefix denoting the access method and the kind of the access location, the remainder of each line might be enclosed in quotes to indicate that the value is a JSON string literal. For backward compatibility, Node.js only uses JSON string literals within this property when necessary to avoid ambiguity. Third-party code should be prepared to handle both possible entry formats.
x509.issuer#
- Type:
<string>
The issuer identification included in this certificate.
x509.issuerCertificate#
- Type:
<X509Certificate>
The issuer certificate or undefined if the issuer certificate is not available.
x509.keyUsage#
- Type:
<string[]>
An array detailing the key extended usages for this certificate.
x509.publicKey#
- Type:
<KeyObject>
The public key <KeyObject> for this certificate.
x509.raw#
- Type:
<Buffer>
A Buffer containing the DER encoding of this certificate.
x509.serialNumber#
- Type:
<string>
The serial number of this certificate.
Serial numbers are assigned by certificate authorities and do not uniquely identify certificates. Consider using x509.fingerprint256 as a unique identifier instead.
x509.subject#
- Type:
<string>
The complete subject of this certificate.
x509.subjectAltName#
- Type:
<string>
The subject alternative name specified for this certificate.
This is a comma-separated list of subject alternative names. Each entry begins with a string identifying the kind of the subject alternative name followed by a colon and the value associated with the entry.
Earlier versions of Node.js incorrectly assumed that it is safe to split this property at the two-character sequence ', ' (see CVE-2021-44532). However, both malicious and legitimate certificates can contain subject alternative names that include this sequence when represented as a string.
After the prefix denoting the type of the entry, the remainder of each entry might be enclosed in quotes to indicate that the value is a JSON string literal. For backward compatibility, Node.js only uses JSON string literals within this property when necessary to avoid ambiguity. Third-party code should be prepared to handle both possible entry formats.
x509.toJSON()#
- Type:
<string>
There is no standard JSON encoding for X509 certificates. The toJSON() method returns a string containing the PEM encoded certificate.
x509.toLegacyObject()#
- Type:
<Object>
Returns information about this certificate using the legacy certificate object encoding.
x509.toString()#
- Type:
<string>
Returns the PEM-encoded certificate.
x509.validFrom#
- Type:
<string>
The date/time from which this certificate is valid.
x509.validFromDate#
- Type:
<Date>
The date/time from which this certificate is valid, encapsulated in a Date object.
x509.validTo#
- Type:
<string>
The date/time until which this certificate is valid.
x509.validToDate#
- Type:
<Date>
The date/time until which this certificate is valid, encapsulated in a Date object.
x509.signatureAlgorithm#
- Type:
<string>|<undefined>
The algorithm used to sign the certificate or undefined if the signature algorithm is unknown by OpenSSL.
x509.signatureAlgorithmOid#
- Type:
<string>
The OID of the algorithm used to sign the certificate.
x509.verify(publicKey)#
publicKey<KeyObject>A public key.- Returns:
<boolean>
Verifies that this certificate was signed by the given public key. Does not perform any other validation checks on the certificate.
node:crypto module methods and properties#
crypto.argon2(algorithm, parameters, callback)#
Stability: 1.2 - Release candidate
algorithm<string>Variant of Argon2, one of"argon2d","argon2i"or"argon2id".parameters<Object>message<string>|<ArrayBuffer>|<Buffer>|<TypedArray>|<DataView>REQUIRED, this is the password for password hashing applications of Argon2.nonce<string>|<ArrayBuffer>|<Buffer>|<TypedArray>|<DataView>REQUIRED, must be at least 8 bytes long. This is the salt for password hashing applications of Argon2.parallelism<number>REQUIRED, degree of parallelism determines how many computational chains (lanes) can be run. Must be greater than 1 and less than2**24-1.tagLength<number>REQUIRED, the length of the key to generate. Must be greater than 4 and less than2**32-1.memory<number>REQUIRED, memory cost in 1KiB blocks. Must be greater than8 * parallelismand less than2**32-1. The actual number of blocks is rounded down to the nearest multiple of4 * parallelism.passes<number>REQUIRED, number of passes (iterations). Must be greater than 1 and less than2**32-1.secret<string>|<ArrayBuffer>|<Buffer>|<TypedArray>|<DataView>|<undefined>OPTIONAL, Random additional input, similar to the salt, that should NOT be stored with the derived key. This is known as pepper in password hashing applications. If used, must have a length not greater than2**32-1bytes.associatedData<string>|<ArrayBuffer>|<Buffer>|<TypedArray>|<DataView>|<undefined>OPTIONAL, Additional data to be added to the hash, functionally equivalent to salt or secret, but meant for non-random data. If used, must have a length not greater than2**32-1bytes.
callback<Function>
Provides an asynchronous Argon2 implementation. Argon2 is a password-based key derivation function that is designed to be expensive computationally and memory-wise in order to make brute-force attacks unrewarding.
The nonce should be as unique as possible. It is recommended that a nonce is random and at least 16 bytes long. See NIST SP 800-132 for details.
When passing strings for message, nonce, secret or associatedData, please consider caveats when using strings as inputs to cryptographic APIs.
The callback function is called with two arguments: err and derivedKey. err is an exception object when key derivation fails, otherwise err is null. derivedKey is passed to the callback as a Buffer.
An exception is thrown when any of the input arguments specify invalid values or types.
const { argon2, randomBytes } = await import('node:crypto'); const parameters = { message: 'password', nonce: randomBytes(16), parallelism: 4, tagLength: 64, memory: 65536, passes: 3, }; argon2('argon2id', parameters, (err, derivedKey) => { if (err) throw err; console.log(derivedKey.toString('hex')); // 'af91dad...9520f15' });const { argon2, randomBytes } = require('node:crypto'); const parameters = { message: 'password', nonce: randomBytes(16), parallelism: 4, tagLength: 64, memory: 65536, passes: 3, }; argon2('argon2id', parameters, (err, derivedKey) => { if (err) throw err; console.log(derivedKey.toString('hex')); // 'af91dad...9520f15' });
crypto.argon2Sync(algorithm, parameters)#
Stability: 1.2 - Release candidate
algorithm<string>Variant of Argon2, one of"argon2d","argon2i"or"argon2id".parameters<Object>message<string>|<ArrayBuffer>|<Buffer>|<TypedArray>|<DataView>REQUIRED, this is the password for password hashing applications of Argon2.nonce<string>|<ArrayBuffer>|<Buffer>|<TypedArray>|<DataView>REQUIRED, must be at least 8 bytes long. This is the salt for password hashing applications of Argon2.parallelism<number>REQUIRED, degree of parallelism determines how many computational chains (lanes) can be run. Must be greater than 1 and less than2**24-1.tagLength<number>REQUIRED, the length of the key to generate. Must be greater than 4 and less than2**32-1.memory<number>REQUIRED, memory cost in 1KiB blocks. Must be greater than8 * parallelismand less than2**32-1. The actual number of blocks is rounded down to the nearest multiple of4 * parallelism.passes<number>REQUIRED, number of passes (iterations). Must be greater than 1 and less than2**32-1.secret<string>|<ArrayBuffer>|<Buffer>|<TypedArray>|<DataView>|<undefined>OPTIONAL, Random additional input, similar to the salt, that should NOT be stored with the derived key. This is known as pepper in password hashing applications. If used, must have a length not greater than2**32-1bytes.associatedData<string>|<ArrayBuffer>|<Buffer>|<TypedArray>|<DataView>|<undefined>OPTIONAL, Additional data to be added to the hash, functionally equivalent to salt or secret, but meant for non-random data. If used, must have a length not greater than2**32-1bytes.
- Returns:
<Buffer>
Provides a synchronous Argon2 implementation. Argon2 is a password-based key derivation function that is designed to be expensive computationally and memory-wise in order to make brute-force attacks unrewarding.
The nonce should be as unique as possible. It is recommended that a nonce is random and at least 16 bytes long. See NIST SP 800-132 for details.
When passing strings for message, nonce, secret or associatedData, please consider caveats when using strings as inputs to cryptographic APIs.
An exception is thrown when key derivation fails, otherwise the derived key is returned as a Buffer.
An exception is thrown when any of the input arguments specify invalid values or types.
const { argon2Sync, randomBytes } = await import('node:crypto'); const parameters = { message: 'password', nonce: randomBytes(16), parallelism: 4, tagLength: 64, memory: 65536, passes: 3, }; const derivedKey = argon2Sync('argon2id', parameters); console.log(derivedKey.toString('hex')); // 'af91dad...9520f15'const { argon2Sync, randomBytes } = require('node:crypto'); const parameters = { message: 'password', nonce: randomBytes(16), parallelism: 4, tagLength: 64, memory: 65536, passes: 3, }; const derivedKey = argon2Sync('argon2id', parameters); console.log(derivedKey.toString('hex')); // 'af91dad...9520f15'
crypto.checkPrime(candidate[, options], callback)#
candidate<ArrayBuffer>|<SharedArrayBuffer>|<TypedArray>|<Buffer>|<DataView>|<bigint>A possible prime encoded as a sequence of big endian octets of arbitrary length.options<Object>checks<number>The number of Miller-Rabin probabilistic primality iterations to perform. When the value is0(zero), a number of checks is used that yields a false positive rate of at most 2-64 for random input. Care must be used when selecting a number of checks. Refer to the OpenSSL documentation for theBN_is_prime_exfunctionnchecksoptions for more details. Default:0
callback<Function>
Checks the primality of the candidate.
crypto.checkPrimeSync(candidate[, options])#
candidate<ArrayBuffer>|<SharedArrayBuffer>|<TypedArray>|<Buffer>|<DataView>|<bigint>A possible prime encoded as a sequence of big endian octets of arbitrary length.options<Object>checks<number>The number of Miller-Rabin probabilistic primality iterations to perform. When the value is0(zero), a number of checks is used that yields a false positive rate of at most 2-64 for random input. Care must be used when selecting a number of checks. Refer to the OpenSSL documentation for theBN_is_prime_exfunctionnchecksoptions for more details. Default:0
- Returns:
<boolean>trueif the candidate is a prime with an error probability less than0.25 ** options.checks.
Checks the primality of the candidate.
crypto.constants#
- Type:
<Object>
An object containing commonly used constants for crypto and security related operations. The specific constants currently defined are described in Crypto constants.
crypto.createCipheriv(algorithm, key, iv[, options])#
algorithm<string>key<string>|<ArrayBuffer>|<Buffer>|<TypedArray>|<DataView>|<KeyObject>|<CryptoKey>iv<string>|<ArrayBuffer>|<Buffer>|<TypedArray>|<DataView>|<null>options<Object>stream.transformoptions- Returns:
<Cipheriv>
Creates and returns a Cipheriv object, with the given algorithm, key and initialization vector (iv).
The options argument controls stream behavior and is optional except when a cipher in CCM or OCB mode (e.g. 'aes-128-ccm') is used. In that case, the authTagLength option is required and specifies the length of the authentication tag in bytes, see CCM mode. In GCM mode, the authTagLength option is not required but can be used to set the length of the authentication tag that will be returned by getAuthTag() and defaults to 16 bytes. For chacha20-poly1305, the authTagLength option defaults to 16 bytes.
The algorithm is dependent on OpenSSL, examples are 'aes192', etc. On recent OpenSSL releases, openssl list -cipher-algorithms will display the available cipher algorithms.
The key is the raw key used by the algorithm and iv is an initialization vector. Both arguments must be 'utf8' encoded strings, Buffers, TypedArray, or DataViews. The key may optionally be a KeyObject of type secret. If the cipher does not need an initialization vector, iv may be null.
When passing strings for key or iv, please consider caveats when using strings as inputs to cryptographic APIs.
Initialization vectors should be unpredictable and unique; ideally, they will be cryptographically random. They do not have to be secret: IVs are typically just added to ciphertext messages unencrypted. It may sound contradictory that something has to be unpredictable and unique, but does not have to be secret; remember that an attacker must not be able to predict ahead of time what a given IV will be.
crypto.createDecipheriv(algorithm, key, iv[, options])#
algorithm<string>key<string>|<ArrayBuffer>|<Buffer>|<TypedArray>|<DataView>|<KeyObject>|<CryptoKey>iv<string>|<ArrayBuffer>|<Buffer>|<TypedArray>|<DataView>|<null>options<Object>stream.transformoptions- Returns:
<Decipheriv>
Creates and returns a Decipheriv object that uses the given algorithm, key and initialization vector (iv).
The options argument controls stream behavior and is optional except when a cipher in CCM or OCB mode (e.g. 'aes-128-ccm') is used. In that case, the authTagLength option is required and specifies the length of the authentication tag in bytes, see CCM mode. For AES-GCM and chacha20-poly1305, the authTagLength option defaults to 16 bytes and must be set to a different value if a different length is used.
The algorithm is dependent on OpenSSL, examples are 'aes192', etc. On recent OpenSSL releases, openssl list -cipher-algorithms will display the available cipher algorithms.
The key is the raw key used by the algorithm and iv is an initialization vector. Both arguments must be 'utf8' encoded strings, Buffers, TypedArray, or DataViews. The key may optionally be a KeyObject of type secret. If the cipher does not need an initialization vector, iv may be null.
When passing strings for key or iv, please consider caveats when using strings as inputs to cryptographic APIs.
Initialization vectors should be unpredictable and unique; ideally, they will be cryptographically random. They do not have to be secret: IVs are typically just added to ciphertext messages unencrypted. It may sound contradictory that something has to be unpredictable and unique, but does not have to be secret; remember that an attacker must not be able to predict ahead of time what a given IV will be.
crypto.createDiffieHellman(prime[, primeEncoding][, generator][, generatorEncoding])#
prime<string>|<ArrayBuffer>|<Buffer>|<TypedArray>|<DataView>primeEncoding<string>The encoding of theprimestring.generator<number>|<string>|<ArrayBuffer>|<Buffer>|<TypedArray>|<DataView>Default:2generatorEncoding<string>The encoding of thegeneratorstring.- Returns:
<DiffieHellman>
Creates a DiffieHellman key exchange object using the supplied prime and an optional specific generator.
The generator argument can be a number, string, or Buffer. If generator is not specified, the value 2 is used.
If primeEncoding is specified, prime is expected to be a string; otherwise a Buffer, TypedArray, or DataView is expected.
If generatorEncoding is specified, generator is expected to be a string; otherwise a number, Buffer, TypedArray, or DataView is expected.
crypto.createDiffieHellman(primeLength[, generator])#
primeLength<number>generator<number>Default:2- Returns:
<DiffieHellman>
Creates a DiffieHellman key exchange object and generates a prime of primeLength bits using an optional specific numeric generator. If generator is not specified, the value 2 is used.
crypto.createDiffieHellmanGroup(name)#
name<string>- Returns:
<DiffieHellmanGroup>
An alias for crypto.getDiffieHellman()
crypto.createECDH(curveName)#
Creates an Elliptic Curve Diffie-Hellman (ECDH) key exchange object using a predefined curve specified by the curveName string. Use crypto.getCurves() to obtain a list of available curve names. On recent OpenSSL releases, openssl ecparam -list_curves will also display the name and description of each available elliptic curve.
crypto.createHash(algorithm[, options])#
algorithm<string>options<Object>stream.transformoptions- Returns:
<Hash>
Creates and returns a Hash object that can be used to generate hash digests using the given algorithm. Optional options argument controls stream behavior. For XOF hash functions such as 'shake256', the outputLength option can be used to specify the desired output length in bytes.
The algorithm is dependent on the available algorithms supported by the version of OpenSSL on the platform. Examples are 'sha256', 'sha512', etc. On recent releases of OpenSSL, openssl list -digest-algorithms will display the available digest algorithms.
Example: generating the sha256 sum of a file
import { createReadStream, } from 'node:fs'; import { argv } from 'node:process'; const { createHash, } = await import('node:crypto'); const filename = argv[2]; const hash = createHash('sha256'); const input = createReadStream(filename); input.on('readable', () => { // Only one element is going to be produced by the // hash stream. const data = input.read(); if (data) hash.update(data); else { console.log(`${hash.digest('hex')} ${filename}`); } });const { createReadStream, } = require('node:fs'); const { createHash, } = require('node:crypto'); const { argv } = require('node:process'); const filename = argv[2]; const hash = createHash('sha256'); const input = createReadStream(filename); input.on('readable', () => { // Only one element is going to be produced by the // hash stream. const data = input.read(); if (data) hash.update(data); else { console.log(`${hash.digest('hex')} ${filename}`); } });
crypto.createHmac(algorithm, key[, options])#
algorithm<string>key<string>|<ArrayBuffer>|<Buffer>|<TypedArray>|<DataView>|<KeyObject>|<CryptoKey>options<Object>stream.transformoptionsencoding<string>The string encoding to use whenkeyis a string.
- Returns:
<Hmac>
Creates and returns an Hmac object that uses the given algorithm and key. Optional options argument controls stream behavior.
The algorithm is dependent on the available algorithms supported by the version of OpenSSL on the platform. Examples are 'sha256', 'sha512', etc. On recent releases of OpenSSL, openssl list -digest-algorithms will display the available digest algorithms.
The key is the HMAC key used to generate the cryptographic HMAC hash. If it is a KeyObject, its type must be secret. If it is a string, please consider caveats when using strings as inputs to cryptographic APIs. If it was obtained from a cryptographically secure source of entropy, such as crypto.randomBytes() or crypto.generateKey(), its length should not exceed the block size of algorithm (e.g., 512 bits for SHA-256).
Example: generating the sha256 HMAC of a file
import { createReadStream, } from 'node:fs'; import { argv } from 'node:process'; const { createHmac, } = await import('node:crypto'); const filename = argv[2]; const hmac = createHmac('sha256', 'a secret'); const input = createReadStream(filename); input.on('readable', () => { // Only one element is going to be produced by the // hash stream. const data = input.read(); if (data) hmac.update(data); else { console.log(`${hmac.digest('hex')} ${filename}`); } });const { createReadStream, } = require('node:fs'); const { createHmac, } = require('node:crypto'); const { argv } = require('node:process'); const filename = argv[2]; const hmac = createHmac('sha256', 'a secret'); const input = createReadStream(filename); input.on('readable', () => { // Only one element is going to be produced by the // hash stream. const data = input.read(); if (data) hmac.update(data); else { console.log(`${hmac.digest('hex')} ${filename}`); } });
crypto.createPrivateKey(key)#
key<Object>|<string>|<ArrayBuffer>|<Buffer>|<TypedArray>|<DataView>key<string>|<ArrayBuffer>|<Buffer>|<TypedArray>|<DataView>|<Object>The key material, either in PEM, DER, or JWK format.format<string>Must be'pem','der', or ''jwk'. Default:'pem'.type<string>Must be'pkcs1','pkcs8'or'sec1'. This option is required only if theformatis'der'and ignored otherwise.passphrase<string>|<Buffer>The passphrase to use for decryption.encoding<string>The string encoding to use whenkeyis a string.
- Returns:
<KeyObject>
Creates and returns a new key object containing a private key. If key is a string or Buffer, format is assumed to be 'pem'; otherwise, key must be an object with the properties described above.
If the private key is encrypted, a passphrase must be specified. The length of the passphrase is limited to 1024 bytes.
crypto.createPublicKey(key)#
key<Object>|<string>|<ArrayBuffer>|<Buffer>|<TypedArray>|<DataView>key<string>|<ArrayBuffer>|<Buffer>|<TypedArray>|<DataView>|<Object>The key material, either in PEM, DER, or JWK format.format<string>Must be'pem','der', or'jwk'. Default:'pem'.type<string>Must be'pkcs1'or'spki'. This option is required only if theformatis'der'and ignored otherwise.encoding<string>The string encoding to use whenkeyis a string.
- Returns:
<KeyObject>
Creates and returns a new key object containing a public key. If key is a string or Buffer, format is assumed to be 'pem'; if key is a KeyObject with type 'private', the public key is derived from the given private key; otherwise, key must be an object with the properties described above.
If the format is 'pem', the 'key' may also be an X.509 certificate.
Because public keys can be derived from private keys, a private key may be passed instead of a public key. In that case, this function behaves as if crypto.createPrivateKey() had been called, except that the type of the returned KeyObject will be 'public' and that the private key cannot be extracted from the returned KeyObject. Similarly, if a KeyObject with type 'private' is given, a new KeyObject with type 'public' will be returned and it will be impossible to extract the private key from the returned object.
crypto.createSecretKey(key[, encoding])#
key<string>|<ArrayBuffer>|<Buffer>|<TypedArray>|<DataView>encoding<string>The string encoding whenkeyis a string.- Returns:
<KeyObject>
Creates and returns a new key object containing a secret key for symmetric encryption or Hmac.
crypto.createSign(algorithm[, options])#
algorithm<string>options<Object>stream.Writableoptions- Returns:
<Sign>
Creates and returns a Sign object that uses the given algorithm. Use crypto.getHashes() to obtain the names of the available digest algorithms. Optional options argument controls the stream.Writable behavior.
In some cases, a Sign instance can be created using the name of a signature algorithm, such as 'RSA-SHA256', instead of a digest algorithm. This will use the corresponding digest algorithm. This does not work for all signature algorithms, such as 'ecdsa-with-SHA256', so it is best to always use digest algorithm names.
crypto.createVerify(algorithm[, options])#
algorithm<string>options<Object>stream.Writableoptions- Returns:
<Verify>
Creates and returns a Verify object that uses the given algorithm. Use crypto.getHashes() to obtain an array of names of the available signing algorithms. Optional options argument controls the stream.Writable behavior.
In some cases, a Verify instance can be created using the name of a signature algorithm, such as 'RSA-SHA256', instead of a digest algorithm. This will use the corresponding digest algorithm. This does not work for all signature algorithms, such as 'ecdsa-with-SHA256', so it is best to always use digest algorithm names.
crypto.decapsulate(key, ciphertext[, callback])#
Stability: 1.2 - Release candidate
key<Object>|<string>|<ArrayBuffer>|<Buffer>|<TypedArray>|<DataView>|<KeyObject>Private Keyciphertext<ArrayBuffer>|<Buffer>|<TypedArray>|<DataView>callback<Function>- Returns:
<Buffer>if thecallbackfunction is not provided.
Key decapsulation using a KEM algorithm with a private key.
Supported key types and their KEM algorithms are:
'rsa'2 RSA Secret Value Encapsulation'ec'3 DHKEM(P-256, HKDF-SHA256), DHKEM(P-384, HKDF-SHA256), DHKEM(P-521, HKDF-SHA256)'x25519'3 DHKEM(X25519, HKDF-SHA256)'x448'3 DHKEM(X448, HKDF-SHA512)'ml-kem-512'1 ML-KEM'ml-kem-768'1 ML-KEM'ml-kem-1024'1 ML-KEM
If key is not a KeyObject, this function behaves as if key had been passed to crypto.createPrivateKey().
If the callback function is provided this function uses libuv's threadpool.
crypto.diffieHellman(options[, callback])#
options<Object>privateKey<KeyObject>publicKey<KeyObject>
callback<Function>- Returns:
<Buffer>if thecallbackfunction is not provided.
Computes the Diffie-Hellman shared secret based on a privateKey and a publicKey. Both keys must have the same asymmetricKeyType and must support either the DH or ECDH operation.
If the callback function is provided this function uses libuv's threadpool.
crypto.encapsulate(key[, callback])#
Stability: 1.2 - Release candidate
key<Object>|<string>|<ArrayBuffer>|<Buffer>|<TypedArray>|<DataView>|<KeyObject>Public Keycallback<Function>- Returns:
<Object>if thecallbackfunction is not provided.
Key encapsulation using a KEM algorithm with a public key.
Supported key types and their KEM algorithms are:
'rsa'2 RSA Secret Value Encapsulation'ec'3 DHKEM(P-256, HKDF-SHA256), DHKEM(P-384, HKDF-SHA256), DHKEM(P-521, HKDF-SHA256)'x25519'3 DHKEM(X25519, HKDF-SHA256)'x448'3 DHKEM(X448, HKDF-SHA512)'ml-kem-512'1 ML-KEM'ml-kem-768'1 ML-KEM'ml-kem-1024'1 ML-KEM
If key is not a KeyObject, this function behaves as if key had been passed to crypto.createPublicKey().
If the callback function is provided this function uses libuv's threadpool.
crypto.fips#
Stability: 0 - Deprecated
Property for checking and controlling whether a FIPS compliant crypto provider is currently in use. Setting to true requires a FIPS build of Node.js.
This property is deprecated. Please use crypto.setFips() and crypto.getFips() instead.
crypto.generateKey(type, options, callback)#
type<string>The intended use of the generated secret key. Currently accepted values are'hmac'and'aes'.options<Object>length<number>The bit length of the key to generate. This must be a value greater than 0.- If
typeis'hmac', the minimum is 8, and the maximum length is 231-1. If the value is not a multiple of 8, the generated key will be truncated toMath.floor(length / 8). - If
typeis'aes', the length must be one of128,192, or256.
- If
callback<Function>err<Error>key<KeyObject>
Asynchronously generates a new random secret key of the given length. The type will determine which validations will be performed on the length.
const { generateKey, } = await import('node:crypto'); generateKey('hmac', { length: 512 }, (err, key) => { if (err) throw err; console.log(key.export().toString('hex')); // 46e..........620 });const { generateKey, } = require('node:crypto'); generateKey('hmac', { length: 512 }, (err, key) => { if (err) throw err; console.log(key.export().toString('hex')); // 46e..........620 });
The size of a generated HMAC key should not exceed the block size of the underlying hash function. See crypto.createHmac() for more information.
crypto.generateKeyPair(type, options, callback)#
type<string>The asymmetric key type to generate. See the supported asymmetric key types.options<Object>modulusLength<number>Key size in bits (RSA, DSA).publicExponent<number>Public exponent (RSA). Default:0x10001.hashAlgorithm<string>Name of the message digest (RSA-PSS).mgf1HashAlgorithm<string>Name of the message digest used by MGF1 (RSA-PSS).saltLength<number>Minimal salt length in bytes (RSA-PSS).divisorLength<number>Size ofqin bits (DSA).namedCurve<string>Name of the curve to use (EC).prime<Buffer>The prime parameter (DH).primeLength<number>Prime length in bits (DH).generator<number>Custom generator (DH). Default:2.groupName<string>Diffie-Hellman group name (DH). Seecrypto.getDiffieHellman().paramEncoding<string>Must be'named'or'explicit'(EC). Default:'named'.publicKeyEncoding<Object>SeekeyObject.export().privateKeyEncoding<Object>SeekeyObject.export().
callback<Function>err<Error>publicKey<string>|<Buffer>|<KeyObject>privateKey<string>|<Buffer>|<KeyObject>
Generates a new asymmetric key pair of the given type. See the supported asymmetric key types.
If a publicKeyEncoding or privateKeyEncoding was specified, this function behaves as if keyObject.export() had been called on its result. Otherwise, the respective part of the key is returned as a KeyObject.
It is recommended to encode public keys as 'spki' and private keys as 'pkcs8' with encryption for long-term storage:
const { generateKeyPair, } = await import('node:crypto'); generateKeyPair('rsa', { modulusLength: 4096, publicKeyEncoding: { type: 'spki', format: 'pem', }, privateKeyEncoding: { type: 'pkcs8', format: 'pem', cipher: 'aes-256-cbc', passphrase: 'top secret', }, }, (err, publicKey, privateKey) => { // Handle errors and use the generated key pair. });const { generateKeyPair, } = require('node:crypto'); generateKeyPair('rsa', { modulusLength: 4096, publicKeyEncoding: { type: 'spki', format: 'pem', }, privateKeyEncoding: { type: 'pkcs8', format: 'pem', cipher: 'aes-256-cbc', passphrase: 'top secret', }, }, (err, publicKey, privateKey) => { // Handle errors and use the generated key pair. });
On completion, callback will be called with err set to undefined and publicKey / privateKey representing the generated key pair.
If this method is invoked as its util.promisify()ed version, it returns a Promise for an Object with publicKey and privateKey properties.
crypto.generateKeyPairSync(type, options)#
type<string>The asymmetric key type to generate. See the supported asymmetric key types.options<Object>modulusLength<number>Key size in bits (RSA, DSA).publicExponent<number>Public exponent (RSA). Default:0x10001.hashAlgorithm<string>Name of the message digest (RSA-PSS).mgf1HashAlgorithm<string>Name of the message digest used by MGF1 (RSA-PSS).saltLength<number>Minimal salt length in bytes (RSA-PSS).divisorLength<number>Size ofqin bits (DSA).namedCurve<string>Name of the curve to use (EC).prime<Buffer>The prime parameter (DH).primeLength<number>Prime length in bits (DH).generator<number>Custom generator (DH). Default:2.groupName<string>Diffie-Hellman group name (DH). Seecrypto.getDiffieHellman().paramEncoding<string>Must be'named'or'explicit'(EC). Default:'named'.publicKeyEncoding<Object>SeekeyObject.export().privateKeyEncoding<Object>SeekeyObject.export().
- Returns:
<Object>publicKey<string>|<Buffer>|<KeyObject>privateKey<string>|<Buffer>|<KeyObject>
Generates a new asymmetric key pair of the given type. See the supported asymmetric key types.
If a publicKeyEncoding or privateKeyEncoding was specified, this function behaves as if keyObject.export() had been called on its result. Otherwise, the respective part of the key is returned as a KeyObject.
When encoding public keys, it is recommended to use 'spki'. When encoding private keys, it is recommended to use 'pkcs8' with a strong passphrase, and to keep the passphrase confidential.
const { generateKeyPairSync, } = await import('node:crypto'); const { publicKey, privateKey, } = generateKeyPairSync('rsa', { modulusLength: 4096, publicKeyEncoding: { type: 'spki', format: 'pem', }, privateKeyEncoding: { type: 'pkcs8', format: 'pem', cipher: 'aes-256-cbc', passphrase: 'top secret', }, });const { generateKeyPairSync, } = require('node:crypto'); const { publicKey, privateKey, } = generateKeyPairSync('rsa', { modulusLength: 4096, publicKeyEncoding: { type: 'spki', format: 'pem', }, privateKeyEncoding: { type: 'pkcs8', format: 'pem', cipher: 'aes-256-cbc', passphrase: 'top secret', }, });
The return value { publicKey, privateKey } represents the generated key pair. When PEM encoding was selected, the respective key will be a string, otherwise it will be a buffer containing the data encoded as DER.
crypto.generateKeySync(type, options)#
type<string>The intended use of the generated secret key. Currently accepted values are'hmac'and'aes'.options<Object>length<number>The bit length of the key to generate.- If
typeis'hmac', the minimum is 8, and the maximum length is 231-1. If the value is not a multiple of 8, the generated key will be truncated toMath.floor(length / 8). - If
typeis'aes', the length must be one of128,192, or256.
- If
- Returns:
<KeyObject>
Synchronously generates a new random secret key of the given length. The type will determine which validations will be performed on the length.
const { generateKeySync, } = await import('node:crypto'); const key = generateKeySync('hmac', { length: 512 }); console.log(key.export().toString('hex')); // e89..........41econst { generateKeySync, } = require('node:crypto'); const key = generateKeySync('hmac', { length: 512 }); console.log(key.export().toString('hex')); // e89..........41e
The size of a generated HMAC key should not exceed the block size of the underlying hash function. See crypto.createHmac() for more information.
crypto.generatePrime(size[, options], callback)#
size<number>The size (in bits) of the prime to generate.options<Object>add<ArrayBuffer>|<SharedArrayBuffer>|<TypedArray>|<Buffer>|<DataView>|<bigint>rem<ArrayBuffer>|<SharedArrayBuffer>|<TypedArray>|<Buffer>|<DataView>|<bigint>safe<boolean>Default:false.bigint<boolean>Whentrue, the generated prime is returned as abigint.
callback<Function>err<Error>prime<ArrayBuffer>|<bigint>
Generates a pseudorandom prime of size bits.
If options.safe is true, the prime will be a safe prime -- that is, (prime - 1) / 2 will also be a prime.
The options.add and options.rem parameters can be used to enforce additional requirements, e.g., for Diffie-Hellman:
- If
options.addandoptions.remare both set, the prime will satisfy the condition thatprime % add = rem. - If only
options.addis set andoptions.safeis nottrue, the prime will satisfy the condition thatprime % add = 1. - If only
options.addis set andoptions.safeis set totrue, the prime will instead satisfy the condition thatprime % add = 3. This is necessary becauseprime % add = 1foroptions.add > 2would contradict the condition enforced byoptions.safe. options.remis ignored ifoptions.addis not given.
Both options.add and options.rem must be encoded as big-endian sequences if given as an ArrayBuffer, SharedArrayBuffer, TypedArray, Buffer, or DataView.
By default, the prime is encoded as a big-endian sequence of octets in an <ArrayBuffer>. If the bigint option is true, then a <bigint> is provided.
The size of the prime will have a direct impact on how long it takes to generate the prime. The larger the size, the longer it will take. Because we use OpenSSL's BN_generate_prime_ex function, which provides only minimal control over our ability to interrupt the generation process, it is not recommended to generate overly large primes, as doing so may make the process unresponsive.
crypto.generatePrimeSync(size[, options])#
size<number>The size (in bits) of the prime to generate.options<Object>add<ArrayBuffer>|<SharedArrayBuffer>|<TypedArray>|<Buffer>|<DataView>|<bigint>rem<ArrayBuffer>|<SharedArrayBuffer>|<TypedArray>|<Buffer>|<DataView>|<bigint>safe<boolean>Default:false.bigint<boolean>Whentrue, the generated prime is returned as abigint.
- Returns:
<ArrayBuffer>|<bigint>
Generates a pseudorandom prime of size bits.
If options.safe is true, the prime will be a safe prime -- that is, (prime - 1) / 2 will also be a prime.
The options.add and options.rem parameters can be used to enforce additional requirements, e.g., for Diffie-Hellman:
- If
options.addandoptions.remare both set, the prime will satisfy the condition thatprime % add = rem. - If only
options.addis set andoptions.safeis nottrue, the prime will satisfy the condition thatprime % add = 1. - If only
options.addis set andoptions.safeis set totrue, the prime will instead satisfy the condition thatprime % add = 3. This is necessary becauseprime % add = 1foroptions.add > 2would contradict the condition enforced byoptions.safe. options.remis ignored ifoptions.addis not given.
Both options.add and options.rem must be encoded as big-endian sequences if given as an ArrayBuffer, SharedArrayBuffer, TypedArray, Buffer, or DataView.
By default, the prime is encoded as a big-endian sequence of octets in an <ArrayBuffer>. If the bigint option is true, then a <bigint> is provided.
The size of the prime will have a direct impact on how long it takes to generate the prime. The larger the size, the longer it will take. Because we use OpenSSL's BN_generate_prime_ex function, which provides only minimal control over our ability to interrupt the generation process, it is not recommended to generate overly large primes, as doing so may make the process unresponsive.
crypto.getCipherInfo(nameOrNid[, options])#
nameOrNid<string>|<number>The name or nid of the cipher to query.options<Object>- Returns:
<Object>name<string>The name of the ciphernid<number>The nid of the cipherblockSize<number>The block size of the cipher in bytes. This property is omitted whenmodeis'stream'.ivLength<number>The expected or default initialization vector length in bytes. This property is omitted if the cipher does not use an initialization vector.keyLength<number>The expected or default key length in bytes.mode<string>The cipher mode. One of'cbc','ccm','cfb','ctr','ecb','gcm','ocb','ofb','stream','wrap','xts'.
Returns information about a given cipher.
Some ciphers accept variable length keys and initialization vectors. By default, the crypto.getCipherInfo() method will return the default values for these ciphers. To test if a given key length or iv length is acceptable for given cipher, use the keyLength and ivLength options. If the given values are unacceptable, undefined will be returned.
crypto.getCiphers()#
- Returns:
<string[]>An array with the names of the supported cipher algorithms.
const { getCiphers, } = await import('node:crypto'); console.log(getCiphers()); // ['aes-128-cbc', 'aes-128-ccm', ...]const { getCiphers, } = require('node:crypto'); console.log(getCiphers()); // ['aes-128-cbc', 'aes-128-ccm', ...]
crypto.getCurves()#
- Returns:
<string[]>An array with the names of the supported elliptic curves.
const { getCurves, } = await import('node:crypto'); console.log(getCurves()); // ['Oakley-EC2N-3', 'Oakley-EC2N-4', ...]const { getCurves, } = require('node:crypto'); console.log(getCurves()); // ['Oakley-EC2N-3', 'Oakley-EC2N-4', ...]
crypto.getDiffieHellman(groupName)#
groupName<string>- Returns:
<DiffieHellmanGroup>
Creates a predefined DiffieHellmanGroup key exchange object. The supported groups are listed in the documentation for DiffieHellmanGroup.
The returned object mimics the interface of objects created by crypto.createDiffieHellman(), but will not allow changing the keys (with diffieHellman.setPublicKey(), for example). The advantage of using this method is that the parties do not have to generate nor exchange a group modulus beforehand, saving both processor and communication time.
Example (obtaining a shared secret):
const { getDiffieHellman, } = await import('node:crypto'); const alice = getDiffieHellman('modp14'); const bob = getDiffieHellman('modp14'); alice.generateKeys(); bob.generateKeys(); const aliceSecret = alice.computeSecret(bob.getPublicKey(), null, 'hex'); const bobSecret = bob.computeSecret(alice.getPublicKey(), null, 'hex'); /* aliceSecret and bobSecret should be the same */ console.log(aliceSecret === bobSecret);const { getDiffieHellman, } = require('node:crypto'); const alice = getDiffieHellman('modp14'); const bob = getDiffieHellman('modp14'); alice.generateKeys(); bob.generateKeys(); const aliceSecret = alice.computeSecret(bob.getPublicKey(), null, 'hex'); const bobSecret = bob.computeSecret(alice.getPublicKey(), null, 'hex'); /* aliceSecret and bobSecret should be the same */ console.log(aliceSecret === bobSecret);
crypto.getFips()#
crypto.getHashes()#
- Returns:
<string[]>An array of the names of the supported hash algorithms, such as'RSA-SHA256'. Hash algorithms are also called "digest" algorithms.
const { getHashes, } = await import('node:crypto'); console.log(getHashes()); // ['DSA', 'DSA-SHA', 'DSA-SHA1', ...]const { getHashes, } = require('node:crypto'); console.log(getHashes()); // ['DSA', 'DSA-SHA', 'DSA-SHA1', ...]
crypto.getRandomValues(typedArray)#
typedArray<Buffer>|<TypedArray>|<DataView>|<ArrayBuffer>- Returns:
<Buffer>|<TypedArray>|<DataView>|<ArrayBuffer>ReturnstypedArray.
A convenient alias for crypto.webcrypto.getRandomValues(). This implementation is not compliant with the Web Crypto spec, to write web-compatible code use crypto.webcrypto.getRandomValues() instead.
crypto.hash(algorithm, data[, options])#
algorithm<string>|<undefined>data<string>|<Buffer>|<TypedArray>|<DataView>Whendatais a string, it will be encoded as UTF-8 before being hashed. If a different input encoding is desired for a string input, user could encode the string into aTypedArrayusing eitherTextEncoderorBuffer.from()and passing the encodedTypedArrayinto this API instead.options<Object>|<string>- Returns:
<string>|<Buffer>
A utility for creating one-shot hash digests of data. It can be faster than the object-based crypto.createHash() when hashing a smaller amount of data (<= 5MB) that's readily available. If the data can be big or if it is streamed, it's still recommended to use crypto.createHash() instead.
The algorithm is dependent on the available algorithms supported by the version of OpenSSL on the platform. Examples are 'sha256', 'sha512', etc. On recent releases of OpenSSL, openssl list -digest-algorithms will display the available digest algorithms.
If options is a string, then it specifies the outputEncoding.
Example:
const crypto = require('node:crypto'); const { Buffer } = require('node:buffer'); // Hashing a string and return the result as a hex-encoded string. const string = 'Node.js'; // 10b3493287f831e81a438811a1ffba01f8cec4b7 console.log(crypto.hash('sha1', string)); // Encode a base64-encoded string into a Buffer, hash it and return // the result as a buffer. const base64 = 'Tm9kZS5qcw=='; // <Buffer 10 b3 49 32 87 f8 31 e8 1a 43 88 11 a1 ff ba 01 f8 ce c4 b7> console.log(crypto.hash('sha1', Buffer.from(base64, 'base64'), 'buffer'));import crypto from 'node:crypto'; import { Buffer } from 'node:buffer'; // Hashing a string and return the result as a hex-encoded string. const string = 'Node.js'; // 10b3493287f831e81a438811a1ffba01f8cec4b7 console.log(crypto.hash('sha1', string)); // Encode a base64-encoded string into a Buffer, hash it and return // the result as a buffer. const base64 = 'Tm9kZS5qcw=='; // <Buffer 10 b3 49 32 87 f8 31 e8 1a 43 88 11 a1 ff ba 01 f8 ce c4 b7> console.log(crypto.hash('sha1', Buffer.from(base64, 'base64'), 'buffer'));
crypto.hkdf(digest, ikm, salt, info, keylen, callback)#
digest<string>The digest algorithm to use.ikm<string>|<ArrayBuffer>|<Buffer>|<TypedArray>|<DataView>|<KeyObject>The input keying material. Must be provided but can be zero-length.salt<string>|<ArrayBuffer>|<Buffer>|<TypedArray>|<DataView>The salt value. Must be provided but can be zero-length.info<string>|<ArrayBuffer>|<Buffer>|<TypedArray>|<DataView>Additional info value. Must be provided but can be zero-length, and cannot be more than 1024 bytes.keylen<number>The length of the key to generate. Must be greater than 0. The maximum allowable value is255times the number of bytes produced by the selected digest function (e.g.sha512generates 64-byte hashes, making the maximum HKDF output 16320 bytes).callback<Function>err<Error>derivedKey<ArrayBuffer>
HKDF is a simple key derivation function defined in RFC 5869. The given ikm, salt and info are used with the digest to derive a key of keylen bytes.
The supplied callback function is called with two arguments: err and derivedKey. If an errors occurs while deriving the key, err will be set; otherwise err will be null. The successfully generated derivedKey will be passed to the callback as an <ArrayBuffer>. An error will be thrown if any of the input arguments specify invalid values or types.
import { Buffer } from 'node:buffer'; const { hkdf, } = await import('node:crypto'); hkdf('sha512', 'key', 'salt', 'info', 64, (err, derivedKey) => { if (err) throw err; console.log(Buffer.from(derivedKey).toString('hex')); // '24156e2...5391653' });const { hkdf, } = require('node:crypto'); const { Buffer } = require('node:buffer'); hkdf('sha512', 'key', 'salt', 'info', 64, (err, derivedKey) => { if (err) throw err; console.log(Buffer.from(derivedKey).toString('hex')); // '24156e2...5391653' });
crypto.hkdfSync(digest, ikm, salt, info, keylen)#
digest<string>The digest algorithm to use.ikm<string>|<ArrayBuffer>|<Buffer>|<TypedArray>|<DataView>|<KeyObject>The input keying material. Must be provided but can be zero-length.salt<string>|<ArrayBuffer>|<Buffer>|<TypedArray>|<DataView>The salt value. Must be provided but can be zero-length.info<string>|<ArrayBuffer>|<Buffer>|<TypedArray>|<DataView>Additional info value. Must be provided but can be zero-length, and cannot be more than 1024 bytes.keylen<number>The length of the key to generate. Must be greater than 0. The maximum allowable value is255times the number of bytes produced by the selected digest function (e.g.sha512generates 64-byte hashes, making the maximum HKDF output 16320 bytes).- Returns:
<ArrayBuffer>
Provides a synchronous HKDF key derivation function as defined in RFC 5869. The given ikm, salt and info are used with the digest to derive a key of keylen bytes.
The successfully generated derivedKey will be returned as an <ArrayBuffer>.
An error will be thrown if any of the input arguments specify invalid values or types, or if the derived key cannot be generated.
import { Buffer } from 'node:buffer'; const { hkdfSync, } = await import('node:crypto'); const derivedKey = hkdfSync('sha512', 'key', 'salt', 'info', 64); console.log(Buffer.from(derivedKey).toString('hex')); // '24156e2...5391653'const { hkdfSync, } = require('node:crypto'); const { Buffer } = require('node:buffer'); const derivedKey = hkdfSync('sha512', 'key', 'salt', 'info', 64); console.log(Buffer.from(derivedKey).toString('hex')); // '24156e2...5391653'
crypto.pbkdf2(password, salt, iterations, keylen, digest, callback)#
password<string>|<ArrayBuffer>|<Buffer>|<TypedArray>|<DataView>salt<string>|<ArrayBuffer>|<Buffer>|<TypedArray>|<DataView>iterations<number>keylen<number>digest<string>callback<Function>
Provides an asynchronous Password-Based Key Derivation Function 2 (PBKDF2) implementation. A selected HMAC digest algorithm specified by digest is applied to derive a key of the requested byte length (keylen) from the password, salt and iterations.
The supplied callback function is called with two arguments: err and derivedKey. If an error occurs while deriving the key, err will be set; otherwise err will be null. By default, the successfully generated derivedKey will be passed to the callback as a Buffer. An error will be thrown if any of the input arguments specify invalid values or types.
The iterations argument must be a number set as high as possible. The higher the number of iterations, the more secure the derived key will be, but will take a longer amount of time to complete.
The salt should be as unique as possible. It is recommended that a salt is random and at least 16 bytes long. See NIST SP 800-132 for details.
When passing strings for password or salt, please consider caveats when using strings as inputs to cryptographic APIs.
const { pbkdf2, } = await import('node:crypto'); pbkdf2('secret', 'salt', 100000, 64, 'sha512', (err, derivedKey) => { if (err) throw err; console.log(derivedKey.toString('hex')); // '3745e48...08d59ae' });const { pbkdf2, } = require('node:crypto'); pbkdf2('secret', 'salt', 100000, 64, 'sha512', (err, derivedKey) => { if (err) throw err; console.log(derivedKey.toString('hex')); // '3745e48...08d59ae' });
An array of supported digest functions can be retrieved using crypto.getHashes().
This API uses libuv's threadpool, which can have surprising and negative performance implications for some applications; see the UV_THREADPOOL_SIZE documentation for more information.
crypto.pbkdf2Sync(password, salt, iterations, keylen, digest)#
password<string>|<Buffer>|<TypedArray>|<DataView>salt<string>|<Buffer>|<TypedArray>|<DataView>iterations<number>keylen<number>digest<string>- Returns:
<Buffer>
Provides a synchronous Password-Based Key Derivation Function 2 (PBKDF2) implementation. A selected HMAC digest algorithm specified by digest is applied to derive a key of the requested byte length (keylen) from the password, salt and iterations.
If an error occurs an Error will be thrown, otherwise the derived key will be returned as a Buffer.
The iterations argument must be a number set as high as possible. The higher the number of iterations, the more secure the derived key will be, but will take a longer amount of time to complete.
The salt should be as unique as possible. It is recommended that a salt is random and at least 16 bytes long. See NIST SP 800-132 for details.
When passing strings for password or salt, please consider caveats when using strings as inputs to cryptographic APIs.
const { pbkdf2Sync, } = await import('node:crypto'); const key = pbkdf2Sync('secret', 'salt', 100000, 64, 'sha512'); console.log(key.toString('hex')); // '3745e48...08d59ae'const { pbkdf2Sync, } = require('node:crypto'); const key = pbkdf2Sync('secret', 'salt', 100000, 64, 'sha512'); console.log(key.toString('hex')); // '3745e48...08d59ae'
An array of supported digest functions can be retrieved using crypto.getHashes().
crypto.privateDecrypt(privateKey, buffer)#
privateKey<Object>|<string>|<ArrayBuffer>|<Buffer>|<TypedArray>|<DataView>|<KeyObject>|<CryptoKey>oaepHash<string>The hash function to use for OAEP padding and MGF1. Default:'sha1'oaepLabel<string>|<ArrayBuffer>|<Buffer>|<TypedArray>|<DataView>The label to use for OAEP padding. If not specified, no label is used.padding<crypto.constants>An optional padding value defined incrypto.constants, which may be:crypto.constants.RSA_NO_PADDING,crypto.constants.RSA_PKCS1_PADDING, orcrypto.constants.RSA_PKCS1_OAEP_PADDING.
buffer<string>|<ArrayBuffer>|<Buffer>|<TypedArray>|<DataView>- Returns:
<Buffer>A newBufferwith the decrypted content.
Decrypts buffer with privateKey. buffer was previously encrypted using the corresponding public key, for example using crypto.publicEncrypt().
If privateKey is not a KeyObject, this function behaves as if privateKey had been passed to crypto.createPrivateKey(). If it is an object, the padding property can be passed. Otherwise, this function uses RSA_PKCS1_OAEP_PADDING.
Using crypto.constants.RSA_PKCS1_PADDING in crypto.privateDecrypt() requires OpenSSL to support implicit rejection (rsa_pkcs1_implicit_rejection). If the version of OpenSSL used by Node.js does not support this feature, attempting to use RSA_PKCS1_PADDING will fail.
crypto.privateEncrypt(privateKey, buffer)#
privateKey<Object>|<string>|<ArrayBuffer>|<Buffer>|<TypedArray>|<DataView>|<KeyObject>|<CryptoKey>key<string>|<ArrayBuffer>|<Buffer>|<TypedArray>|<DataView>|<KeyObject>|<CryptoKey>A PEM encoded private key.passphrase<string>|<ArrayBuffer>|<Buffer>|<TypedArray>|<DataView>An optional passphrase for the private key.padding<crypto.constants>An optional padding value defined incrypto.constants, which may be:crypto.constants.RSA_NO_PADDINGorcrypto.constants.RSA_PKCS1_PADDING.encoding<string>The string encoding to use whenbuffer,key, orpassphraseare strings.
buffer<string>|<ArrayBuffer>|<Buffer>|<TypedArray>|<DataView>- Returns:
<Buffer>A newBufferwith the encrypted content.
Encrypts buffer with privateKey. The returned data can be decrypted using the corresponding public key, for example using crypto.publicDecrypt().
If privateKey is not a KeyObject, this function behaves as if privateKey had been passed to crypto.createPrivateKey(). If it is an object, the padding property can be passed. Otherwise, this function uses RSA_PKCS1_PADDING.
crypto.publicDecrypt(key, buffer)#
key<Object>|<string>|<ArrayBuffer>|<Buffer>|<TypedArray>|<DataView>|<KeyObject>|<CryptoKey>passphrase<string>|<ArrayBuffer>|<Buffer>|<TypedArray>|<DataView>An optional passphrase for the private key.padding<crypto.constants>An optional padding value defined incrypto.constants, which may be:crypto.constants.RSA_NO_PADDINGorcrypto.constants.RSA_PKCS1_PADDING.encoding<string>The string encoding to use whenbuffer,key, orpassphraseare strings.
buffer<string>|<ArrayBuffer>|<Buffer>|<TypedArray>|<DataView>- Returns:
<Buffer>A newBufferwith the decrypted content.
Decrypts buffer with key.buffer was previously encrypted using the corresponding private key, for example using crypto.privateEncrypt().
If key is not a KeyObject, this function behaves as if key had been passed to crypto.createPublicKey(). If it is an object, the padding property can be passed. Otherwise, this function uses RSA_PKCS1_PADDING.
Because RSA public keys can be derived from private keys, a private key may be passed instead of a public key.
crypto.publicEncrypt(key, buffer)#
key<Object>|<string>|<ArrayBuffer>|<Buffer>|<TypedArray>|<DataView>|<KeyObject>|<CryptoKey>key<string>|<ArrayBuffer>|<Buffer>|<TypedArray>|<DataView>|<KeyObject>|<CryptoKey>A PEM encoded public or private key,<KeyObject>, or<CryptoKey>.oaepHash<string>The hash function to use for OAEP padding and MGF1. Default:'sha1'oaepLabel<string>|<ArrayBuffer>|<Buffer>|<TypedArray>|<DataView>The label to use for OAEP padding. If not specified, no label is used.passphrase<string>|<ArrayBuffer>|<Buffer>|<TypedArray>|<DataView>An optional passphrase for the private key.padding<crypto.constants>An optional padding value defined incrypto.constants, which may be:crypto.constants.RSA_NO_PADDING,crypto.constants.RSA_PKCS1_PADDING, orcrypto.constants.RSA_PKCS1_OAEP_PADDING.encoding<string>The string encoding to use whenbuffer,key,oaepLabel, orpassphraseare strings.
buffer<string>|<ArrayBuffer>|<Buffer>|<TypedArray>|<DataView>- Returns:
<Buffer>A newBufferwith the encrypted content.
Encrypts the content of buffer with key and returns a new Buffer with encrypted content. The returned data can be decrypted using the corresponding private key, for example using crypto.privateDecrypt().
If key is not a KeyObject, this function behaves as if key had been passed to crypto.createPublicKey(). If it is an object, the padding property can be passed. Otherwise, this function uses RSA_PKCS1_OAEP_PADDING.
Because RSA public keys can be derived from private keys, a private key may be passed instead of a public key.
crypto.randomBytes(size[, callback])#
size<number>The number of bytes to generate. Thesizemust not be larger than2**31 - 1.callback<Function>- Returns:
<Buffer>if thecallbackfunction is not provided.
Generates cryptographically strong pseudorandom data. The size argument is a number indicating the number of bytes to generate.
If a callback function is provided, the bytes are generated asynchronously and the callback function is invoked with two arguments: err and buf. If an error occurs, err will be an Error object; otherwise it is null. The buf argument is a Buffer containing the generated bytes.
// Asynchronous const { randomBytes, } = await import('node:crypto'); randomBytes(256, (err, buf) => { if (err) throw err; console.log(`${buf.length} bytes of random data: ${buf.toString('hex')}`); });// Asynchronous const { randomBytes, } = require('node:crypto'); randomBytes(256, (err, buf) => { if (err) throw err; console.log(`${buf.length} bytes of random data: ${buf.toString('hex')}`); });
If the callback function is not provided, the random bytes are generated synchronously and returned as a Buffer. An error will be thrown if there is a problem generating the bytes.
// Synchronous const { randomBytes, } = await import('node:crypto'); const buf = randomBytes(256); console.log( `${buf.length} bytes of random data: ${buf.toString('hex')}`);// Synchronous const { randomBytes, } = require('node:crypto'); const buf = randomBytes(256); console.log( `${buf.length} bytes of random data: ${buf.toString('hex')}`);
The crypto.randomBytes() method will not complete until there is sufficient entropy available. This should normally never take longer than a few milliseconds. The only time when generating the random bytes may conceivably block for a longer period of time is right after boot, when the whole system is still low on entropy.
This API uses libuv's threadpool, which can have surprising and negative performance implications for some applications; see the UV_THREADPOOL_SIZE documentation for more information.
The asynchronous version of crypto.randomBytes() is carried out in a single threadpool request. To minimize threadpool task length variation, partition large randomBytes requests when doing so as part of fulfilling a client request.
crypto.randomFill(buffer[, offset][, size], callback)#
buffer<ArrayBuffer>|<Buffer>|<TypedArray>|<DataView>Must be supplied. The size of the providedbuffermust not be larger than2**31 - 1.offset<number>Default:0size<number>Default:buffer.length - offset. Thesizemust not be larger than2**31 - 1.callback<Function>function(err, buf) {}.
This function is similar to crypto.randomBytes() but requires the first argument to be a Buffer that will be filled. It also requires that a callback is passed in.
If the callback function is not provided, an error will be thrown.
import { Buffer } from 'node:buffer'; const { randomFill } = await import('node:crypto'); const buf = Buffer.alloc(10); randomFill(buf, (err, buf) => { if (err) throw err; console.log(buf.toString('hex')); }); randomFill(buf, 5, (err, buf) => { if (err) throw err; console.log(buf.toString('hex')); }); // The above is equivalent to the following: randomFill(buf, 5, 5, (err, buf) => { if (err) throw err; console.log(buf.toString('hex')); });const { randomFill } = require('node:crypto'); const { Buffer } = require('node:buffer'); const buf = Buffer.alloc(10); randomFill(buf, (err, buf) => { if (err) throw err; console.log(buf.toString('hex')); }); randomFill(buf, 5, (err, buf) => { if (err) throw err; console.log(buf.toString('hex')); }); // The above is equivalent to the following: randomFill(buf, 5, 5, (err, buf) => { if (err) throw err; console.log(buf.toString('hex')); });
Any ArrayBuffer, TypedArray, or DataView instance may be passed as buffer.
While this includes instances of Float32Array and Float64Array, this function should not be used to generate random floating-point numbers. The result may contain +Infinity, -Infinity, and NaN, and even if the array contains finite numbers only, they are not drawn from a uniform random distribution and have no meaningful lower or upper bounds.
import { Buffer } from 'node:buffer'; const { randomFill } = await import('node:crypto'); const a = new Uint32Array(10); randomFill(a, (err, buf) => { if (err) throw err; console.log(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength) .toString('hex')); }); const b = new DataView(new ArrayBuffer(10)); randomFill(b, (err, buf) => { if (err) throw err; console.log(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength) .toString('hex')); }); const c = new ArrayBuffer(10); randomFill(c, (err, buf) => { if (err) throw err; console.log(Buffer.from(buf).toString('hex')); });const { randomFill } = require('node:crypto'); const { Buffer } = require('node:buffer'); const a = new Uint32Array(10); randomFill(a, (err, buf) => { if (err) throw err; console.log(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength) .toString('hex')); }); const b = new DataView(new ArrayBuffer(10)); randomFill(b, (err, buf) => { if (err) throw err; console.log(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength) .toString('hex')); }); const c = new ArrayBuffer(10); randomFill(c, (err, buf) => { if (err) throw err; console.log(Buffer.from(buf).toString('hex')); });
This API uses libuv's threadpool, which can have surprising and negative performance implications for some applications; see the UV_THREADPOOL_SIZE documentation for more information.
The asynchronous version of crypto.randomFill() is carried out in a single threadpool request. To minimize threadpool task length variation, partition large randomFill requests when doing so as part of fulfilling a client request.
crypto.randomFillSync(buffer[, offset][, size])#
buffer<ArrayBuffer>|<Buffer>|<TypedArray>|<DataView>Must be supplied. The size of the providedbuffermust not be larger than2**31 - 1.offset<number>Default:0size<number>Default:buffer.length - offset. Thesizemust not be larger than2**31 - 1.- Returns:
<ArrayBuffer>|<Buffer>|<TypedArray>|<DataView>The object passed asbufferargument.
Synchronous version of crypto.randomFill().
import { Buffer } from 'node:buffer'; const { randomFillSync } = await import('node:crypto'); const buf = Buffer.alloc(10); console.log(randomFillSync(buf).toString('hex')); randomFillSync(buf, 5); console.log(buf.toString('hex')); // The above is equivalent to the following: randomFillSync(buf, 5, 5); console.log(buf.toString('hex'));const { randomFillSync } = require('node:crypto'); const { Buffer } = require('node:buffer'); const buf = Buffer.alloc(10); console.log(randomFillSync(buf).toString('hex')); randomFillSync(buf, 5); console.log(buf.toString('hex')); // The above is equivalent to the following: randomFillSync(buf, 5, 5); console.log(buf.toString('hex'));
Any ArrayBuffer, TypedArray or DataView instance may be passed as buffer.
import { Buffer } from 'node:buffer'; const { randomFillSync } = await import('node:crypto'); const a = new Uint32Array(10); console.log(Buffer.from(randomFillSync(a).buffer, a.byteOffset, a.byteLength).toString('hex')); const b = new DataView(new ArrayBuffer(10)); console.log(Buffer.from(randomFillSync(b).buffer, b.byteOffset, b.byteLength).toString('hex')); const c = new ArrayBuffer(10); console.log(Buffer.from(randomFillSync(c)).toString('hex'));const { randomFillSync } = require('node:crypto'); const { Buffer } = require('node:buffer'); const a = new Uint32Array(10); console.log(Buffer.from(randomFillSync(a).buffer, a.byteOffset, a.byteLength).toString('hex')); const b = new DataView(new ArrayBuffer(10)); console.log(Buffer.from(randomFillSync(b).buffer, b.byteOffset, b.byteLength).toString('hex')); const c = new ArrayBuffer(10); console.log(Buffer.from(randomFillSync(c)).toString('hex'));
crypto.randomInt([min, ]max[, callback])#
min<integer>Start of random range (inclusive). Default:0.max<integer>End of random range (exclusive).callback<Function>function(err, n) {}.
Return a random integer n such that min <= n < max. This implementation avoids modulo bias.
The range (max - min) must be less than 248. min and max must be safe integers.
If the callback function is not provided, the random integer is generated synchronously.
// Asynchronous const { randomInt, } = await import('node:crypto'); randomInt(3, (err, n) => { if (err) throw err; console.log(`Random number chosen from (0, 1, 2): ${n}`); });// Asynchronous const { randomInt, } = require('node:crypto'); randomInt(3, (err, n) => { if (err) throw err; console.log(`Random number chosen from (0, 1, 2): ${n}`); });
// Synchronous const { randomInt, } = await import('node:crypto'); const n = randomInt(3); console.log(`Random number chosen from (0, 1, 2): ${n}`);// Synchronous const { randomInt, } = require('node:crypto'); const n = randomInt(3); console.log(`Random number chosen from (0, 1, 2): ${n}`);
// With `min` argument const { randomInt, } = await import('node:crypto'); const n = randomInt(1, 7); console.log(`The dice rolled: ${n}`);// With `min` argument const { randomInt, } = require('node:crypto'); const n = randomInt(1, 7); console.log(`The dice rolled: ${n}`);
crypto.randomUUID([options])#
options<Object>disableEntropyCache<boolean>By default, to improve performance, Node.js generates and caches enough random data to generate up to 128 random UUIDs. To generate a UUID without using the cache, setdisableEntropyCachetotrue. Default:false.
- Returns:
<string>
Generates a random RFC 4122 version 4 UUID. The UUID is generated using a cryptographic pseudorandom number generator.
crypto.scrypt(password, salt, keylen[, options], callback)#
password<string>|<ArrayBuffer>|<Buffer>|<TypedArray>|<DataView>salt<string>|<ArrayBuffer>|<Buffer>|<TypedArray>|<DataView>keylen<number>options<Object>cost<number>CPU/memory cost parameter. Must be a power of two greater than one. Default:16384.blockSize<number>Block size parameter. Default:8.parallelization<number>Parallelization parameter. Default:1.N<number>Alias forcost. Only one of both may be specified.r<number>Alias forblockSize. Only one of both may be specified.p<number>Alias forparallelization. Only one of both may be specified.maxmem<number>Memory upper bound. It is an error when (approximately)128 * N * r > maxmem. Default:32 * 1024 * 1024.
callback<Function>
Provides an asynchronous scrypt implementation. Scrypt is a password-based key derivation function that is designed to be expensive computationally and memory-wise in order to make brute-force attacks unrewarding.
The salt should be as unique as possible. It is recommended that a salt is random and at least 16 bytes long. See NIST SP 800-132 for details.
When passing strings for password or salt, please consider caveats when using strings as inputs to cryptographic APIs.
The callback function is called with two arguments: err and derivedKey. err is an exception object when key derivation fails, otherwise err is null. derivedKey is passed to the callback as a Buffer.
An exception is thrown when any of the input arguments specify invalid values or types.
const { scrypt, } = await import('node:crypto'); // Using the factory defaults. scrypt('password', 'salt', 64, (err, derivedKey) => { if (err) throw err; console.log(derivedKey.toString('hex')); // '3745e48...08d59ae' }); // Using a custom N parameter. Must be a power of two. scrypt('password', 'salt', 64, { N: 1024 }, (err, derivedKey) => { if (err) throw err; console.log(derivedKey.toString('hex')); // '3745e48...aa39b34' });const { scrypt, } = require('node:crypto'); // Using the factory defaults. scrypt('password', 'salt', 64, (err, derivedKey) => { if (err) throw err; console.log(derivedKey.toString('hex')); // '3745e48...08d59ae' }); // Using a custom N parameter. Must be a power of two. scrypt('password', 'salt', 64, { N: 1024 }, (err, derivedKey) => { if (err) throw err; console.log(derivedKey.toString('hex')); // '3745e48...aa39b34' });
crypto.scryptSync(password, salt, keylen[, options])#
password<string>|<Buffer>|<TypedArray>|<DataView>salt<string>|<Buffer>|<TypedArray>|<DataView>keylen<number>options<Object>cost<number>CPU/memory cost parameter. Must be a power of two greater than one. Default:16384.blockSize<number>Block size parameter. Default:8.parallelization<number>Parallelization parameter. Default:1.N<number>Alias forcost. Only one of both may be specified.r<number>Alias forblockSize. Only one of both may be specified.p<number>Alias forparallelization. Only one of both may be specified.maxmem<number>Memory upper bound. It is an error when (approximately)128 * N * r > maxmem. Default:32 * 1024 * 1024.
- Returns:
<Buffer>
Provides a synchronous scrypt implementation. Scrypt is a password-based key derivation function that is designed to be expensive computationally and memory-wise in order to make brute-force attacks unrewarding.
The salt should be as unique as possible. It is recommended that a salt is random and at least 16 bytes long. See NIST SP 800-132 for details.
When passing strings for password or salt, please consider caveats when using strings as inputs to cryptographic APIs.
An exception is thrown when key derivation fails, otherwise the derived key is returned as a Buffer.
An exception is thrown when any of the input arguments specify invalid values or types.
const { scryptSync, } = await import('node:crypto'); // Using the factory defaults. const key1 = scryptSync('password', 'salt', 64); console.log(key1.toString('hex')); // '3745e48...08d59ae' // Using a custom N parameter. Must be a power of two. const key2 = scryptSync('password', 'salt', 64, { N: 1024 }); console.log(key2.toString('hex')); // '3745e48...aa39b34'const { scryptSync, } = require('node:crypto'); // Using the factory defaults. const key1 = scryptSync('password', 'salt', 64); console.log(key1.toString('hex')); // '3745e48...08d59ae' // Using a custom N parameter. Must be a power of two. const key2 = scryptSync('password', 'salt', 64, { N: 1024 }); console.log(key2.toString('hex')); // '3745e48...aa39b34'
crypto.secureHeapUsed()#
- Returns:
<Object>total<number>The total allocated secure heap size as specified using the--secure-heap=ncommand-line flag.min<number>The minimum allocation from the secure heap as specified using the--secure-heap-mincommand-line flag.used<number>The total number of bytes currently allocated from the secure heap.utilization<number>The calculated ratio ofusedtototalallocated bytes.
crypto.setEngine(engine[, flags])#
engine<string>flags<crypto.constants>Default:crypto.constants.ENGINE_METHOD_ALL
Load and set the engine for some or all OpenSSL functions (selected by flags). Support for custom engines in OpenSSL is deprecated from OpenSSL 3.
engine could be either an id or a path to the engine's shared library.
The optional flags argument uses ENGINE_METHOD_ALL by default. The flags is a bit field taking one of or a mix of the following flags (defined in crypto.constants):
crypto.constants.ENGINE_METHOD_RSAcrypto.constants.ENGINE_METHOD_DSAcrypto.constants.ENGINE_METHOD_DHcrypto.constants.ENGINE_METHOD_RANDcrypto.constants.ENGINE_METHOD_ECcrypto.constants.ENGINE_METHOD_CIPHERScrypto.constants.ENGINE_METHOD_DIGESTScrypto.constants.ENGINE_METHOD_PKEY_METHScrypto.constants.ENGINE_METHOD_PKEY_ASN1_METHScrypto.constants.ENGINE_METHOD_ALLcrypto.constants.ENGINE_METHOD_NONE
crypto.setFips(bool)#
bool<boolean>trueto enable FIPS mode.
Enables the FIPS compliant crypto provider in a FIPS-enabled Node.js build. Throws an error if FIPS mode is not available.
crypto.sign(algorithm, data, key[, callback])#
algorithm<string>|<null>|<undefined>data<ArrayBuffer>|<Buffer>|<TypedArray>|<DataView>key<Object>|<string>|<ArrayBuffer>|<Buffer>|<TypedArray>|<DataView>|<KeyObject>|<CryptoKey>callback<Function>- Returns:
<Buffer>if thecallbackfunction is not provided.
Calculates and returns the signature for data using the given private key and algorithm. If algorithm is null or undefined, then the algorithm is dependent upon the key type.
algorithm is required to be null or undefined for Ed25519, Ed448, and ML-DSA.
If key is not a KeyObject, this function behaves as if key had been passed to crypto.createPrivateKey(). If it is an object, the following additional properties can be passed:
dsaEncoding<string>For DSA and ECDSA, this option specifies the format of the generated signature. It can be one of the following:'der'(default): DER-encoded ASN.1 signature structure encoding(r, s).'ieee-p1363': Signature formatr || sas proposed in IEEE-P1363.
padding<integer>Optional padding value for RSA, one of the following:crypto.constants.RSA_PKCS1_PADDING(default)crypto.constants.RSA_PKCS1_PSS_PADDING
RSA_PKCS1_PSS_PADDINGwill use MGF1 with the same hash function used to sign the message as specified in section 3.1 of RFC 4055.saltLength<integer>Salt length for when padding isRSA_PKCS1_PSS_PADDING. The special valuecrypto.constants.RSA_PSS_SALTLEN_DIGESTsets the salt length to the digest size,crypto.constants.RSA_PSS_SALTLEN_MAX_SIGN(default) sets it to the maximum permissible value.context<ArrayBuffer>|<Buffer>|<TypedArray>|<DataView>For Ed448, ML-DSA, and SLH-DSA, this option specifies the optional context to differentiate signatures generated for different purposes with the same key.
If the callback function is provided this function uses libuv's threadpool.
crypto.subtle#
- Type:
<SubtleCrypto>
A convenient alias for crypto.webcrypto.subtle.
crypto.timingSafeEqual(a, b)#
a<ArrayBuffer>|<Buffer>|<TypedArray>|<DataView>b<ArrayBuffer>|<Buffer>|<TypedArray>|<DataView>- Returns:
<boolean>
This function compares the underlying bytes that represent the given ArrayBuffer, TypedArray, or DataView instances using a constant-time algorithm.
This function does not leak timing information that would allow an attacker to guess one of the values. This is suitable for comparing HMAC digests or secret values like authentication cookies or capability urls.
a and b must both be Buffers, TypedArrays, or DataViews, and they must have the same byte length. An error is thrown if a and b have different byte lengths.
If at least one of a and b is a TypedArray with more than one byte per entry, such as Uint16Array, the result will be computed using the platform byte order.
When both of the inputs are Float32Arrays or Float64Arrays, this function might return unexpected results due to IEEE 754 encoding of floating-point numbers. In particular, neither x === y nor Object.is(x, y) implies that the byte representations of two floating-point numbers x and y are equal.
Use of crypto.timingSafeEqual does not guarantee that the surrounding code is timing-safe. Care should be taken to ensure that the surrounding code does not introduce timing vulnerabilities.
crypto.verify(algorithm, data, key, signature[, callback])#
algorithm<string>|<null>|<undefined>data<ArrayBuffer>|<Buffer>|<TypedArray>|<DataView>key<Object>|<string>|<ArrayBuffer>|<Buffer>|<TypedArray>|<DataView>|<KeyObject>|<CryptoKey>signature<ArrayBuffer>|<Buffer>|<TypedArray>|<DataView>callback<Function>- Returns:
<boolean>trueorfalsedepending on the validity of the signature for the data and public key if thecallbackfunction is not provided.
Verifies the given signature for data using the given key and algorithm. If algorithm is null or undefined, then the algorithm is dependent upon the key type.
algorithm is required to be null or undefined for Ed25519, Ed448, and ML-DSA.
If key is not a KeyObject, this function behaves as if key had been passed to crypto.createPublicKey(). If it is an object, the following additional properties can be passed:
dsaEncoding<string>For DSA and ECDSA, this option specifies the format of the signature. It can be one of the following:'der'(default): DER-encoded ASN.1 signature structure encoding(r, s).'ieee-p1363': Signature formatr || sas proposed in IEEE-P1363.
padding<integer>Optional padding value for RSA, one of the following:crypto.constants.RSA_PKCS1_PADDING(default)crypto.constants.RSA_PKCS1_PSS_PADDING
RSA_PKCS1_PSS_PADDINGwill use MGF1 with the same hash function used to sign the message as specified in section 3.1 of RFC 4055.saltLength<integer>Salt length for when padding isRSA_PKCS1_PSS_PADDING. The special valuecrypto.constants.RSA_PSS_SALTLEN_DIGESTsets the salt length to the digest size,crypto.constants.RSA_PSS_SALTLEN_MAX_SIGN(default) sets it to the maximum permissible value.context<ArrayBuffer>|<Buffer>|<TypedArray>|<DataView>For Ed448, ML-DSA, and SLH-DSA, this option specifies the optional context to differentiate signatures generated for different purposes with the same key.
The signature argument is the previously calculated signature for the data.
Because public keys can be derived from private keys, a private key or a public key may be passed for key.
If the callback function is provided this function uses libuv's threadpool.
crypto.webcrypto#
Type: <Crypto> An implementation of the Web Crypto API standard.
See the Web Crypto API documentation for details.
Notes#
Using strings as inputs to cryptographic APIs#
For historical reasons, many cryptographic APIs provided by Node.js accept strings as inputs where the underlying cryptographic algorithm works on byte sequences. These instances include plaintexts, ciphertexts, symmetric keys, initialization vectors, passphrases, salts, authentication tags, and additional authenticated data.
When passing strings to cryptographic APIs, consider the following factors.
Not all byte sequences are valid UTF-8 strings. Therefore, when a byte sequence of length
nis derived from a string, its entropy is generally lower than the entropy of a random or pseudorandomnbyte sequence. For example, no UTF-8 string will result in the byte sequencec0 af. Secret keys should almost exclusively be random or pseudorandom byte sequences.Similarly, when converting random or pseudorandom byte sequences to UTF-8 strings, subsequences that do not represent valid code points may be replaced by the Unicode replacement character (
U+FFFD). The byte representation of the resulting Unicode string may, therefore, not be equal to the byte sequence that the string was created from.const original = [0xc0, 0xaf]; const bytesAsString = Buffer.from(original).toString('utf8'); const stringAsBytes = Buffer.from(bytesAsString, 'utf8'); console.log(stringAsBytes); // Prints '<Buffer ef bf bd ef bf bd>'.The outputs of ciphers, hash functions, signature algorithms, and key derivation functions are pseudorandom byte sequences and should not be used as Unicode strings.
When strings are obtained from user input, some Unicode characters can be represented in multiple equivalent ways that result in different byte sequences. For example, when passing a user passphrase to a key derivation function, such as PBKDF2 or scrypt, the result of the key derivation function depends on whether the string uses composed or decomposed characters. Node.js does not normalize character representations. Developers should consider using
String.prototype.normalize()on user inputs before passing them to cryptographic APIs.
Legacy streams API (prior to Node.js 0.10)#
The Crypto module was added to Node.js before there was the concept of a unified Stream API, and before there were Buffer objects for handling binary data. As such, many crypto classes have methods not typically found on other Node.js classes that implement the streams API (e.g. update(), final(), or digest()). Also, many methods accepted and returned 'latin1' encoded strings by default rather than Buffers. This default was changed in Node.js 0.9.3 to use Buffer objects by default instead.
Support for weak or compromised algorithms#
The node:crypto module still supports some algorithms which are already compromised and are not recommended for use. The API also allows the use of ciphers and hashes with a small key size that are too weak for safe use.
Users should take full responsibility for selecting the crypto algorithm and key size according to their security requirements.
Based on the recommendations of NIST SP 800-131A:
- MD5 and SHA-1 are no longer acceptable where collision resistance is required such as digital signatures.
- The key used with RSA, DSA, and DH algorithms is recommended to have at least 2048 bits and that of the curve of ECDSA and ECDH at least 224 bits, to be safe to use for several years.
- The DH groups of
modp1,modp2andmodp5have a key size smaller than 2048 bits and are not recommended.
See the reference for other recommendations and details.
Some algorithms that have known weaknesses and are of little relevance in practice are only available through the legacy provider, which is not enabled by default.
CCM mode#
CCM is one of the supported AEAD algorithms. Applications which use this mode must adhere to certain restrictions when using the cipher API:
- The authentication tag length must be specified during cipher creation by setting the
authTagLengthoption and must be one of 4, 6, 8, 10, 12, 14 or 16 bytes. - The length of the initialization vector (nonce)
Nmust be between 7 and 13 bytes (7 ≤ N ≤ 13). - The length of the plaintext is limited to
2 ** (8 * (15 - N))bytes. - When decrypting, the authentication tag must be set via
setAuthTag()before callingupdate(). Otherwise, decryption will fail andfinal()will throw an error in compliance with section 2.6 of RFC 3610. - Using stream methods such as
write(data),end(data)orpipe()in CCM mode might fail as CCM cannot handle more than one chunk of data per instance. - When passing additional authenticated data (AAD), the length of the actual message in bytes must be passed to
setAAD()via theplaintextLengthoption. Many crypto libraries include the authentication tag in the ciphertext, which means that they produce ciphertexts of the lengthplaintextLength + authTagLength. Node.js does not include the authentication tag, so the ciphertext length is alwaysplaintextLength. This is not necessary if no AAD is used. - As CCM processes the whole message at once,
update()must be called exactly once. - Even though calling
update()is sufficient to encrypt/decrypt the message, applications must callfinal()to compute or verify the authentication tag.
import { Buffer } from 'node:buffer'; const { createCipheriv, createDecipheriv, randomBytes, } = await import('node:crypto'); const key = 'keykeykeykeykeykeykeykey'; const nonce = randomBytes(12); const aad = Buffer.from('0123456789', 'hex'); const cipher = createCipheriv('aes-192-ccm', key, nonce, { authTagLength: 16, }); const plaintext = 'Hello world'; cipher.setAAD(aad, { plaintextLength: Buffer.byteLength(plaintext), }); const ciphertext = cipher.update(plaintext, 'utf8'); cipher.final(); const tag = cipher.getAuthTag(); // Now transmit { ciphertext, nonce, tag }. const decipher = createDecipheriv('aes-192-ccm', key, nonce, { authTagLength: 16, }); decipher.setAuthTag(tag); decipher.setAAD(aad, { plaintextLength: ciphertext.length, }); const receivedPlaintext = decipher.update(ciphertext, null, 'utf8'); try { decipher.final(); } catch (err) { throw new Error('Authentication failed!', { cause: err }); } console.log(receivedPlaintext);const { Buffer } = require('node:buffer'); const { createCipheriv, createDecipheriv, randomBytes, } = require('node:crypto'); const key = 'keykeykeykeykeykeykeykey'; const nonce = randomBytes(12); const aad = Buffer.from('0123456789', 'hex'); const cipher = createCipheriv('aes-192-ccm', key, nonce, { authTagLength: 16, }); const plaintext = 'Hello world'; cipher.setAAD(aad, { plaintextLength: Buffer.byteLength(plaintext), }); const ciphertext = cipher.update(plaintext, 'utf8'); cipher.final(); const tag = cipher.getAuthTag(); // Now transmit { ciphertext, nonce, tag }. const decipher = createDecipheriv('aes-192-ccm', key, nonce, { authTagLength: 16, }); decipher.setAuthTag(tag); decipher.setAAD(aad, { plaintextLength: ciphertext.length, }); const receivedPlaintext = decipher.update(ciphertext, null, 'utf8'); try { decipher.final(); } catch (err) { throw new Error('Authentication failed!', { cause: err }); } console.log(receivedPlaintext);
FIPS mode#
When using OpenSSL 3, Node.js supports FIPS 140-2 when used with an appropriate OpenSSL 3 provider, such as the FIPS provider from OpenSSL 3 which can be installed by following the instructions in OpenSSL's FIPS README file.
For FIPS support in Node.js you will need:
- A correctly installed OpenSSL 3 FIPS provider.
- An OpenSSL 3 FIPS module configuration file.
- An OpenSSL 3 configuration file that references the FIPS module configuration file.
Node.js will need to be configured with an OpenSSL configuration file that points to the FIPS provider. An example configuration file looks like this:
nodejs_conf = nodejs_init
.include /<absolute path>/fipsmodule.cnf
[nodejs_init]
providers = provider_sect
[provider_sect]
default = default_sect
# The fips section name should match the section name inside the
# included fipsmodule.cnf.
fips = fips_sect
[default_sect]
activate = 1
where fipsmodule.cnf is the FIPS module configuration file generated from the FIPS provider installation step:
openssl fipsinstall
Set the OPENSSL_CONF environment variable to point to your configuration file and OPENSSL_MODULES to the location of the FIPS provider dynamic library. e.g.
export OPENSSL_CONF=/<path to configuration file>/nodejs.cnf
export OPENSSL_MODULES=/<path to openssl lib>/ossl-modules
FIPS mode can then be enabled in Node.js either by:
- Starting Node.js with
--enable-fipsor--force-fipscommand line flags. - Programmatically calling
crypto.setFips(true).
Optionally FIPS mode can be enabled in Node.js via the OpenSSL configuration file. e.g.
nodejs_conf = nodejs_init
.include /<absolute path>/fipsmodule.cnf
[nodejs_init]
providers = provider_sect
alg_section = algorithm_sect
[provider_sect]
default = default_sect
# The fips section name should match the section name inside the
# included fipsmodule.cnf.
fips = fips_sect
[default_sect]
activate = 1
[algorithm_sect]
default_properties = fips=yes
Crypto constants#
The following constants exported by crypto.constants apply to various uses of the node:crypto, node:tls, and node:https modules and are generally specific to OpenSSL.
OpenSSL options#
See the list of SSL OP Flags for details.
| Constant | Description |
|---|---|
SSL_OP_ALL | Applies multiple bug workarounds within OpenSSL. See https://www.openssl.org/docs/man3.0/man3/SSL_CTX_set_options.html for detail. |
SSL_OP_ALLOW_NO_DHE_KEX | Instructs OpenSSL to allow a non-[EC]DHE-based key exchange mode for TLS v1.3 |
SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION | Allows legacy insecure renegotiation between OpenSSL and unpatched clients or servers. See https://www.openssl.org/docs/man3.0/man3/SSL_CTX_set_options.html. |
SSL_OP_CIPHER_SERVER_PREFERENCE | Attempts to use the server's preferences instead of the client's when selecting a cipher. Behavior depends on protocol version. See https://www.openssl.org/docs/man3.0/man3/SSL_CTX_set_options.html. |
SSL_OP_CISCO_ANYCONNECT | Instructs OpenSSL to use Cisco's version identifier of DTLS_BAD_VER. |
SSL_OP_COOKIE_EXCHANGE | Instructs OpenSSL to turn on cookie exchange. |
SSL_OP_CRYPTOPRO_TLSEXT_BUG | Instructs OpenSSL to add server-hello extension from an early version of the cryptopro draft. |
SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS | Instructs OpenSSL to disable a SSL 3.0/TLS 1.0 vulnerability workaround added in OpenSSL 0.9.6d. |
SSL_OP_LEGACY_SERVER_CONNECT | Allows initial connection to servers that do not support RI. |
SSL_OP_NO_COMPRESSION | Instructs OpenSSL to disable support for SSL/TLS compression. |
SSL_OP_NO_ENCRYPT_THEN_MAC | Instructs OpenSSL to disable encrypt-then-MAC. |
SSL_OP_NO_QUERY_MTU | |
SSL_OP_NO_RENEGOTIATION | Instructs OpenSSL to disable renegotiation. |
SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION | Instructs OpenSSL to always start a new session when performing renegotiation. |
SSL_OP_NO_SSLv2 | Instructs OpenSSL to turn off SSL v2 |
SSL_OP_NO_SSLv3 | Instructs OpenSSL to turn off SSL v3 |
SSL_OP_NO_TICKET | Instructs OpenSSL to disable use of RFC4507bis tickets. |
SSL_OP_NO_TLSv1 | Instructs OpenSSL to turn off TLS v1 |
SSL_OP_NO_TLSv1_1 | Instructs OpenSSL to turn off TLS v1.1 |
SSL_OP_NO_TLSv1_2 | Instructs OpenSSL to turn off TLS v1.2 |
SSL_OP_NO_TLSv1_3 | Instructs OpenSSL to turn off TLS v1.3 |
SSL_OP_PRIORITIZE_CHACHA | Instructs OpenSSL server to prioritize ChaCha20-Poly1305 when the client does. This option has no effect if SSL_OP_CIPHER_SERVER_PREFERENCE is not enabled. |
SSL_OP_TLS_ROLLBACK_BUG | Instructs OpenSSL to disable version rollback attack detection. |
OpenSSL engine constants#
| Constant | Description |
|---|---|
ENGINE_METHOD_RSA | Limit engine usage to RSA |
ENGINE_METHOD_DSA | Limit engine usage to DSA |
ENGINE_METHOD_DH | Limit engine usage to DH |
ENGINE_METHOD_RAND | Limit engine usage to RAND |
ENGINE_METHOD_EC | Limit engine usage to EC |
ENGINE_METHOD_CIPHERS | Limit engine usage to CIPHERS |
ENGINE_METHOD_DIGESTS | Limit engine usage to DIGESTS |
ENGINE_METHOD_PKEY_METHS | Limit engine usage to PKEY_METHS |
ENGINE_METHOD_PKEY_ASN1_METHS | Limit engine usage to PKEY_ASN1_METHS |
ENGINE_METHOD_ALL | |
ENGINE_METHOD_NONE |
Other OpenSSL constants#
| Constant | Description |
|---|---|
DH_CHECK_P_NOT_SAFE_PRIME | |
DH_CHECK_P_NOT_PRIME | |
DH_UNABLE_TO_CHECK_GENERATOR | |
DH_NOT_SUITABLE_GENERATOR | |
RSA_PKCS1_PADDING | |
RSA_SSLV23_PADDING | |
RSA_NO_PADDING | |
RSA_PKCS1_OAEP_PADDING | |
RSA_X931_PADDING | |
RSA_PKCS1_PSS_PADDING | |
RSA_PSS_SALTLEN_DIGEST | Sets the salt length for RSA_PKCS1_PSS_PADDING to the digest size when signing or verifying. |
RSA_PSS_SALTLEN_MAX_SIGN | Sets the salt length for RSA_PKCS1_PSS_PADDING to the maximum permissible value when signing data. |
RSA_PSS_SALTLEN_AUTO | Causes the salt length for RSA_PKCS1_PSS_PADDING to be determined automatically when verifying a signature. |
POINT_CONVERSION_COMPRESSED | |
POINT_CONVERSION_UNCOMPRESSED | |
POINT_CONVERSION_HYBRID |
Node.js crypto constants#
| Constant | Description |
|---|---|
defaultCoreCipherList | Specifies the built-in default cipher list used by Node.js. |
defaultCipherList | Specifies the active default cipher list used by the current Node.js process. |
Footnotes
Debugger#
Stability: 2 - Stable
Node.js includes a command-line debugging utility. The Node.js debugger client is not a full-featured debugger, but simple stepping and inspection are possible.
To use it, start Node.js with the inspect argument followed by the path to the script to debug.
$ node inspect myscript.js
< Debugger listening on ws://127.0.0.1:9229/621111f9-ffcb-4e82-b718-48a145fa5db8
< For help, see: https://nodejs.org/en/docs/inspector
<
connecting to 127.0.0.1:9229 ... ok
< Debugger attached.
<
ok
Break on start in myscript.js:2
1 // myscript.js
> 2 global.x = 5;
3 setTimeout(() => {
4 debugger;
debug>
The debugger automatically breaks on the first executable line. To instead run until the first breakpoint (specified by a debugger statement), set the NODE_INSPECT_RESUME_ON_START environment variable to 1.
$ cat myscript.js
// myscript.js
global.x = 5;
setTimeout(() => {
debugger;
console.log('world');
}, 1000);
console.log('hello');
$ NODE_INSPECT_RESUME_ON_START=1 node inspect myscript.js
< Debugger listening on ws://127.0.0.1:9229/f1ed133e-7876-495b-83ae-c32c6fc319c2
< For help, see: https://nodejs.org/en/docs/inspector
<
connecting to 127.0.0.1:9229 ... ok
< Debugger attached.
<
< hello
<
break in myscript.js:4
2 global.x = 5;
3 setTimeout(() => {
> 4 debugger;
5 console.log('world');
6 }, 1000);
debug> next
break in myscript.js:5
3 setTimeout(() => {
4 debugger;
> 5 console.log('world');
6 }, 1000);
7 console.log('hello');
debug> repl
Press Ctrl+C to leave debug repl
> x
5
> 2 + 2
4
debug> next
< world
<
break in myscript.js:6
4 debugger;
5 console.log('world');
> 6 }, 1000);
7 console.log('hello');
8
debug> .exit
$
The repl command allows code to be evaluated remotely. The next command steps to the next line. Type help to see what other commands are available.
Pressing enter without typing a command will repeat the previous debugger command.
Watchers#
It is possible to watch expression and variable values while debugging. On every breakpoint, each expression from the watchers list will be evaluated in the current context and displayed immediately before the breakpoint's source code listing.
To begin watching an expression, type watch('my_expression'). The command watchers will print the active watchers. To remove a watcher, type unwatch('my_expression').
Command reference#
Stepping#
cont,c: Continue executionnext,n: Step nextstep,s: Step inout,o: Step outpause: Pause running code (like pause button in Developer Tools)
Breakpoints#
setBreakpoint(),sb(): Set breakpoint on current linesetBreakpoint(line),sb(line): Set breakpoint on specific linesetBreakpoint('fn()'),sb(...): Set breakpoint on a first statement in function's bodysetBreakpoint('script.js', 1),sb(...): Set breakpoint on first line ofscript.jssetBreakpoint('script.js', 1, 'num < 4'),sb(...): Set conditional breakpoint on first line ofscript.jsthat only breaks whennum < 4evaluates totrueclearBreakpoint('script.js', 1),cb(...): Clear breakpoint inscript.json line 1
It is also possible to set a breakpoint in a file (module) that is not loaded yet:
$ node inspect main.js
< Debugger listening on ws://127.0.0.1:9229/48a5b28a-550c-471b-b5e1-d13dd7165df9
< For help, see: https://nodejs.org/en/docs/inspector
<
connecting to 127.0.0.1:9229 ... ok
< Debugger attached.
<
Break on start in main.js:1
> 1 const mod = require('./mod.js');
2 mod.hello();
3 mod.hello();
debug> setBreakpoint('mod.js', 22)
Warning: script 'mod.js' was not loaded yet.
debug> c
break in mod.js:22
20 // USE OR OTHER DEALINGS IN THE SOFTWARE.
21
>22 exports.hello = function() {
23 return 'hello from module';
24 };
debug>
It is also possible to set a conditional breakpoint that only breaks when a given expression evaluates to true:
$ node inspect main.js
< Debugger listening on ws://127.0.0.1:9229/ce24daa8-3816-44d4-b8ab-8273c8a66d35
< For help, see: https://nodejs.org/en/docs/inspector
<
connecting to 127.0.0.1:9229 ... ok
< Debugger attached.
Break on start in main.js:7
5 }
6
> 7 addOne(10);
8 addOne(-1);
9
debug> setBreakpoint('main.js', 4, 'num < 0')
1 'use strict';
2
3 function addOne(num) {
> 4 return num + 1;
5 }
6
7 addOne(10);
8 addOne(-1);
9
debug> cont
break in main.js:4
2
3 function addOne(num) {
> 4 return num + 1;
5 }
6
debug> exec('num')
-1
debug>
Information#
backtrace,bt: Print backtrace of current execution framelist(5): List scripts source code with 5 line context (5 lines before and after)watch(expr): Add expression to watch listunwatch(expr): Remove expression from watch listunwatch(index): Remove expression at specific index from watch listwatchers: List all watchers and their values (automatically listed on each breakpoint)repl: Open debugger's repl for evaluation in debugging script's contextexec expr,p expr: Execute an expression in debugging script's context and print its valueprofile: Start CPU profiling sessionprofileEnd: Stop current CPU profiling sessionprofiles: List all completed CPU profiling sessionsprofiles[n].save(filepath = 'node.cpuprofile'): Save CPU profiling session to disk as JSONtakeHeapSnapshot(filepath = 'node.heapsnapshot'): Take a heap snapshot and save to disk as JSON
Execution control#
run: Run script (automatically runs on debugger's start)restart: Restart scriptkill: Kill script
Various#
scripts: List all loaded scriptsversion: Display V8's version
Advanced usage#
V8 inspector integration for Node.js#
V8 Inspector integration allows attaching Chrome DevTools to Node.js instances for debugging and profiling. It uses the Chrome DevTools Protocol.
V8 Inspector can be enabled by passing the --inspect flag when starting a Node.js application. It is also possible to supply a custom port with that flag, e.g. --inspect=9222 will accept DevTools connections on port 9222.
Using the --inspect flag will execute the code immediately before debugger is connected. This means that the code will start running before you can start debugging, which might not be ideal if you want to debug from the very beginning.
In such cases, you have two alternatives:
--inspect-waitflag: This flag will wait for debugger to be attached before executing the code. This allows you to start debugging right from the beginning of the execution.--inspect-brkflag: Unlike--inspect, this flag will break on the first line of the code as soon as debugger is attached. This is useful when you want to debug the code step by step from the very beginning, without any code execution prior to debugging.
So, when deciding between --inspect, --inspect-wait, and --inspect-brk, consider whether you want the code to start executing immediately, wait for debugger to be attached before execution, or break on the first line for step-by-step debugging.
$ node --inspect index.js
Debugger listening on ws://127.0.0.1:9229/dc9010dd-f8b8-4ac5-a510-c1a114ec7d29
For help, see: https://nodejs.org/en/docs/inspector
(In the example above, the UUID dc9010dd-f8b8-4ac5-a510-c1a114ec7d29 at the end of the URL is generated on the fly, it varies in different debugging sessions.)
If the Chrome browser is older than 66.0.3345.0, use inspector.html instead of js_app.html in the above URL.
Chrome DevTools doesn't support debugging worker threads yet. ndb can be used to debug them.
Deprecated APIs#
Node.js APIs might be deprecated for any of the following reasons:
- Use of the API is unsafe.
- An improved alternative API is available.
- Breaking changes to the API are expected in a future major release.
Node.js uses four kinds of deprecations:
- Documentation-only
- Application (non-
node_modulescode only) - Runtime (all code)
- End-of-Life
A Documentation-only deprecation is one that is expressed only within the Node.js API docs. These generate no side-effects while running Node.js. Some Documentation-only deprecations trigger a runtime warning when launched with --pending-deprecation flag (or its alternative, NODE_PENDING_DEPRECATION=1 environment variable), similarly to Runtime deprecations below. Documentation-only deprecations that support that flag are explicitly labeled as such in the list of Deprecated APIs.
An Application deprecation for only non-node_modules code will, by default, generate a process warning that will be printed to stderr the first time the deprecated API is used in code that's not loaded from node_modules. When the --throw-deprecation command-line flag is used, a Runtime deprecation will cause an error to be thrown. When --pending-deprecation is used, warnings will also be emitted for code loaded from node_modules.
A runtime deprecation for all code is similar to the runtime deprecation for non-node_modules code, except that it also emits a warning for code loaded from node_modules.
An End-of-Life deprecation is used when functionality is or will soon be removed from Node.js.
Revoking deprecations#
Occasionally, the deprecation of an API might be reversed. In such situations, this document will be updated with information relevant to the decision. However, the deprecation identifier will not be modified.
List of deprecated APIs#
DEP0001: http.OutgoingMessage.prototype.flush#
Type: End-of-Life
OutgoingMessage.prototype.flush() has been removed. Use OutgoingMessage.prototype.flushHeaders() instead.
DEP0002: require('_linklist')#
Type: End-of-Life
The _linklist module is deprecated. Please use a userland alternative.
DEP0003: _writableState.buffer#
Type: End-of-Life
The _writableState.buffer has been removed. Use _writableState.getBuffer() instead.
DEP0004: CryptoStream.prototype.readyState#
Type: End-of-Life
The CryptoStream.prototype.readyState property was removed.
DEP0005: Buffer() constructor#
Type: Application (non-node_modules code only)
The Buffer() function and new Buffer() constructor are deprecated due to API usability issues that can lead to accidental security issues.
As an alternative, use one of the following methods of constructing Buffer objects:
Buffer.alloc(size[, fill[, encoding]]): Create aBufferwith initialized memory.Buffer.allocUnsafe(size): Create aBufferwith uninitialized memory.Buffer.allocUnsafeSlow(size): Create aBufferwith uninitialized memory.Buffer.from(array): Create aBufferwith a copy ofarrayBuffer.from(arrayBuffer[, byteOffset[, length]])- Create aBufferthat wraps the givenarrayBuffer.Buffer.from(buffer): Create aBufferthat copiesbuffer.Buffer.from(string[, encoding]): Create aBufferthat copiesstring.
Without --pending-deprecation, runtime warnings occur only for code not in node_modules. This means there will not be deprecation warnings for Buffer() usage in dependencies. With --pending-deprecation, a runtime warning results no matter where the Buffer() usage occurs.
DEP0006: child_process options.customFds#
Type: End-of-Life
Within the child_process module's spawn(), fork(), and exec() methods, the options.customFds option is deprecated. The options.stdio option should be used instead.
DEP0007: Replace cluster worker.suicide with worker.exitedAfterDisconnect#
Type: End-of-Life
In an earlier version of the Node.js cluster, a boolean property with the name suicide was added to the Worker object. The intent of this property was to provide an indication of how and why the Worker instance exited. In Node.js 6.0.0, the old property was deprecated and replaced with a new worker.exitedAfterDisconnect property. The old property name did not precisely describe the actual semantics and was unnecessarily emotion-laden.
DEP0008: require('node:constants')#
Type: Documentation-only
The node:constants module is deprecated. When requiring access to constants relevant to specific Node.js builtin modules, developers should instead refer to the constants property exposed by the relevant module. For instance, require('node:fs').constants and require('node:os').constants.
DEP0009: crypto.pbkdf2 without digest#
Type: End-of-Life
Use of the crypto.pbkdf2() API without specifying a digest was deprecated in Node.js 6.0 because the method defaulted to using the non-recommended 'SHA1' digest. Previously, a deprecation warning was printed. Starting in Node.js 8.0.0, calling crypto.pbkdf2() or crypto.pbkdf2Sync() with digest set to undefined will throw a TypeError.
Beginning in Node.js 11.0.0, calling these functions with digest set to null would print a deprecation warning to align with the behavior when digest is undefined.
Now, however, passing either undefined or null will throw a TypeError.
DEP0010: crypto.createCredentials#
Type: End-of-Life
The crypto.createCredentials() API was removed. Please use tls.createSecureContext() instead.
DEP0011: crypto.Credentials#
Type: End-of-Life
The crypto.Credentials class was removed. Please use tls.SecureContext instead.
DEP0012: Domain.dispose#
Type: End-of-Life
Domain.dispose() has been removed. Recover from failed I/O actions explicitly via error event handlers set on the domain instead.
DEP0013: fs asynchronous function without callback#
Type: End-of-Life
Calling an asynchronous function without a callback throws a TypeError in Node.js 10.0.0 onwards. See https://github.com/nodejs/node/pull/12562.
DEP0014: fs.read legacy String interface#
Type: End-of-Life
The fs.read() legacy String interface is deprecated. Use the Buffer API as mentioned in the documentation instead.
DEP0015: fs.readSync legacy String interface#
Type: End-of-Life
The fs.readSync() legacy String interface is deprecated. Use the Buffer API as mentioned in the documentation instead.
DEP0016: GLOBAL/root#
Type: End-of-Life
The GLOBAL and root aliases for the global property were deprecated in Node.js 6.0.0 and have since been removed.
DEP0017: Intl.v8BreakIterator#
Type: End-of-Life
Intl.v8BreakIterator was a non-standard extension and has been removed. See Intl.Segmenter.
DEP0018: Unhandled promise rejections#
Type: End-of-Life
Unhandled promise rejections are deprecated. By default, promise rejections that are not handled terminate the Node.js process with a non-zero exit code. To change the way Node.js treats unhandled rejections, use the --unhandled-rejections command-line option.
DEP0019: require('.') resolved outside directory#
Type: End-of-Life
In certain cases, require('.') could resolve outside the package directory. This behavior has been removed.
DEP0020: Server.connections#
Type: End-of-Life
The Server.connections property was deprecated in Node.js 0.9.7 and has been removed. Please use the Server.getConnections() method instead.
DEP0021: Server.listenFD#
Type: End-of-Life
The Server.listenFD() method was deprecated and removed. Please use Server.listen({fd: <number>}) instead.
DEP0022: os.tmpDir()#
Type: End-of-Life
The os.tmpDir() API was deprecated in Node.js 7.0.0 and has since been removed. Please use os.tmpdir() instead.
An automated migration is available (source):
npx codemod@latest @nodejs/tmpDir-to-tmpdir
DEP0023: os.getNetworkInterfaces()#
Type: End-of-Life
The os.getNetworkInterfaces() method is deprecated. Please use the os.networkInterfaces() method instead.
DEP0024: REPLServer.prototype.convertToContext()#
Type: End-of-Life
The REPLServer.prototype.convertToContext() API has been removed.
DEP0025: require('node:sys')#
Type: Runtime
The node:sys module is deprecated. Please use the util module instead.
DEP0026: util.print()#
Type: End-of-Life
util.print() has been removed. Please use console.log() instead.
An automated migration is available (source):
npx codemod@latest @nodejs/util-print-to-console-log
DEP0027: util.puts()#
Type: End-of-Life
util.puts() has been removed. Please use console.log() instead.
An automated migration is available (source):
npx codemod@latest @nodejs/util-print-to-console-log
DEP0028: util.debug()#
Type: End-of-Life
util.debug() has been removed. Please use console.error() instead.
An automated migration is available (source):
npx codemod@latest @nodejs/util-print-to-console-log
DEP0029: util.error()#
Type: End-of-Life
util.error() has been removed. Please use console.error() instead.
An automated migration is available (source):
npx codemod@latest @nodejs/util-print-to-console-log
DEP0030: SlowBuffer#
Type: End-of-Life
The SlowBuffer class has been removed. Please use Buffer.allocUnsafeSlow(size) instead.
An automated migration is available (source).
npx codemod@latest @nodejs/slow-buffer-to-buffer-alloc-unsafe-slow
DEP0031: ecdh.setPublicKey()#
Type: Runtime
The ecdh.setPublicKey() method is now deprecated as its inclusion in the API is not useful.
DEP0032: node:domain module#
Type: Documentation-only
The domain module is deprecated and should not be used.
DEP0033: EventEmitter.listenerCount()#
Type: Revoked
The events.listenerCount(emitter, eventName) API was deprecated, as it provided identical fuctionality to emitter.listenerCount(eventName). The deprecation was revoked because this function has been repurposed to also accept <EventTarget> arguments.
DEP0034: fs.exists(path, callback)#
Type: Documentation-only
The fs.exists(path, callback) API is deprecated. Please use fs.stat() or fs.access() instead.
DEP0035: fs.lchmod(path, mode, callback)#
Type: Documentation-only
The fs.lchmod(path, mode, callback) API is deprecated.
DEP0036: fs.lchmodSync(path, mode)#
Type: Documentation-only
The fs.lchmodSync(path, mode) API is deprecated.
DEP0037: fs.lchown(path, uid, gid, callback)#
Type: Deprecation revoked
The fs.lchown(path, uid, gid, callback) API was deprecated. The deprecation was revoked because the requisite supporting APIs were added in libuv.
DEP0038: fs.lchownSync(path, uid, gid)#
Type: Deprecation revoked
The fs.lchownSync(path, uid, gid) API was deprecated. The deprecation was revoked because the requisite supporting APIs were added in libuv.
DEP0039: require.extensions#
Type: Documentation-only
The require.extensions property is deprecated.
DEP0040: node:punycode module#
Type: Application (non-node_modules code only)
The punycode module is deprecated. Please use a userland alternative instead.
DEP0041: NODE_REPL_HISTORY_FILE environment variable#
Type: End-of-Life
The NODE_REPL_HISTORY_FILE environment variable was removed. Please use NODE_REPL_HISTORY instead.
DEP0042: tls.CryptoStream#
Type: End-of-Life
The tls.CryptoStream class was removed. Please use tls.TLSSocket instead.
DEP0043: tls.SecurePair#
Type: End-of-Life
The tls.SecurePair class is deprecated. Please use tls.TLSSocket instead.
DEP0044: util.isArray()#
Type: Runtime
The util.isArray() API is deprecated. Please use Array.isArray() instead.
An automated migration is available (source):
npx codemod@latest @nodejs/util-is
DEP0045: util.isBoolean()#
Type: End-of-Life
The util.isBoolean() API has been removed. Please use typeof arg === 'boolean' instead.
An automated migration is available (source):
npx codemod@latest @nodejs/util-is
DEP0046: util.isBuffer()#
Type: End-of-Life
The util.isBuffer() API has been removed. Please use Buffer.isBuffer() instead.
An automated migration is available (source):
npx codemod@latest @nodejs/util-is
DEP0047: util.isDate()#
Type: End-of-Life
The util.isDate() API has been removed. Please use arg instanceof Date instead.
Also for stronger approaches, consider using: Date.prototype.toString.call(arg) === '[object Date]' && !isNaN(arg). This can also be used in a try/catch block to handle invalid date objects.
An automated migration is available (source):
npx codemod@latest @nodejs/util-is
DEP0048: util.isError()#
Type: End-of-Life
The util.isError() API has been removed. Please use Error.isError(arg).
An automated migration is available (source):
npx codemod@latest @nodejs/util-is
DEP0049: util.isFunction()#
Type: End-of-Life
The util.isFunction() API has been removed. Please use typeof arg === 'function' instead.
An automated migration is available (source):
npx codemod@latest @nodejs/util-is
DEP0050: util.isNull()#
Type: End-of-Life
The util.isNull() API has been removed. Please use arg === null instead.
An automated migration is available (source):
npx codemod@latest @nodejs/util-is
DEP0051: util.isNullOrUndefined()#
Type: End-of-Life
The util.isNullOrUndefined() API has been removed. Please use arg === null || arg === undefined instead.
An automated migration is available (source):
npx codemod@latest @nodejs/util-is
DEP0052: util.isNumber()#
Type: End-of-Life
The util.isNumber() API has been removed. Please use typeof arg === 'number' instead.
An automated migration is available (source):
npx codemod@latest @nodejs/util-is
DEP0053: util.isObject()#
Type: End-of-Life
The util.isObject() API has been removed. Please use arg && typeof arg === 'object' instead.
An automated migration is available (source):
npx codemod@latest @nodejs/util-is
DEP0054: util.isPrimitive()#
Type: End-of-Life
The util.isPrimitive() API has been removed. Please use Object(arg) !== arg instead.
An automated migration is available (source):
npx codemod@latest @nodejs/util-is
DEP0055: util.isRegExp()#
Type: End-of-Life
The util.isRegExp() API has been removed. Please use arg instanceof RegExp instead.
An automated migration is available (source):
npx codemod@latest @nodejs/util-is
DEP0056: util.isString()#
Type: End-of-Life
The util.isString() API has been removed. Please use typeof arg === 'string' instead.
An automated migration is available (source):
npx codemod@latest @nodejs/util-is
DEP0057: util.isSymbol()#
Type: End-of-Life
The util.isSymbol() API has been removed. Please use typeof arg === 'symbol' instead.
An automated migration is available (source):
npx codemod@latest @nodejs/util-is
DEP0058: util.isUndefined()#
Type: End-of-Life
The util.isUndefined() API has been removed. Please use arg === undefined instead.
An automated migration is available (source):
npx codemod@latest @nodejs/util-is
DEP0059: util.log()#
Type: End-of-Life
The util.log() API has been removed because it's an unmaintained legacy API that was exposed to user land by accident. Instead, consider the following alternatives based on your specific needs:
Third-Party Logging Libraries
Use
console.log(new Date().toLocaleString(), message)
By adopting one of these alternatives, you can transition away from util.log() and choose a logging strategy that aligns with the specific requirements and complexity of your application.
An automated migration is available (source):
npx codemod@latest @nodejs/util-log-to-console-log
DEP0060: util._extend()#
Type: Runtime
The util._extend() API is deprecated because it's an unmaintained legacy API that was exposed to user land by accident. Please use target = Object.assign(target, source) instead.
An automated migration is available (source):
npx codemod@latest @nodejs/util-extend-to-object-assign
DEP0061: fs.SyncWriteStream#
Type: End-of-Life
The fs.SyncWriteStream class was never intended to be a publicly accessible API and has been removed. No alternative API is available. Please use a userland alternative.
DEP0062: node --debug#
Type: End-of-Life
--debug activates the legacy V8 debugger interface, which was removed as of V8 5.8. It is replaced by Inspector which is activated with --inspect instead.
DEP0063: ServerResponse.prototype.writeHeader()#
Type: End-of-Life
The node:http module ServerResponse.prototype.writeHeader() API is deprecated. Please use ServerResponse.prototype.writeHead() instead.
The ServerResponse.prototype.writeHeader() method was never documented as an officially supported API.
DEP0064: tls.createSecurePair()#
Type: End-of-Life
The tls.createSecurePair() API was deprecated in documentation in Node.js 0.11.3. Users should use tls.Socket instead.
DEP0065: repl.REPL_MODE_MAGIC and NODE_REPL_MODE=magic#
Type: End-of-Life
The node:repl module's REPL_MODE_MAGIC constant, used for replMode option, has been removed. Its behavior has been functionally identical to that of REPL_MODE_SLOPPY since Node.js 6.0.0, when V8 5.0 was imported. Please use REPL_MODE_SLOPPY instead.
The NODE_REPL_MODE environment variable is used to set the underlying replMode of an interactive node session. Its value, magic, is also removed. Please use sloppy instead.
DEP0066: OutgoingMessage.prototype._headers, OutgoingMessage.prototype._headerNames#
Type: End-of-Life
The node:http module OutgoingMessage.prototype._headers and OutgoingMessage.prototype._headerNames properties are deprecated. Use one of the public methods (e.g. OutgoingMessage.prototype.getHeader(), OutgoingMessage.prototype.getHeaders(), OutgoingMessage.prototype.getHeaderNames(), OutgoingMessage.prototype.getRawHeaderNames(), OutgoingMessage.prototype.hasHeader(), OutgoingMessage.prototype.removeHeader(), OutgoingMessage.prototype.setHeader()) for working with outgoing headers.
The OutgoingMessage.prototype._headers and OutgoingMessage.prototype._headerNames properties were never documented as officially supported properties.
An automated migration is available (source):
npx codemod@latest @nodejs/http-outgoingmessage-headers
DEP0067: OutgoingMessage.prototype._renderHeaders#
Type: Documentation-only
The node:http module OutgoingMessage.prototype._renderHeaders() API is deprecated.
The OutgoingMessage.prototype._renderHeaders property was never documented as an officially supported API.
DEP0068: node debug#
Type: End-of-Life
node debug corresponds to the legacy CLI debugger which has been replaced with a V8-inspector based CLI debugger available through node inspect.
DEP0069: vm.runInDebugContext(string)#
Type: End-of-Life
DebugContext has been removed in V8 and is not available in Node.js 10+.
DebugContext was an experimental API.
DEP0070: async_hooks.currentId()#
Type: End-of-Life
async_hooks.currentId() was renamed to async_hooks.executionAsyncId() for clarity.
This change was made while async_hooks was an experimental API.
DEP0071: async_hooks.triggerId()#
Type: End-of-Life
async_hooks.triggerId() was renamed to async_hooks.triggerAsyncId() for clarity.
This change was made while async_hooks was an experimental API.
DEP0072: async_hooks.AsyncResource.triggerId()#
Type: End-of-Life
async_hooks.AsyncResource.triggerId() was renamed to async_hooks.AsyncResource.triggerAsyncId() for clarity.
This change was made while async_hooks was an experimental API.
DEP0073: Several internal properties of net.Server#
Type: End-of-Life
Accessing several internal, undocumented properties of net.Server instances with inappropriate names is deprecated.
As the original API was undocumented and not generally useful for non-internal code, no replacement API is provided.
DEP0074: REPLServer.bufferedCommand#
Type: End-of-Life
The REPLServer.bufferedCommand property was deprecated in favor of REPLServer.clearBufferedCommand().
DEP0075: REPLServer.parseREPLKeyword()#
Type: End-of-Life
REPLServer.parseREPLKeyword() was removed from userland visibility.
DEP0076: tls.parseCertString()#
Type: End-of-Life
tls.parseCertString() was a trivial parsing helper that was made public by mistake. While it was supposed to parse certificate subject and issuer strings, it never handled multi-value Relative Distinguished Names correctly.
Earlier versions of this document suggested using querystring.parse() as an alternative to tls.parseCertString(). However, querystring.parse() also does not handle all certificate subjects correctly and should not be used.
DEP0077: Module._debug()#
Type: End-of-Life
Module._debug() has been removed.
The Module._debug() function was never documented as an officially supported API.
DEP0078: REPLServer.turnOffEditorMode()#
Type: End-of-Life
REPLServer.turnOffEditorMode() was removed from userland visibility.
DEP0079: Custom inspection function on objects via .inspect()#
Type: End-of-Life
Using a property named inspect on an object to specify a custom inspection function for util.inspect() is deprecated. Use util.inspect.custom instead. For backward compatibility with Node.js prior to version 6.4.0, both can be specified.
DEP0080: path._makeLong()#
Type: Documentation-only
The internal path._makeLong() was not intended for public use. However, userland modules have found it useful. The internal API is deprecated and replaced with an identical, public path.toNamespacedPath() method.
DEP0081: fs.truncate() using a file descriptor#
Type: End-of-Life
fs.truncate() fs.truncateSync() usage with a file descriptor is deprecated. Please use fs.ftruncate() or fs.ftruncateSync() to work with file descriptors.
An automated migration is available (source):
npx codemod@latest @nodejs/fs-truncate-fd-deprecation
DEP0082: REPLServer.prototype.memory()#
Type: End-of-Life
REPLServer.prototype.memory() is only necessary for the internal mechanics of the REPLServer itself. Do not use this function.
DEP0083: Disabling ECDH by setting ecdhCurve to false#
Type: End-of-Life
The ecdhCurve option to tls.createSecureContext() and tls.TLSSocket could be set to false to disable ECDH entirely on the server only. This mode was deprecated in preparation for migrating to OpenSSL 1.1.0 and consistency with the client and is now unsupported. Use the ciphers parameter instead.
DEP0084: requiring bundled internal dependencies#
Type: End-of-Life
Since Node.js versions 4.4.0 and 5.2.0, several modules only intended for internal usage were mistakenly exposed to user code through require(). These modules were:
v8/tools/codemapv8/tools/consarrayv8/tools/csvparserv8/tools/logreaderv8/tools/profile_viewv8/tools/profilev8/tools/SourceMapv8/tools/splaytreev8/tools/tickprocessor-driverv8/tools/tickprocessornode-inspect/lib/_inspect(from 7.6.0)node-inspect/lib/internal/inspect_client(from 7.6.0)node-inspect/lib/internal/inspect_repl(from 7.6.0)
The v8/* modules do not have any exports, and if not imported in a specific order would in fact throw errors. As such there are virtually no legitimate use cases for importing them through require().
On the other hand, node-inspect can be installed locally through a package manager, as it is published on the npm registry under the same name. No source code modification is necessary if that is done.
DEP0085: AsyncHooks sensitive API#
Type: End-of-Life
The AsyncHooks sensitive API was never documented and had various minor issues. Use the AsyncResource API instead. See https://github.com/nodejs/node/issues/15572.
DEP0086: Remove runInAsyncIdScope#
Type: End-of-Life
runInAsyncIdScope doesn't emit the 'before' or 'after' event and can thus cause a lot of issues. See https://github.com/nodejs/node/issues/14328.
DEP0089: require('node:assert')#
Type: Deprecation revoked
Importing assert directly was not recommended as the exposed functions use loose equality checks. The deprecation was revoked because use of the node:assert module is not discouraged, and the deprecation caused developer confusion.
DEP0090: Invalid GCM authentication tag lengths#
Type: End-of-Life
Node.js used to support all GCM authentication tag lengths which are accepted by OpenSSL when calling decipher.setAuthTag(). Beginning with Node.js v11.0.0, only authentication tag lengths of 128, 120, 112, 104, 96, 64, and 32 bits are allowed. Authentication tags of other lengths are invalid per NIST SP 800-38D.
DEP0091: crypto.DEFAULT_ENCODING#
Type: End-of-Life
The crypto.DEFAULT_ENCODING property only existed for compatibility with Node.js releases prior to versions 0.9.3 and has been removed.
DEP0092: Top-level this bound to module.exports#
Type: Documentation-only
Assigning properties to the top-level this as an alternative to module.exports is deprecated. Developers should use exports or module.exports instead.
DEP0093: crypto.fips is deprecated and replaced#
Type: Runtime
The crypto.fips property is deprecated. Please use crypto.setFips() and crypto.getFips() instead.
An automated migration is available (source).
npx codemod@latest @nodejs/crypto-fips-to-getFips
DEP0094: Using assert.fail() with more than one argument#
Type: End-of-Life
Using assert.fail() with more than one argument is deprecated. Use assert.fail() with only one argument or use a different node:assert module method.
DEP0095: timers.enroll()#
Type: End-of-Life
timers.enroll() has been removed. Please use the publicly documented setTimeout() or setInterval() instead.
DEP0096: timers.unenroll()#
Type: End-of-Life
timers.unenroll() has been removed. Please use the publicly documented clearTimeout() or clearInterval() instead.
DEP0097: MakeCallback with domain property#
Type: Runtime
Users of MakeCallback that add the domain property to carry context, should start using the async_context variant of MakeCallback or CallbackScope, or the high-level AsyncResource class.
DEP0098: AsyncHooks embedder AsyncResource.emitBefore and AsyncResource.emitAfter APIs#
Type: End-of-Life
The embedded API provided by AsyncHooks exposes .emitBefore() and .emitAfter() methods which are very easy to use incorrectly which can lead to unrecoverable errors.
Use asyncResource.runInAsyncScope() API instead which provides a much safer, and more convenient, alternative. See https://github.com/nodejs/node/pull/18513.
DEP0099: Async context-unaware node::MakeCallback C++ APIs#
Type: Compile-time
Certain versions of node::MakeCallback APIs available to native addons are deprecated. Please use the versions of the API that accept an async_context parameter.
DEP0100: process.assert()#
Type: End-of-Life
process.assert() is deprecated. Please use the assert module instead.
This was never a documented feature.
An automated migration is available (source).
npx codemod@latest @nodejs/process-assert-to-node-assert
DEP0101: --with-lttng#
Type: End-of-Life
The --with-lttng compile-time option has been removed.
DEP0102: Using noAssert in Buffer#(read|write) operations#
Type: End-of-Life
Using the noAssert argument has no functionality anymore. All input is verified regardless of the value of noAssert. Skipping the verification could lead to hard-to-find errors and crashes.
DEP0103: process.binding('util').is[...] typechecks#
Type: Documentation-only (supports --pending-deprecation)
Using process.binding() in general should be avoided. The type checking methods in particular can be replaced by using util.types.
This deprecation has been superseded by the deprecation of the process.binding() API (DEP0111).
DEP0104: process.env string coercion#
Type: Documentation-only (supports --pending-deprecation)
When assigning a non-string property to process.env, the assigned value is implicitly converted to a string. This behavior is deprecated if the assigned value is not a string, boolean, or number. In the future, such assignment might result in a thrown error. Please convert the property to a string before assigning it to process.env.
DEP0105: decipher.finaltol#
Type: End-of-Life
decipher.finaltol() has never been documented and was an alias for decipher.final(). This API has been removed, and it is recommended to use decipher.final() instead.
DEP0106: crypto.createCipher and crypto.createDecipher#
Type: End-of-Life
crypto.createCipher() and crypto.createDecipher() have been removed as they use a weak key derivation function (MD5 with no salt) and static initialization vectors. It is recommended to derive a key using crypto.pbkdf2() or crypto.scrypt() with random salts and to use crypto.createCipheriv() and crypto.createDecipheriv() to obtain the Cipheriv and Decipheriv objects respectively.
DEP0107: tls.convertNPNProtocols()#
Type: End-of-Life
This was an undocumented helper function not intended for use outside Node.js core and obsoleted by the removal of NPN (Next Protocol Negotiation) support.
DEP0108: zlib.bytesRead#
Type: End-of-Life
Deprecated alias for zlib.bytesWritten. This original name was chosen because it also made sense to interpret the value as the number of bytes read by the engine, but is inconsistent with other streams in Node.js that expose values under these names.
An automated migration is available (source):
npx codemod@latest @nodejs/zlib-bytesread-to-byteswritten
DEP0109: http, https, and tls support for invalid URLs#
Type: End-of-Life
Some previously supported (but strictly invalid) URLs were accepted through the http.request(), http.get(), https.request(), https.get(), and tls.checkServerIdentity() APIs because those were accepted by the legacy url.parse() API. The mentioned APIs now use the WHATWG URL parser that requires strictly valid URLs. Passing an invalid URL is deprecated and support will be removed in the future.
DEP0110: vm.Script cached data#
Type: Documentation-only
The produceCachedData option is deprecated. Use script.createCachedData() instead.
DEP0111: process.binding()#
Type: Documentation-only (supports --pending-deprecation)
process.binding() is for use by Node.js internal code only.
While process.binding() has not reached End-of-Life status in general, it is unavailable when the permission model is enabled.
DEP0112: dgram private APIs#
Type: End-of-Life
The node:dgram module previously contained several APIs that were never meant to accessed outside of Node.js core: Socket.prototype._handle, Socket.prototype._receiving, Socket.prototype._bindState, Socket.prototype._queue, Socket.prototype._reuseAddr, Socket.prototype._healthCheck(), Socket.prototype._stopReceiving(), and dgram._createSocketHandle(). These have been removed.
DEP0113: Cipher.setAuthTag(), Decipher.getAuthTag()#
Type: End-of-Life
Cipher.setAuthTag() and Decipher.getAuthTag() are no longer available. They were never documented and would throw when called.
DEP0114: crypto._toBuf()#
Type: End-of-Life
The crypto._toBuf() function was not designed to be used by modules outside of Node.js core and was removed.
DEP0115: crypto.prng(), crypto.pseudoRandomBytes(), crypto.rng()#
Type: Documentation-only (supports --pending-deprecation)
In recent versions of Node.js, there is no difference between crypto.randomBytes() and crypto.pseudoRandomBytes(). The latter is deprecated along with the undocumented aliases crypto.prng() and crypto.rng() in favor of crypto.randomBytes() and might be removed in a future release.
DEP0116: Legacy URL API#
Type: Deprecation revoked
The legacy URL API is deprecated. This includes url.format(), url.parse(), url.resolve(), and the legacy urlObject. Please use the WHATWG URL API instead.
An automated migration is available (source).
npx codemod@latest @nodejs/node-url-to-whatwg-url
DEP0117: Native crypto handles#
Type: End-of-Life
Previous versions of Node.js exposed handles to internal native objects through the _handle property of the Cipher, Decipher, DiffieHellman, DiffieHellmanGroup, ECDH, Hash, Hmac, Sign, and Verify classes. The _handle property has been removed because improper use of the native object can lead to crashing the application.
DEP0118: dns.lookup() support for a falsy host name#
Type: End-of-Life
Previous versions of Node.js supported dns.lookup() with a falsy host name like dns.lookup(false) due to backward compatibility. This has been removed.
DEP0119: process.binding('uv').errname() private API#
Type: Documentation-only (supports --pending-deprecation)
process.binding('uv').errname() is deprecated. Please use util.getSystemErrorName() instead.
DEP0120: Windows Performance Counter support#
Type: End-of-Life
Windows Performance Counter support has been removed from Node.js. The undocumented COUNTER_NET_SERVER_CONNECTION(), COUNTER_NET_SERVER_CONNECTION_CLOSE(), COUNTER_HTTP_SERVER_REQUEST(), COUNTER_HTTP_SERVER_RESPONSE(), COUNTER_HTTP_CLIENT_REQUEST(), and COUNTER_HTTP_CLIENT_RESPONSE() functions have been deprecated.
DEP0121: net._setSimultaneousAccepts()#
Type: End-of-Life
The undocumented net._setSimultaneousAccepts() function was originally intended for debugging and performance tuning when using the node:child_process and node:cluster modules on Windows. The function is not generally useful and is being removed. See discussion here: https://github.com/nodejs/node/issues/18391
DEP0122: tls Server.prototype.setOptions()#
Type: End-of-Life
Please use Server.prototype.setSecureContext() instead.
DEP0123: setting the TLS ServerName to an IP address#
Type: End-of-Life
Setting the TLS ServerName to an IP address is not permitted by RFC 6066.
DEP0124: using REPLServer.rli#
Type: End-of-Life
This property is a reference to the instance itself.
DEP0125: require('node:_stream_wrap')#
Type: End-of-Life
The node:_stream_wrap module is deprecated.
DEP0126: timers.active()#
Type: End-of-Life
The previously undocumented timers.active() has been removed. Please use the publicly documented timeout.refresh() instead. If re-referencing the timeout is necessary, timeout.ref() can be used with no performance impact since Node.js 10.
DEP0127: timers._unrefActive()#
Type: End-of-Life
The previously undocumented and "private" timers._unrefActive() has been removed. Please use the publicly documented timeout.refresh() instead. If unreferencing the timeout is necessary, timeout.unref() can be used with no performance impact since Node.js 10.
DEP0128: modules with an invalid main entry and an index.js file#
Type: Runtime
Modules that have an invalid main entry (e.g., ./does-not-exist.js) and also have an index.js file in the top level directory will resolve the index.js file. That is deprecated and is going to throw an error in future Node.js versions.
DEP0129: ChildProcess._channel#
Type: End-of-Life
The _channel property of child process objects returned by spawn() and similar functions is not intended for public use. Use ChildProcess.channel instead.
DEP0130: Module.createRequireFromPath()#
Type: End-of-Life
Use module.createRequire() instead.
An automated migration is available (source):
npx codemod@latest @nodejs/create-require-from-path
DEP0131: Legacy HTTP parser#
Type: End-of-Life
The legacy HTTP parser, used by default in versions of Node.js prior to 12.0.0, is deprecated and has been removed in v13.0.0. Prior to v13.0.0, the --http-parser=legacy command-line flag could be used to revert to using the legacy parser.
DEP0132: worker.terminate() with callback#
Type: End-of-Life
Passing a callback to worker.terminate() is deprecated. Use the returned Promise instead, or a listener to the worker's 'exit' event.
DEP0133: http connection#
Type: Documentation-only
Prefer response.socket over response.connection and request.socket over request.connection.
DEP0134: process._tickCallback#
Type: Documentation-only (supports --pending-deprecation)
The process._tickCallback property was never documented as an officially supported API.
DEP0135: WriteStream.open() and ReadStream.open() are internal#
Type: End-of-Life
WriteStream.open() and ReadStream.open() are undocumented internal APIs that do not make sense to use in userland. File streams should always be opened through their corresponding factory methods fs.createWriteStream() and fs.createReadStream()) or by passing a file descriptor in options.
DEP0136: http finished#
Type: Documentation-only
response.finished indicates whether response.end() has been called, not whether 'finish' has been emitted and the underlying data is flushed.
Use response.writableFinished or response.writableEnded accordingly instead to avoid the ambiguity.
To maintain existing behavior response.finished should be replaced with response.writableEnded.
DEP0137: Closing fs.FileHandle on garbage collection#
Type: End-of-Life
Allowing a fs.FileHandle object to be closed on garbage collection used to be allowed, but now throws an error.
Please ensure that all fs.FileHandle objects are explicitly closed using FileHandle.prototype.close() when the fs.FileHandle is no longer needed:
const fsPromises = require('node:fs').promises;
async function openAndClose() {
let filehandle;
try {
filehandle = await fsPromises.open('thefile.txt', 'r');
} finally {
if (filehandle !== undefined)
await filehandle.close();
}
}
DEP0138: process.mainModule#
Type: Documentation-only
process.mainModule is a CommonJS-only feature while process global object is shared with non-CommonJS environment. Its use within ECMAScript modules is unsupported.
It is deprecated in favor of require.main, because it serves the same purpose and is only available on CommonJS environment.
An automated migration is available (source):
npx codemod@latest @nodejs/process-main-module
DEP0139: process.umask() with no arguments#
Type: Documentation-only
Calling process.umask() with no argument causes the process-wide umask to be written twice. This introduces a race condition between threads, and is a potential security vulnerability. There is no safe, cross-platform alternative API.
DEP0140: Use request.destroy() instead of request.abort()#
Type: Documentation-only
Use request.destroy() instead of request.abort().
DEP0141: repl.inputStream and repl.outputStream#
Type: Documentation-only (supports --pending-deprecation)
The node:repl module exported the input and output stream twice. Use .input instead of .inputStream and .output instead of .outputStream.
DEP0142: repl._builtinLibs#
Type: Documentation-only (supports --pending-deprecation)
The node:repl module exports a _builtinLibs property that contains an array of built-in modules. It was incomplete so far and instead it's better to rely upon require('node:module').builtinModules.
An automated migration is available (source):
npx codemod@latest @nodejs/repl-builtin-modules
DEP0143: Transform._transformState#
Type: End-of-Life
Transform._transformState will be removed in future versions where it is no longer required due to simplification of the implementation.
DEP0144: module.parent#
Type: Documentation-only (supports --pending-deprecation)
A CommonJS module can access the first module that required it using module.parent. This feature is deprecated because it does not work consistently in the presence of ECMAScript modules and because it gives an inaccurate representation of the CommonJS module graph.
Some modules use it to check if they are the entry point of the current process. Instead, it is recommended to compare require.main and module:
if (require.main === module) {
// Code section that will run only if current file is the entry point.
}
When looking for the CommonJS modules that have required the current one, require.cache and module.children can be used:
const moduleParents = Object.values(require.cache)
.filter((m) => m.children.includes(module));
DEP0145: socket.bufferSize#
Type: Documentation-only
socket.bufferSize is just an alias for writable.writableLength.
DEP0146: new crypto.Certificate()#
Type: Documentation-only
The crypto.Certificate() constructor is deprecated. Use static methods of crypto.Certificate() instead.
DEP0147: fs.rmdir(path, { recursive: true })#
Type: End-of-Life
The fs.rmdir, fs.rmdirSync, and fs.promises.rmdir methods used to support a recursive option. That option has been removed.
Use fs.rm(path, { recursive: true, force: true }), fs.rmSync(path, { recursive: true, force: true }) or fs.promises.rm(path, { recursive: true, force: true }) instead.
An automated migration is available (source):
npx codemod@latest @nodejs/rmdir
DEP0148: Folder mappings in "exports" (trailing "/")#
Type: End-of-Life
Using a trailing "/" to define subpath folder mappings in the subpath exports or subpath imports fields is no longer supported. Use subpath patterns instead.
DEP0149: http.IncomingMessage#connection#
Type: Documentation-only
Prefer message.socket over message.connection.
DEP0150: Changing the value of process.config#
Type: End-of-Life
The process.config property provides access to Node.js compile-time settings. However, the property is mutable and therefore subject to tampering. The ability to change the value will be removed in a future version of Node.js.
DEP0151: Main index lookup and extension searching#
Type: Runtime
Previously, index.js and extension searching lookups would apply to import 'pkg' main entry point resolution, even when resolving ES modules.
With this deprecation, all ES module main entry point resolutions require an explicit "exports" or "main" entry with the exact file extension.
DEP0152: Extension PerformanceEntry properties#
Type: End-of-Life
The 'gc', 'http2', and 'http' <PerformanceEntry> object types used to have additional properties assigned to them that provide additional information. These properties are now available within the standard detail property of the PerformanceEntry object. The deprecated accessors have been removed.
DEP0153: dns.lookup and dnsPromises.lookup options type coercion#
Type: End-of-Life
Using a non-nullish non-integer value for family option, a non-nullish non-number value for hints option, a non-nullish non-boolean value for all option, or a non-nullish non-boolean value for verbatim option in dns.lookup() and dnsPromises.lookup() throws an ERR_INVALID_ARG_TYPE error.
DEP0154: RSA-PSS generate key pair options#
Type: End-of-Life
Use 'hashAlgorithm' instead of 'hash', and 'mgf1HashAlgorithm' instead of 'mgf1Hash'.
An automated migration is available (source):
npx codemod@latest @nodejs/crypto-rsa-pss-update
DEP0155: Trailing slashes in pattern specifier resolutions#
Type: Runtime
The remapping of specifiers ending in "/" like import 'pkg/x/' is deprecated for package "exports" and "imports" pattern resolutions.
DEP0156: .aborted property and 'abort', 'aborted' event in http#
Type: Documentation-only
Move to <Stream> API instead, as the http.ClientRequest, http.ServerResponse, and http.IncomingMessage are all stream-based. Check stream.destroyed instead of the .aborted property, and listen for 'close' instead of 'abort', 'aborted' event.
The .aborted property and 'abort' event are only useful for detecting .abort() calls. For closing a request early, use the Stream .destroy([error]) then check the .destroyed property and 'close' event should have the same effect. The receiving end should also check the readable.readableEnded value on http.IncomingMessage to get whether it was an aborted or graceful destroy.
DEP0157: Thenable support in streams#
Type: End-of-Life
An undocumented feature of Node.js streams was to support thenables in implementation methods. This is now deprecated, use callbacks instead and avoid use of async function for streams implementation methods.
This feature caused users to encounter unexpected problems where the user implements the function in callback style but uses e.g. an async method which would cause an error since mixing promise and callback semantics is not valid.
const w = new Writable({
async final(callback) {
await someOp();
callback();
},
});
DEP0158: buffer.slice(start, end)#
Type: Documentation-only
This method was deprecated because it is not compatible with Uint8Array.prototype.slice(), which is a superclass of Buffer.
Use buffer.subarray which does the same thing instead.
DEP0159: ERR_INVALID_CALLBACK#
Type: End-of-Life
This error code was removed due to adding more confusion to the errors used for value type validation.
DEP0160: process.on('multipleResolves', handler)#
Type: End-of-Life
This event was deprecated and removed because it did not work with V8 promise combinators which diminished its usefulness.
DEP0161: process._getActiveRequests() and process._getActiveHandles()#
Type: Documentation-only
The process._getActiveHandles() and process._getActiveRequests() functions are not intended for public use and can be removed in future releases.
Use process.getActiveResourcesInfo() to get a list of types of active resources and not the actual references.
DEP0162: fs.write(), fs.writeFileSync() coercion to string#
Type: End-of-Life
Implicit coercion of objects with own toString property, passed as second parameter in fs.write(), fs.writeFile(), fs.appendFile(), fs.writeFileSync(), and fs.appendFileSync() is deprecated. Convert them to primitive strings.
DEP0163: channel.subscribe(onMessage), channel.unsubscribe(onMessage)#
Type: Deprecation revoked
These methods were deprecated because their use could leave the channel object vulnerable to being garbage-collected if not strongly referenced by the user. The deprecation was revoked because channel objects are now resistant to garbage collection when the channel has active subscribers.
DEP0164: process.exit(code), process.exitCode coercion to integer#
Type: End-of-Life
Values other than undefined, null, integer numbers, and integer strings (e.g., '1') are deprecated as value for the code parameter in process.exit() and as value to assign to process.exitCode.
DEP0165: --trace-atomics-wait#
Type: End-of-Life
The --trace-atomics-wait flag has been removed because it uses the V8 hook SetAtomicsWaitCallback, that will be removed in a future V8 release.
DEP0166: Double slashes in imports and exports targets#
Type: Runtime
Package imports and exports targets mapping into paths including a double slash (of "/" or "\") are deprecated and will fail with a resolution validation error in a future release. This same deprecation also applies to pattern matches starting or ending in a slash.
DEP0167: Weak DiffieHellmanGroup instances (modp1, modp2, modp5)#
Type: Documentation-only
The well-known MODP groups modp1, modp2, and modp5 are deprecated because they are not secure against practical attacks. See RFC 8247 Section 2.4 for details.
These groups might be removed in future versions of Node.js. Applications that rely on these groups should evaluate using stronger MODP groups instead.
DEP0168: Unhandled exception in Node-API callbacks#
Type: Runtime
The implicit suppression of uncaught exceptions in Node-API callbacks is now deprecated.
Set the flag --force-node-api-uncaught-exceptions-policy to force Node.js to emit an 'uncaughtException' event if the exception is not handled in Node-API callbacks.
DEP0169: Insecure url.parse()#
Type: Application (non-node_modules code only)
url.parse() behavior is not standardized and prone to errors that have security implications. Use the WHATWG URL API instead. CVEs are not issued for url.parse() vulnerabilities.
Calling url.format(urlString) or url.resolve() invokes url.parse() internally, and is therefore also covered by this deprecation.
DEP0170: Invalid port when using url.parse()#
Type: End-of-Life
url.parse() used to accept URLs with ports that are not numbers. This behavior might result in host name spoofing with unexpected input. These URLs will throw an error (which the WHATWG URL API also does).
DEP0171: Setters for http.IncomingMessage headers and trailers#
Type: Documentation-only
In a future version of Node.js, message.headers, message.headersDistinct, message.trailers, and message.trailersDistinct will be read-only.
DEP0172: The asyncResource property of AsyncResource bound functions#
Type: End-of-Life
Older versions of Node.js would add the asyncResource when a function is bound to an AsyncResource. It no longer does.
DEP0173: the assert.CallTracker class#
Type: End-of-Life
The assert.CallTracker API has been removed.
DEP0174: calling promisify on a function that returns a Promise#
Type: Runtime
Calling util.promisify on a function that returns a Promise will ignore the result of said promise, which can lead to unhandled promise rejections.
DEP0175: util.toUSVString#
Type: Documentation-only
The util.toUSVString() API is deprecated. Please use String.prototype.toWellFormed instead.
DEP0176: fs.F_OK, fs.R_OK, fs.W_OK, fs.X_OK#
Type: End-of-Life
F_OK, R_OK, W_OK and X_OK getters exposed directly on node:fs were removed. Get them from fs.constants or fs.promises.constants instead.
An automated migration is available (source):
npx codemod@latest @nodejs/fs-access-mode-constants
DEP0177: util.types.isWebAssemblyCompiledModule#
Type: End-of-Life
The util.types.isWebAssemblyCompiledModule API has been removed. Please use value instanceof WebAssembly.Module instead.
DEP0178: dirent.path#
Type: End-of-Life
The dirent.path property has been removed due to its lack of consistency across release lines. Please use dirent.parentPath instead.
An automated migration is available (source):
npx codemod@latest @nodejs/dirent-path-to-parent-path
DEP0179: Hash constructor#
Type: Runtime
Calling Hash class directly with Hash() or new Hash() is deprecated due to being internals, not intended for public use. Please use the crypto.createHash() method to create Hash instances.
DEP0180: fs.Stats constructor#
Type: Runtime
Calling fs.Stats class directly with Stats() or new Stats() is deprecated due to being internals, not intended for public use.
DEP0181: Hmac constructor#
Type: Runtime
Calling Hmac class directly with Hmac() or new Hmac() is deprecated due to being internals, not intended for public use. Please use the crypto.createHmac() method to create Hmac instances.
DEP0182: Short GCM authentication tags without explicit authTagLength#
Type: End-of-Life
For ciphers in GCM mode, the decipher.setAuthTag() function used to accept authentication tags of any valid length (see also DEP0090). This exception has been removed to better align with recommendations per NIST SP 800-38D, and applications that intend to use authentication tags that are shorter than the default authentication tag length (i.e., shorter than 16 bytes for AES-GCM) must explicitly set the authTagLength option of the crypto.createDecipheriv() function to the appropriate length.
DEP0183: OpenSSL engine-based APIs#
Type: Documentation-only
OpenSSL 3 has deprecated support for custom engines with a recommendation to switch to its new provider model. The clientCertEngine option for https.request(), tls.createSecureContext(), and tls.createServer(); the privateKeyEngine and privateKeyIdentifier for tls.createSecureContext(); and crypto.setEngine() all depend on this functionality from OpenSSL.
DEP0184: Instantiating node:zlib classes without new#
Type: Runtime
Instantiating classes without the new qualifier exported by the node:zlib module is deprecated. It is recommended to use the new qualifier instead. This applies to all Zlib classes, such as Deflate, DeflateRaw, Gunzip, Inflate, InflateRaw, Unzip, and Zlib.
DEP0185: Instantiating node:repl classes without new#
Type: End-of-Life
Instantiating classes without the new qualifier exported by the node:repl module is deprecated. The new qualifier must be used instead. This applies to all REPL classes, including REPLServer and Recoverable.
An automated migration is available (source):
npx codemod@latest @nodejs/repl-classes-with-new
DEP0187: Passing invalid argument types to fs.existsSync#
Type: Runtime
Passing non-supported argument types is deprecated and, instead of returning false, will throw an error in a future version.
DEP0188: process.features.ipv6 and process.features.uv#
Type: Documentation-only
These properties are unconditionally true. Any checks based on these properties are redundant.
DEP0189: process.features.tls_*#
Type: Documentation-only
process.features.tls_alpn, process.features.tls_ocsp, and process.features.tls_sni are deprecated, as their values are guaranteed to be identical to that of process.features.tls.
DEP0190: Passing args to node:child_process execFile/spawn with shell option true#
Type: Runtime
When an args array is passed to child_process.execFile or child_process.spawn with the option { shell: true }, the values are not escaped, only space-separated, which can lead to shell injection.
DEP0191: repl.builtinModules#
Type: Documentation-only (supports --pending-deprecation)
The node:repl module exports a builtinModules property that contains an array of built-in modules. This was incomplete and matched the already deprecated repl._builtinLibs (DEP0142) instead it's better to rely upon require('node:module').builtinModules.
An automated migration is available (source):
npx codemod@latest @nodejs/repl-builtin-modules
DEP0192: require('node:_tls_common') and require('node:_tls_wrap')#
Type: Runtime
The node:_tls_common and node:_tls_wrap modules are deprecated as they should be considered an internal nodejs implementation rather than a public facing API, use node:tls instead.
DEP0193: require('node:_stream_*')#
Type: End-of-Life
The node:_stream_duplex, node:_stream_passthrough, node:_stream_readable, node:_stream_transform, node:_stream_wrap and node:_stream_writable modules are deprecated as they should be considered an internal nodejs implementation rather than a public facing API, use node:stream instead.
DEP0194: HTTP/2 priority signaling#
Type: End-of-Life
The support for priority signaling has been removed following its deprecation in the RFC 9113.
DEP0195: Instantiating node:http classes without new#
Type: Documentation-only
Instantiating classes without the new qualifier exported by the node:http module is deprecated. It is recommended to use the new qualifier instead. This applies to all http classes, such as OutgoingMessage, IncomingMessage, ServerResponse and ClientRequest.
An automated migration is available (source):
npx codemod@latest @nodejs/http-classes-with-new
DEP0196: Calling node:child_process functions with options.shell as an empty string#
Type: Documentation-only
Calling the process-spawning functions with { shell: '' } is almost certainly unintentional, and can cause aberrant behavior.
To make child_process.execFile or child_process.spawn invoke the default shell, use { shell: true }. If the intention is not to invoke a shell (default behavior), either omit the shell option, or set it to false or a nullish value.
To make child_process.exec invoke the default shell, either omit the shell option, or set it to a nullish value. If the intention is not to invoke a shell, use child_process.execFile instead.
DEP0197: util.types.isNativeError()#
Type: Documentation-only
The util.types.isNativeError API is deprecated. Please use Error.isError instead.
An automated migration is available (source):
npx codemod@latest @nodejs/types-is-native-error
DEP0198: Creating SHAKE-128 and SHAKE-256 digests without an explicit options.outputLength#
Type: Runtime
Creating SHAKE-128 and SHAKE-256 digests without an explicit options.outputLength is deprecated.
DEP0199: require('node:_http_*')#
Type: Documentation-only
The node:_http_agent, node:_http_client, node:_http_common, node:_http_incoming, node:_http_outgoing and node:_http_server modules are deprecated as they should be considered an internal nodejs implementation rather than a public facing API, use node:http instead.
DEP0200: Closing fs.Dir on garbage collection#
Type: Documentation-only
Allowing a fs.Dir object to be closed on garbage collection is deprecated. In the future, doing so might result in a thrown error that will terminate the process.
Please ensure that all fs.Dir objects are explicitly closed using Dir.prototype.close() or using keyword:
import { opendir } from 'node:fs/promises';
{
await using dir = await opendir('/async/disposable/directory');
} // Closed by dir[Symbol.asyncDispose]()
{
using dir = await opendir('/sync/disposable/directory');
} // Closed by dir[Symbol.dispose]()
{
const dir = await opendir('/unconditionally/iterated/directory');
for await (const entry of dir) {
// process an entry
} // Closed by iterator
}
{
let dir;
try {
dir = await opendir('/legacy/closeable/directory');
} finally {
await dir?.close();
}
}
DEP0201: Passing options.type to Duplex.toWeb()#
Type: Documentation-only
Passing the type option to Duplex.toWeb() is deprecated. To specify the type of the readable half of the constructed readable-writable pair, use the readableType option instead.
DEP0202: Http1IncomingMessage and Http1ServerResponse options of HTTP/2 servers#
Type: Documentation-only
The Http1IncomingMessage and Http1ServerResponse options of http2.createServer() and http2.createSecureServer() are deprecated. Use http1Options.IncomingMessage and http1Options.ServerResponse instead.
// Deprecated const server = http2.createSecureServer({ allowHTTP1: true, Http1IncomingMessage: MyIncomingMessage, Http1ServerResponse: MyServerResponse, });// Use this instead const server = http2.createSecureServer({ allowHTTP1: true, http1Options: { IncomingMessage: MyIncomingMessage, ServerResponse: MyServerResponse, }, });
Diagnostic report#
Stability: 2 - Stable
Delivers a JSON-formatted diagnostic summary, written to a file.
The report is intended for development, test, and production use, to capture and preserve information for problem determination. It includes JavaScript and native stack traces, heap statistics, platform information, resource usage etc. With the report option enabled, diagnostic reports can be triggered on unhandled exceptions, fatal errors and user signals, in addition to triggering programmatically through API calls.
A complete example report that was generated on an uncaught exception is provided below for reference.
{
"header": {
"reportVersion": 5,
"event": "exception",
"trigger": "Exception",
"filename": "report.20181221.005011.8974.0.001.json",
"dumpEventTime": "2018-12-21T00:50:11Z",
"dumpEventTimeStamp": "1545371411331",
"processId": 8974,
"cwd": "/home/nodeuser/project/node",
"commandLine": [
"/home/nodeuser/project/node/out/Release/node",
"--report-uncaught-exception",
"/home/nodeuser/project/node/test/report/test-exception.js",
"child"
],
"nodejsVersion": "v12.0.0-pre",
"glibcVersionRuntime": "2.17",
"glibcVersionCompiler": "2.17",
"wordSize": "64 bit",
"arch": "x64",
"platform": "linux",
"componentVersions": {
"node": "12.0.0-pre",
"v8": "7.1.302.28-node.5",
"uv": "1.24.1",
"zlib": "1.2.11",
"ares": "1.15.0",
"modules": "68",
"nghttp2": "1.34.0",
"napi": "3",
"llhttp": "1.0.1",
"openssl": "1.1.0j"
},
"release": {
"name": "node"
},
"osName": "Linux",
"osRelease": "3.10.0-862.el7.x86_64",
"osVersion": "#1 SMP Wed Mar 21 18:14:51 EDT 2018",
"osMachine": "x86_64",
"cpus": [
{
"model": "Intel(R) Core(TM) i7-6820HQ CPU @ 2.70GHz",
"speed": 2700,
"user": 88902660,
"nice": 0,
"sys": 50902570,
"idle": 241732220,
"irq": 0
},
{
"model": "Intel(R) Core(TM) i7-6820HQ CPU @ 2.70GHz",
"speed": 2700,
"user": 88902660,
"nice": 0,
"sys": 50902570,
"idle": 241732220,
"irq": 0
}
],
"networkInterfaces": [
{
"name": "en0",
"internal": false,
"mac": "13:10:de:ad:be:ef",
"address": "10.0.0.37",
"netmask": "255.255.255.0",
"family": "IPv4"
}
],
"host": "test_machine"
},
"javascriptStack": {
"message": "Error: *** test-exception.js: throwing uncaught Error",
"stack": [
"at myException (/home/nodeuser/project/node/test/report/test-exception.js:9:11)",
"at Object.<anonymous> (/home/nodeuser/project/node/test/report/test-exception.js:12:3)",
"at Module._compile (internal/modules/cjs/loader.js:718:30)",
"at Object.Module._extensions..js (internal/modules/cjs/loader.js:729:10)",
"at Module.load (internal/modules/cjs/loader.js:617:32)",
"at tryModuleLoad (internal/modules/cjs/loader.js:560:12)",
"at Function.Module._load (internal/modules/cjs/loader.js:552:3)",
"at Function.Module.runMain (internal/modules/cjs/loader.js:771:12)",
"at executeUserCode (internal/bootstrap/node.js:332:15)"
]
},
"nativeStack": [
{
"pc": "0x000055b57f07a9ef",
"symbol": "report::GetNodeReport(v8::Isolate*, node::Environment*, char const*, char const*, v8::Local<v8::String>, std::ostream&) [./node]"
},
{
"pc": "0x000055b57f07cf03",
"symbol": "report::GetReport(v8::FunctionCallbackInfo<v8::Value> const&) [./node]"
},
{
"pc": "0x000055b57f1bccfd",
"symbol": " [./node]"
},
{
"pc": "0x000055b57f1be048",
"symbol": "v8::internal::Builtin_HandleApiCall(int, v8::internal::Object**, v8::internal::Isolate*) [./node]"
},
{
"pc": "0x000055b57feeda0e",
"symbol": " [./node]"
}
],
"javascriptHeap": {
"totalMemory": 5660672,
"executableMemory": 524288,
"totalCommittedMemory": 5488640,
"availableMemory": 4341379928,
"totalGlobalHandlesMemory": 8192,
"usedGlobalHandlesMemory": 3136,
"usedMemory": 4816432,
"memoryLimit": 4345298944,
"mallocedMemory": 254128,
"externalMemory": 315644,
"peakMallocedMemory": 98752,
"nativeContextCount": 1,
"detachedContextCount": 0,
"doesZapGarbage": 0,
"heapSpaces": {
"read_only_space": {
"memorySize": 524288,
"committedMemory": 39208,
"capacity": 515584,
"used": 30504,
"available": 485080
},
"new_space": {
"memorySize": 2097152,
"committedMemory": 2019312,
"capacity": 1031168,
"used": 985496,
"available": 45672
},
"old_space": {
"memorySize": 2273280,
"committedMemory": 1769008,
"capacity": 1974640,
"used": 1725488,
"available": 249152
},
"code_space": {
"memorySize": 696320,
"committedMemory": 184896,
"capacity": 152128,
"used": 152128,
"available": 0
},
"map_space": {
"memorySize": 536576,
"committedMemory": 344928,
"capacity": 327520,
"used": 327520,
"available": 0
},
"large_object_space": {
"memorySize": 0,
"committedMemory": 0,
"capacity": 1520590336,
"used": 0,
"available": 1520590336
},
"new_large_object_space": {
"memorySize": 0,
"committedMemory": 0,
"capacity": 0,
"used": 0,
"available": 0
}
}
},
"resourceUsage": {
"rss": "35766272",
"free_memory": "1598337024",
"total_memory": "17179869184",
"available_memory": "1598337024",
"maxRss": "36624662528",
"constrained_memory": "36624662528",
"userCpuSeconds": 0.040072,
"kernelCpuSeconds": 0.016029,
"cpuConsumptionPercent": 5.6101,
"userCpuConsumptionPercent": 4.0072,
"kernelCpuConsumptionPercent": 1.6029,
"pageFaults": {
"IORequired": 0,
"IONotRequired": 4610
},
"fsActivity": {
"reads": 0,
"writes": 0
}
},
"uvthreadResourceUsage": {
"userCpuSeconds": 0.039843,
"kernelCpuSeconds": 0.015937,
"cpuConsumptionPercent": 5.578,
"userCpuConsumptionPercent": 3.9843,
"kernelCpuConsumptionPercent": 1.5937,
"fsActivity": {
"reads": 0,
"writes": 0
}
},
"libuv": [
{
"type": "async",
"is_active": true,
"is_referenced": false,
"address": "0x0000000102910900",
"details": ""
},
{
"type": "timer",
"is_active": false,
"is_referenced": false,
"address": "0x00007fff5fbfeab0",
"repeat": 0,
"firesInMsFromNow": 94403548320796,
"expired": true
},
{
"type": "check",
"is_active": true,
"is_referenced": false,
"address": "0x00007fff5fbfeb48"
},
{
"type": "idle",
"is_active": false,
"is_referenced": true,
"address": "0x00007fff5fbfebc0"
},
{
"type": "prepare",
"is_active": false,
"is_referenced": false,
"address": "0x00007fff5fbfec38"
},
{
"type": "check",
"is_active": false,
"is_referenced": false,
"address": "0x00007fff5fbfecb0"
},
{
"type": "async",
"is_active": true,
"is_referenced": false,
"address": "0x000000010188f2e0"
},
{
"type": "tty",
"is_active": false,
"is_referenced": true,
"address": "0x000055b581db0e18",
"width": 204,
"height": 55,
"fd": 17,
"writeQueueSize": 0,
"readable": true,
"writable": true
},
{
"type": "signal",
"is_active": true,
"is_referenced": false,
"address": "0x000055b581d80010",
"signum": 28,
"signal": "SIGWINCH"
},
{
"type": "tty",
"is_active": true,
"is_referenced": true,
"address": "0x000055b581df59f8",
"width": 204,
"height": 55,
"fd": 19,
"writeQueueSize": 0,
"readable": true,
"writable": true
},
{
"type": "loop",
"is_active": true,
"address": "0x000055fc7b2cb180",
"loopIdleTimeSeconds": 22644.8
},
{
"type": "tcp",
"is_active": true,
"is_referenced": true,
"address": "0x000055e70fcb85d8",
"localEndpoint": {
"host": "localhost",
"ip4": "127.0.0.1",
"port": 48986
},
"remoteEndpoint": {
"host": "localhost",
"ip4": "127.0.0.1",
"port": 38573
},
"sendBufferSize": 2626560,
"recvBufferSize": 131072,
"fd": 24,
"writeQueueSize": 0,
"readable": true,
"writable": true
}
],
"workers": [],
"environmentVariables": {
"REMOTEHOST": "REMOVED",
"MANPATH": "/opt/rh/devtoolset-3/root/usr/share/man:",
"XDG_SESSION_ID": "66126",
"HOSTNAME": "test_machine",
"HOST": "test_machine",
"TERM": "xterm-256color",
"SHELL": "/bin/csh",
"SSH_CLIENT": "REMOVED",
"PERL5LIB": "/opt/rh/devtoolset-3/root//usr/lib64/perl5/vendor_perl:/opt/rh/devtoolset-3/root/usr/lib/perl5:/opt/rh/devtoolset-3/root//usr/share/perl5/vendor_perl",
"OLDPWD": "/home/nodeuser/project/node/src",
"JAVACONFDIRS": "/opt/rh/devtoolset-3/root/etc/java:/etc/java",
"SSH_TTY": "/dev/pts/0",
"PCP_DIR": "/opt/rh/devtoolset-3/root",
"GROUP": "normaluser",
"USER": "nodeuser",
"LD_LIBRARY_PATH": "/opt/rh/devtoolset-3/root/usr/lib64:/opt/rh/devtoolset-3/root/usr/lib",
"HOSTTYPE": "x86_64-linux",
"XDG_CONFIG_DIRS": "/opt/rh/devtoolset-3/root/etc/xdg:/etc/xdg",
"MAIL": "/var/spool/mail/nodeuser",
"PATH": "/home/nodeuser/project/node:/opt/rh/devtoolset-3/root/usr/bin:/usr/local/bin:/usr/bin:/usr/local/sbin:/usr/sbin",
"PWD": "/home/nodeuser/project/node",
"LANG": "en_US.UTF-8",
"PS1": "\\u@\\h : \\[\\e[31m\\]\\w\\[\\e[m\\] > ",
"SHLVL": "2",
"HOME": "/home/nodeuser",
"OSTYPE": "linux",
"VENDOR": "unknown",
"PYTHONPATH": "/opt/rh/devtoolset-3/root/usr/lib64/python2.7/site-packages:/opt/rh/devtoolset-3/root/usr/lib/python2.7/site-packages",
"MACHTYPE": "x86_64",
"LOGNAME": "nodeuser",
"XDG_DATA_DIRS": "/opt/rh/devtoolset-3/root/usr/share:/usr/local/share:/usr/share",
"LESSOPEN": "||/usr/bin/lesspipe.sh %s",
"INFOPATH": "/opt/rh/devtoolset-3/root/usr/share/info",
"XDG_RUNTIME_DIR": "/run/user/50141",
"_": "./node"
},
"userLimits": {
"core_file_size_blocks": {
"soft": "",
"hard": "unlimited"
},
"data_seg_size_bytes": {
"soft": "unlimited",
"hard": "unlimited"
},
"file_size_blocks": {
"soft": "unlimited",
"hard": "unlimited"
},
"max_locked_memory_bytes": {
"soft": "unlimited",
"hard": 65536
},
"max_memory_size_bytes": {
"soft": "unlimited",
"hard": "unlimited"
},
"open_files": {
"soft": "unlimited",
"hard": 4096
},
"stack_size_bytes": {
"soft": "unlimited",
"hard": "unlimited"
},
"cpu_time_seconds": {
"soft": "unlimited",
"hard": "unlimited"
},
"max_user_processes": {
"soft": "unlimited",
"hard": 4127290
},
"virtual_memory_bytes": {
"soft": "unlimited",
"hard": "unlimited"
}
},
"sharedObjects": [
"/lib64/libdl.so.2",
"/lib64/librt.so.1",
"/lib64/libstdc++.so.6",
"/lib64/libm.so.6",
"/lib64/libgcc_s.so.1",
"/lib64/libpthread.so.0",
"/lib64/libc.so.6",
"/lib64/ld-linux-x86-64.so.2"
]
}
Usage#
node --report-uncaught-exception --report-on-signal \
--report-on-fatalerror app.js
--report-uncaught-exceptionEnables report to be generated on un-caught exceptions. Useful when inspecting JavaScript stack in conjunction with native stack and other runtime environment data.--report-on-signalEnables report to be generated upon receiving the specified (or predefined) signal to the running Node.js process. (See below on how to modify the signal that triggers the report.) Default signal isSIGUSR2. Useful when a report needs to be triggered from another program. Application monitors may leverage this feature to collect report at regular intervals and plot rich set of internal runtime data to their views.
Signal based report generation is not supported in Windows.
Under normal circumstances, there is no need to modify the report triggering signal. However, if SIGUSR2 is already used for other purposes, then this flag helps to change the signal for report generation and preserve the original meaning of SIGUSR2 for the said purposes.
--report-on-fatalerrorEnables the report to be triggered on fatal errors (internal errors within the Node.js runtime, such as out of memory) that leads to termination of the application. Useful to inspect various diagnostic data elements such as heap, stack, event loop state, resource consumption etc. to reason about the fatal error.--report-compactWrite reports in a compact format, single-line JSON, more easily consumable by log processing systems than the default multi-line format designed for human consumption.--report-directoryLocation at which the report will be generated.--report-filenameName of the file to which the report will be written.--report-signalSets or resets the signal for report generation (not supported on Windows). Default signal isSIGUSR2.--report-exclude-networkExcludeheader.networkInterfacesand disable the reverse DNS queries inlibuv.*.(remote|local)Endpoint.hostfrom the diagnostic report. By default this is not set and the network interfaces are included.--report-exclude-envExcludeenvironmentVariablesfrom the diagnostic report. By default this is not set and the environment variables are included.
A report can also be triggered via an API call from a JavaScript application:
process.report.writeReport();
This function takes an optional additional argument filename, which is the name of a file into which the report is written.
process.report.writeReport('./foo.json');
This function takes an optional additional argument err which is an Error object that will be used as the context for the JavaScript stack printed in the report. When using report to handle errors in a callback or an exception handler, this allows the report to include the location of the original error as well as where it was handled.
try {
process.chdir('/non-existent-path');
} catch (err) {
process.report.writeReport(err);
}
// Any other code
If both filename and error object are passed to writeReport() the error object must be the second parameter.
try {
process.chdir('/non-existent-path');
} catch (err) {
process.report.writeReport(filename, err);
}
// Any other code
The content of the diagnostic report can be returned as a JavaScript Object via an API call from a JavaScript application:
const report = process.report.getReport();
console.log(typeof report === 'object'); // true
// Similar to process.report.writeReport() output
console.log(JSON.stringify(report, null, 2));
This function takes an optional additional argument err, which is an Error object that will be used as the context for the JavaScript stack printed in the report.
const report = process.report.getReport(new Error('custom error'));
console.log(typeof report === 'object'); // true
The API versions are useful when inspecting the runtime state from within the application, in expectation of self-adjusting the resource consumption, load balancing, monitoring etc.
The content of the report consists of a header section containing the event type, date, time, PID, and Node.js version, sections containing JavaScript and native stack traces, a section containing V8 heap information, a section containing libuv handle information, and an OS platform information section showing CPU and memory usage and system limits. An example report can be triggered using the Node.js REPL:
$ node
> process.report.writeReport();
Writing Node.js report to file: report.20181126.091102.8480.0.001.json
Node.js report completed
>
When a report is written, start and end messages are issued to stderr and the filename of the report is returned to the caller. The default filename includes the date, time, PID, and a sequence number. The sequence number helps in associating the report dump with the runtime state if generated multiple times for the same Node.js process.
Report Version#
Diagnostic report has an associated single-digit version number (report.header.reportVersion), uniquely representing the report format. The version number is bumped when new key is added or removed, or the data type of a value is changed. Report version definitions are consistent across LTS releases.
Version history#
Version 5#
Replace the keys data_seg_size_kbytes, max_memory_size_kbytes, and virtual_memory_kbytes with data_seg_size_bytes, max_memory_size_bytes, and virtual_memory_bytes respectively in the userLimits section, as these values are given in bytes.
{
"userLimits": {
// Skip some keys ...
"data_seg_size_bytes": { // replacing data_seg_size_kbytes
"soft": "unlimited",
"hard": "unlimited"
},
// ...
"max_memory_size_bytes": { // replacing max_memory_size_kbytes
"soft": "unlimited",
"hard": "unlimited"
},
// ...
"virtual_memory_bytes": { // replacing virtual_memory_kbytes
"soft": "unlimited",
"hard": "unlimited"
}
}
}
Version 4#
New fields ipv4 and ipv6 are added to tcp and udp libuv handles endpoints. Examples:
{
"libuv": [
{
"type": "tcp",
"is_active": true,
"is_referenced": true,
"address": "0x000055e70fcb85d8",
"localEndpoint": {
"host": "localhost",
"ip4": "127.0.0.1", // new key
"port": 48986
},
"remoteEndpoint": {
"host": "localhost",
"ip4": "127.0.0.1", // new key
"port": 38573
},
"sendBufferSize": 2626560,
"recvBufferSize": 131072,
"fd": 24,
"writeQueueSize": 0,
"readable": true,
"writable": true
},
{
"type": "tcp",
"is_active": true,
"is_referenced": true,
"address": "0x000055e70fcd68c8",
"localEndpoint": {
"host": "ip6-localhost",
"ip6": "::1", // new key
"port": 52266
},
"remoteEndpoint": {
"host": "ip6-localhost",
"ip6": "::1", // new key
"port": 38573
},
"sendBufferSize": 2626560,
"recvBufferSize": 131072,
"fd": 25,
"writeQueueSize": 0,
"readable": false,
"writable": false
}
]
}
Version 3#
The following memory usage keys are added to the resourceUsage section.
{
"resourceUsage": {
"rss": "35766272",
"free_memory": "1598337024",
"total_memory": "17179869184",
"available_memory": "1598337024",
"constrained_memory": "36624662528"
}
}
Version 2#
Added Worker support. Refer to Interaction with workers section for more details.
Version 1#
This is the first version of the diagnostic report.
Configuration#
Additional runtime configuration of report generation is available via the following properties of process.report:
reportOnFatalError triggers diagnostic reporting on fatal errors when true. Defaults to false.
reportOnSignal triggers diagnostic reporting on signal when true. This is not supported on Windows. Defaults to false.
reportOnUncaughtException triggers diagnostic reporting on uncaught exception when true. Defaults to false.
signal specifies the POSIX signal identifier that will be used to intercept external triggers for report generation. Defaults to 'SIGUSR2'.
filename specifies the name of the output file in the file system. Special meaning is attached to stdout and stderr. Usage of these will result in report being written to the associated standard streams. In cases where standard streams are used, the value in directory is ignored. URLs are not supported. Defaults to a composite filename that contains timestamp, PID, and sequence number.
directory specifies the file system directory where the report will be written. URLs are not supported. Defaults to the current working directory of the Node.js process.
excludeNetwork excludes header.networkInterfaces from the diagnostic report.
// Trigger report only on uncaught exceptions.
process.report.reportOnFatalError = false;
process.report.reportOnSignal = false;
process.report.reportOnUncaughtException = true;
// Trigger report for both internal errors as well as external signal.
process.report.reportOnFatalError = true;
process.report.reportOnSignal = true;
process.report.reportOnUncaughtException = false;
// Change the default signal to 'SIGQUIT' and enable it.
process.report.reportOnFatalError = false;
process.report.reportOnUncaughtException = false;
process.report.reportOnSignal = true;
process.report.signal = 'SIGQUIT';
// Disable network interfaces reporting
process.report.excludeNetwork = true;
Configuration on module initialization is also available via environment variables:
NODE_OPTIONS="--report-uncaught-exception \
--report-on-fatalerror --report-on-signal \
--report-signal=SIGUSR2 --report-filename=./report.json \
--report-directory=/home/nodeuser"
Specific API documentation can be found under process API documentation section.
Interaction with workers#
Worker threads can create reports in the same way that the main thread does.
Reports will include information on any Workers that are children of the current thread as part of the workers section, with each Worker generating a report in the standard report format.
The thread which is generating the report will wait for the reports from Worker threads to finish. However, the latency for this will usually be low, as both running JavaScript and the event loop are interrupted to generate the report.
Diagnostics Channel#
Stability: 2 - Stable
The node:diagnostics_channel module provides an API to create named channels to report arbitrary message data for diagnostics purposes.
It can be accessed using:
import diagnostics_channel from 'node:diagnostics_channel';const diagnostics_channel = require('node:diagnostics_channel');
It is intended that a module writer wanting to report diagnostics messages will create one or many top-level channels to report messages through. Channels may also be acquired at runtime but it is not encouraged due to the additional overhead of doing so. Channels may be exported for convenience, but as long as the name is known it can be acquired anywhere.
If you intend for your module to produce diagnostics data for others to consume it is recommended that you include documentation of what named channels are used along with the shape of the message data. Channel names should generally include the module name to avoid collisions with data from other modules.
Public API#
Overview#
Following is a simple overview of the public API.
import diagnostics_channel from 'node:diagnostics_channel'; // Get a reusable channel object const channel = diagnostics_channel.channel('my-channel'); function onMessage(message, name) { // Received data } // Subscribe to the channel diagnostics_channel.subscribe('my-channel', onMessage); // Check if the channel has an active subscriber if (channel.hasSubscribers) { // Publish data to the channel channel.publish({ some: 'data', }); } // Unsubscribe from the channel diagnostics_channel.unsubscribe('my-channel', onMessage);const diagnostics_channel = require('node:diagnostics_channel'); // Get a reusable channel object const channel = diagnostics_channel.channel('my-channel'); function onMessage(message, name) { // Received data } // Subscribe to the channel diagnostics_channel.subscribe('my-channel', onMessage); // Check if the channel has an active subscriber if (channel.hasSubscribers) { // Publish data to the channel channel.publish({ some: 'data', }); } // Unsubscribe from the channel diagnostics_channel.unsubscribe('my-channel', onMessage);
diagnostics_channel.hasSubscribers(name)#
Check if there are active subscribers to the named channel. This is helpful if the message you want to send might be expensive to prepare.
This API is optional but helpful when trying to publish messages from very performance-sensitive code.
import diagnostics_channel from 'node:diagnostics_channel'; if (diagnostics_channel.hasSubscribers('my-channel')) { // There are subscribers, prepare and publish message }const diagnostics_channel = require('node:diagnostics_channel'); if (diagnostics_channel.hasSubscribers('my-channel')) { // There are subscribers, prepare and publish message }
diagnostics_channel.channel(name)#
This is the primary entry-point for anyone wanting to publish to a named channel. It produces a channel object which is optimized to reduce overhead at publish time as much as possible.
import diagnostics_channel from 'node:diagnostics_channel'; const channel = diagnostics_channel.channel('my-channel');const diagnostics_channel = require('node:diagnostics_channel'); const channel = diagnostics_channel.channel('my-channel');
diagnostics_channel.subscribe(name, onMessage)#
name<string>|<symbol>The channel nameonMessage<Function>The handler to receive channel messages
Register a message handler to subscribe to this channel. This message handler will be run synchronously whenever a message is published to the channel. Any errors thrown in the message handler will trigger an 'uncaughtException'.
import diagnostics_channel from 'node:diagnostics_channel'; diagnostics_channel.subscribe('my-channel', (message, name) => { // Received data });const diagnostics_channel = require('node:diagnostics_channel'); diagnostics_channel.subscribe('my-channel', (message, name) => { // Received data });
diagnostics_channel.unsubscribe(name, onMessage)#
name<string>|<symbol>The channel nameonMessage<Function>The previous subscribed handler to remove- Returns:
<boolean>trueif the handler was found,falseotherwise.
Remove a message handler previously registered to this channel with diagnostics_channel.subscribe(name, onMessage).
import diagnostics_channel from 'node:diagnostics_channel'; function onMessage(message, name) { // Received data } diagnostics_channel.subscribe('my-channel', onMessage); diagnostics_channel.unsubscribe('my-channel', onMessage);const diagnostics_channel = require('node:diagnostics_channel'); function onMessage(message, name) { // Received data } diagnostics_channel.subscribe('my-channel', onMessage); diagnostics_channel.unsubscribe('my-channel', onMessage);
diagnostics_channel.tracingChannel(nameOrChannels)#
Stability: 1 - Experimental
nameOrChannels<string>|<TracingChannel>Channel name or object containing all the TracingChannel Channels- Returns:
<TracingChannel>Collection of channels to trace with
Creates a TracingChannel wrapper for the given TracingChannel Channels. If a name is given, the corresponding tracing channels will be created in the form of tracing:${name}:${eventType} where eventType corresponds to the types of TracingChannel Channels.
import diagnostics_channel from 'node:diagnostics_channel'; const channelsByName = diagnostics_channel.tracingChannel('my-channel'); // or... const channelsByCollection = diagnostics_channel.tracingChannel({ start: diagnostics_channel.channel('tracing:my-channel:start'), end: diagnostics_channel.channel('tracing:my-channel:end'), asyncStart: diagnostics_channel.channel('tracing:my-channel:asyncStart'), asyncEnd: diagnostics_channel.channel('tracing:my-channel:asyncEnd'), error: diagnostics_channel.channel('tracing:my-channel:error'), });const diagnostics_channel = require('node:diagnostics_channel'); const channelsByName = diagnostics_channel.tracingChannel('my-channel'); // or... const channelsByCollection = diagnostics_channel.tracingChannel({ start: diagnostics_channel.channel('tracing:my-channel:start'), end: diagnostics_channel.channel('tracing:my-channel:end'), asyncStart: diagnostics_channel.channel('tracing:my-channel:asyncStart'), asyncEnd: diagnostics_channel.channel('tracing:my-channel:asyncEnd'), error: diagnostics_channel.channel('tracing:my-channel:error'), });
Class: Channel#
The class Channel represents an individual named channel within the data pipeline. It is used to track subscribers and to publish messages when there are subscribers present. It exists as a separate object to avoid channel lookups at publish time, enabling very fast publish speeds and allowing for heavy use while incurring very minimal cost. Channels are created with diagnostics_channel.channel(name), constructing a channel directly with new Channel(name) is not supported.
channel.hasSubscribers#
- Returns:
<boolean>If there are active subscribers
Check if there are active subscribers to this channel. This is helpful if the message you want to send might be expensive to prepare.
This API is optional but helpful when trying to publish messages from very performance-sensitive code.
import diagnostics_channel from 'node:diagnostics_channel'; const channel = diagnostics_channel.channel('my-channel'); if (channel.hasSubscribers) { // There are subscribers, prepare and publish message }const diagnostics_channel = require('node:diagnostics_channel'); const channel = diagnostics_channel.channel('my-channel'); if (channel.hasSubscribers) { // There are subscribers, prepare and publish message }
channel.publish(message)#
message<any>The message to send to the channel subscribers
Publish a message to any subscribers to the channel. This will trigger message handlers synchronously so they will execute within the same context.
import diagnostics_channel from 'node:diagnostics_channel'; const channel = diagnostics_channel.channel('my-channel'); channel.publish({ some: 'message', });const diagnostics_channel = require('node:diagnostics_channel'); const channel = diagnostics_channel.channel('my-channel'); channel.publish({ some: 'message', });
channel.subscribe(onMessage)#
onMessage<Function>The handler to receive channel messages
Register a message handler to subscribe to this channel. This message handler will be run synchronously whenever a message is published to the channel. Any errors thrown in the message handler will trigger an 'uncaughtException'.
import diagnostics_channel from 'node:diagnostics_channel'; const channel = diagnostics_channel.channel('my-channel'); channel.subscribe((message, name) => { // Received data });const diagnostics_channel = require('node:diagnostics_channel'); const channel = diagnostics_channel.channel('my-channel'); channel.subscribe((message, name) => { // Received data });
channel.unsubscribe(onMessage)#
onMessage<Function>The previous subscribed handler to remove- Returns:
<boolean>trueif the handler was found,falseotherwise.
Remove a message handler previously registered to this channel with channel.subscribe(onMessage).
import diagnostics_channel from 'node:diagnostics_channel'; const channel = diagnostics_channel.channel('my-channel'); function onMessage(message, name) { // Received data } channel.subscribe(onMessage); channel.unsubscribe(onMessage);const diagnostics_channel = require('node:diagnostics_channel'); const channel = diagnostics_channel.channel('my-channel'); function onMessage(message, name) { // Received data } channel.subscribe(onMessage); channel.unsubscribe(onMessage);
channel.bindStore(store[, transform])#
Stability: 1 - Experimental
store<AsyncLocalStorage>The store to which to bind the context datatransform<Function>Transform context data before setting the store context
When channel.runStores(context, ...) is called, the given context data will be applied to any store bound to the channel. If the store has already been bound the previous transform function will be replaced with the new one. The transform function may be omitted to set the given context data as the context directly.
import diagnostics_channel from 'node:diagnostics_channel'; import { AsyncLocalStorage } from 'node:async_hooks'; const store = new AsyncLocalStorage(); const channel = diagnostics_channel.channel('my-channel'); channel.bindStore(store, (data) => { return { data }; });const diagnostics_channel = require('node:diagnostics_channel'); const { AsyncLocalStorage } = require('node:async_hooks'); const store = new AsyncLocalStorage(); const channel = diagnostics_channel.channel('my-channel'); channel.bindStore(store, (data) => { return { data }; });
channel.unbindStore(store)#
Stability: 1 - Experimental
store<AsyncLocalStorage>The store to unbind from the channel.- Returns:
<boolean>trueif the store was found,falseotherwise.
Remove a message handler previously registered to this channel with channel.bindStore(store).
import diagnostics_channel from 'node:diagnostics_channel'; import { AsyncLocalStorage } from 'node:async_hooks'; const store = new AsyncLocalStorage(); const channel = diagnostics_channel.channel('my-channel'); channel.bindStore(store); channel.unbindStore(store);const diagnostics_channel = require('node:diagnostics_channel'); const { AsyncLocalStorage } = require('node:async_hooks'); const store = new AsyncLocalStorage(); const channel = diagnostics_channel.channel('my-channel'); channel.bindStore(store); channel.unbindStore(store);
channel.runStores(context, fn[, thisArg[, ...args]])#
Stability: 1 - Experimental
context<any>Message to send to subscribers and bind to storesfn<Function>Handler to run within the entered storage contextthisArg<any>The receiver to be used for the function call....args<any>Optional arguments to pass to the function.
Applies the given data to any AsyncLocalStorage instances bound to the channel for the duration of the given function, then publishes to the channel within the scope of that data is applied to the stores.
If a transform function was given to channel.bindStore(store) it will be applied to transform the message data before it becomes the context value for the store. The prior storage context is accessible from within the transform function in cases where context linking is required.
The context applied to the store should be accessible in any async code which continues from execution which began during the given function, however there are some situations in which context loss may occur.
import diagnostics_channel from 'node:diagnostics_channel'; import { AsyncLocalStorage } from 'node:async_hooks'; const store = new AsyncLocalStorage(); const channel = diagnostics_channel.channel('my-channel'); channel.bindStore(store, (message) => { const parent = store.getStore(); return new Span(message, parent); }); channel.runStores({ some: 'message' }, () => { store.getStore(); // Span({ some: 'message' }) });const diagnostics_channel = require('node:diagnostics_channel'); const { AsyncLocalStorage } = require('node:async_hooks'); const store = new AsyncLocalStorage(); const channel = diagnostics_channel.channel('my-channel'); channel.bindStore(store, (message) => { const parent = store.getStore(); return new Span(message, parent); }); channel.runStores({ some: 'message' }, () => { store.getStore(); // Span({ some: 'message' }) });
Class: TracingChannel#
Stability: 1 - Experimental
The class TracingChannel is a collection of TracingChannel Channels which together express a single traceable action. It is used to formalize and simplify the process of producing events for tracing application flow. diagnostics_channel.tracingChannel() is used to construct a TracingChannel. As with Channel it is recommended to create and reuse a single TracingChannel at the top-level of the file rather than creating them dynamically.
tracingChannel.subscribe(subscribers)#
subscribers<Object>Set of TracingChannel Channels subscribersstart<Function>Thestartevent subscriberend<Function>Theendevent subscriberasyncStart<Function>TheasyncStartevent subscriberasyncEnd<Function>TheasyncEndevent subscribererror<Function>Theerrorevent subscriber
Helper to subscribe a collection of functions to the corresponding channels. This is the same as calling channel.subscribe(onMessage) on each channel individually.
import diagnostics_channel from 'node:diagnostics_channel'; const channels = diagnostics_channel.tracingChannel('my-channel'); channels.subscribe({ start(message) { // Handle start message }, end(message) { // Handle end message }, asyncStart(message) { // Handle asyncStart message }, asyncEnd(message) { // Handle asyncEnd message }, error(message) { // Handle error message }, });const diagnostics_channel = require('node:diagnostics_channel'); const channels = diagnostics_channel.tracingChannel('my-channel'); channels.subscribe({ start(message) { // Handle start message }, end(message) { // Handle end message }, asyncStart(message) { // Handle asyncStart message }, asyncEnd(message) { // Handle asyncEnd message }, error(message) { // Handle error message }, });
tracingChannel.unsubscribe(subscribers)#
subscribers<Object>Set of TracingChannel Channels subscribersstart<Function>Thestartevent subscriberend<Function>Theendevent subscriberasyncStart<Function>TheasyncStartevent subscriberasyncEnd<Function>TheasyncEndevent subscribererror<Function>Theerrorevent subscriber
- Returns:
<boolean>trueif all handlers were successfully unsubscribed, andfalseotherwise.
Helper to unsubscribe a collection of functions from the corresponding channels. This is the same as calling channel.unsubscribe(onMessage) on each channel individually.
import diagnostics_channel from 'node:diagnostics_channel'; const channels = diagnostics_channel.tracingChannel('my-channel'); channels.unsubscribe({ start(message) { // Handle start message }, end(message) { // Handle end message }, asyncStart(message) { // Handle asyncStart message }, asyncEnd(message) { // Handle asyncEnd message }, error(message) { // Handle error message }, });const diagnostics_channel = require('node:diagnostics_channel'); const channels = diagnostics_channel.tracingChannel('my-channel'); channels.unsubscribe({ start(message) { // Handle start message }, end(message) { // Handle end message }, asyncStart(message) { // Handle asyncStart message }, asyncEnd(message) { // Handle asyncEnd message }, error(message) { // Handle error message }, });
tracingChannel.traceSync(fn[, context[, thisArg[, ...args]]])#
fn<Function>Function to wrap a trace aroundcontext<Object>Shared object to correlate events throughthisArg<any>The receiver to be used for the function call...args<any>Optional arguments to pass to the function- Returns:
<any>The return value of the given function
Trace a synchronous function call. This will always produce a start event and end event around the execution and may produce an error event if the given function throws an error. This will run the given function using channel.runStores(context, ...) on the start channel which ensures all events should have any bound stores set to match this trace context.
To ensure only correct trace graphs are formed, events will only be published if subscribers are present prior to starting the trace. Subscriptions which are added after the trace begins will not receive future events from that trace, only future traces will be seen.
import diagnostics_channel from 'node:diagnostics_channel'; const channels = diagnostics_channel.tracingChannel('my-channel'); channels.traceSync(() => { // Do something }, { some: 'thing', });const diagnostics_channel = require('node:diagnostics_channel'); const channels = diagnostics_channel.tracingChannel('my-channel'); channels.traceSync(() => { // Do something }, { some: 'thing', });
tracingChannel.tracePromise(fn[, context[, thisArg[, ...args]]])#
fn<Function>Promise-returning function to wrap a trace aroundcontext<Object>Shared object to correlate trace events throughthisArg<any>The receiver to be used for the function call...args<any>Optional arguments to pass to the function- Returns:
<Promise>Chained from promise returned by the given function
Trace a promise-returning function call. This will always produce a start event and end event around the synchronous portion of the function execution, and will produce an asyncStart event and asyncEnd event when a promise continuation is reached. It may also produce an error event if the given function throws an error or the returned promise rejects. This will run the given function using channel.runStores(context, ...) on the start channel which ensures all events should have any bound stores set to match this trace context.
To ensure only correct trace graphs are formed, events will only be published if subscribers are present prior to starting the trace. Subscriptions which are added after the trace begins will not receive future events from that trace, only future traces will be seen.
import diagnostics_channel from 'node:diagnostics_channel'; const channels = diagnostics_channel.tracingChannel('my-channel'); channels.tracePromise(async () => { // Do something }, { some: 'thing', });const diagnostics_channel = require('node:diagnostics_channel'); const channels = diagnostics_channel.tracingChannel('my-channel'); channels.tracePromise(async () => { // Do something }, { some: 'thing', });
tracingChannel.traceCallback(fn[, position[, context[, thisArg[, ...args]]]])#
fn<Function>callback using function to wrap a trace aroundposition<number>Zero-indexed argument position of expected callback (defaults to last argument ifundefinedis passed)context<Object>Shared object to correlate trace events through (defaults to{}ifundefinedis passed)thisArg<any>The receiver to be used for the function call...args<any>arguments to pass to the function (must include the callback)- Returns:
<any>The return value of the given function
Trace a callback-receiving function call. The callback is expected to follow the error as first arg convention typically used. This will always produce a start event and end event around the synchronous portion of the function execution, and will produce a asyncStart event and asyncEnd event around the callback execution. It may also produce an error event if the given function throws or the first argument passed to the callback is set. This will run the given function using channel.runStores(context, ...) on the start channel which ensures all events should have any bound stores set to match this trace context.
To ensure only correct trace graphs are formed, events will only be published if subscribers are present prior to starting the trace. Subscriptions which are added after the trace begins will not receive future events from that trace, only future traces will be seen.
import diagnostics_channel from 'node:diagnostics_channel'; const channels = diagnostics_channel.tracingChannel('my-channel'); channels.traceCallback((arg1, callback) => { // Do something callback(null, 'result'); }, 1, { some: 'thing', }, thisArg, arg1, callback);const diagnostics_channel = require('node:diagnostics_channel'); const channels = diagnostics_channel.tracingChannel('my-channel'); channels.traceCallback((arg1, callback) => { // Do something callback(null, 'result'); }, 1, { some: 'thing', }, thisArg, arg1, callback);
The callback will also be run with channel.runStores(context, ...) which enables context loss recovery in some cases.
import diagnostics_channel from 'node:diagnostics_channel'; import { AsyncLocalStorage } from 'node:async_hooks'; const channels = diagnostics_channel.tracingChannel('my-channel'); const myStore = new AsyncLocalStorage(); // The start channel sets the initial store data to something // and stores that store data value on the trace context object channels.start.bindStore(myStore, (data) => { const span = new Span(data); data.span = span; return span; }); // Then asyncStart can restore from that data it stored previously channels.asyncStart.bindStore(myStore, (data) => { return data.span; });const diagnostics_channel = require('node:diagnostics_channel'); const { AsyncLocalStorage } = require('node:async_hooks'); const channels = diagnostics_channel.tracingChannel('my-channel'); const myStore = new AsyncLocalStorage(); // The start channel sets the initial store data to something // and stores that store data value on the trace context object channels.start.bindStore(myStore, (data) => { const span = new Span(data); data.span = span; return span; }); // Then asyncStart can restore from that data it stored previously channels.asyncStart.bindStore(myStore, (data) => { return data.span; });
tracingChannel.hasSubscribers#
- Returns:
<boolean>trueif any of the individual channels has a subscriber,falseif not.
This is a helper method available on a TracingChannel instance to check if any of the TracingChannel Channels have subscribers. A true is returned if any of them have at least one subscriber, a false is returned otherwise.
import diagnostics_channel from 'node:diagnostics_channel'; const channels = diagnostics_channel.tracingChannel('my-channel'); if (channels.hasSubscribers) { // Do something }const diagnostics_channel = require('node:diagnostics_channel'); const channels = diagnostics_channel.tracingChannel('my-channel'); if (channels.hasSubscribers) { // Do something }
TracingChannel Channels#
A TracingChannel is a collection of several diagnostics_channels representing specific points in the execution lifecycle of a single traceable action. The behavior is split into five diagnostics_channels consisting of start, end, asyncStart, asyncEnd, and error. A single traceable action will share the same event object between all events, this can be helpful for managing correlation through a weakmap.
These event objects will be extended with result or error values when the task "completes". In the case of a synchronous task the result will be the return value and the error will be anything thrown from the function. With callback-based async functions the result will be the second argument of the callback while the error will either be a thrown error visible in the end event or the first callback argument in either of the asyncStart or asyncEnd events.
To ensure only correct trace graphs are formed, events should only be published if subscribers are present prior to starting the trace. Subscriptions which are added after the trace begins should not receive future events from that trace, only future traces will be seen.
Tracing channels should follow a naming pattern of:
tracing:module.class.method:startortracing:module.function:starttracing:module.class.method:endortracing:module.function:endtracing:module.class.method:asyncStartortracing:module.function:asyncStarttracing:module.class.method:asyncEndortracing:module.function:asyncEndtracing:module.class.method:errorortracing:module.function:error
start(event)#
- Name:
tracing:${name}:start
The start event represents the point at which a function is called. At this point the event data may contain function arguments or anything else available at the very start of the execution of the function.
end(event)#
- Name:
tracing:${name}:end
The end event represents the point at which a function call returns a value. In the case of an async function this is when the promise returned not when the function itself makes a return statement internally. At this point, if the traced function was synchronous the result field will be set to the return value of the function. Alternatively, the error field may be present to represent any thrown errors.
It is recommended to listen specifically to the error event to track errors as it may be possible for a traceable action to produce multiple errors. For example, an async task which fails may be started internally before the sync part of the task then throws an error.
asyncStart(event)#
- Name:
tracing:${name}:asyncStart
The asyncStart event represents the callback or continuation of a traceable function being reached. At this point things like callback arguments may be available, or anything else expressing the "result" of the action.
For callbacks-based functions, the first argument of the callback will be assigned to the error field, if not undefined or null, and the second argument will be assigned to the result field.
For promises, the argument to the resolve path will be assigned to result or the argument to the reject path will be assign to error.
It is recommended to listen specifically to the error event to track errors as it may be possible for a traceable action to produce multiple errors. For example, an async task which fails may be started internally before the sync part of the task then throws an error.
asyncEnd(event)#
- Name:
tracing:${name}:asyncEnd
The asyncEnd event represents the callback of an asynchronous function returning. It's not likely event data will change after the asyncStart event, however it may be useful to see the point where the callback completes.
error(event)#
- Name:
tracing:${name}:error
The error event represents any error produced by the traceable function either synchronously or asynchronously. If an error is thrown in the synchronous portion of the traced function the error will be assigned to the error field of the event and the error event will be triggered. If an error is received asynchronously through a callback or promise rejection it will also be assigned to the error field of the event and trigger the error event.
It is possible for a single traceable function call to produce errors multiple times so this should be considered when consuming this event. For example, if another async task is triggered internally which fails and then the sync part of the function then throws and error two error events will be emitted, one for the sync error and one for the async error.
Built-in Channels#
Console#
Stability: 1 - Experimental
Event: 'console.log'#
args<any[]>
Emitted when console.log() is called. Receives and array of the arguments passed to console.log().
Event: 'console.info'#
args<any[]>
Emitted when console.info() is called. Receives and array of the arguments passed to console.info().
Event: 'console.debug'#
args<any[]>
Emitted when console.debug() is called. Receives and array of the arguments passed to console.debug().
Event: 'console.warn'#
args<any[]>
Emitted when console.warn() is called. Receives and array of the arguments passed to console.warn().
Event: 'console.error'#
args<any[]>
Emitted when console.error() is called. Receives and array of the arguments passed to console.error().
HTTP#
Stability: 1 - Experimental
Event: 'http.client.request.created'#
request<http.ClientRequest>
Emitted when client creates a request object. Unlike http.client.request.start, this event is emitted before the request has been sent.
Event: 'http.client.request.start'#
request<http.ClientRequest>
Emitted when client starts a request.
Event: 'http.client.request.error'#
request<http.ClientRequest>error<Error>
Emitted when an error occurs during a client request.
Event: 'http.client.response.finish'#
request<http.ClientRequest>response<http.IncomingMessage>
Emitted when client receives a response.
Event: 'http.server.request.start'#
request<http.IncomingMessage>response<http.ServerResponse>socket<net.Socket>server<http.Server>
Emitted when server receives a request.
Event: 'http.server.response.created'#
request<http.IncomingMessage>response<http.ServerResponse>
Emitted when server creates a response. The event is emitted before the response is sent.
Event: 'http.server.response.finish'#
request<http.IncomingMessage>response<http.ServerResponse>socket<net.Socket>server<http.Server>
Emitted when server sends a response.
HTTP/2#
Stability: 1 - Experimental
Event: 'http2.client.stream.created'#
stream<ClientHttp2Stream>headers<HTTP/2 Headers Object>
Emitted when a stream is created on the client.
Event: 'http2.client.stream.start'#
stream<ClientHttp2Stream>headers<HTTP/2 Headers Object>
Emitted when a stream is started on the client.
Event: 'http2.client.stream.error'#
stream<ClientHttp2Stream>error<Error>
Emitted when an error occurs during the processing of a stream on the client.
Event: 'http2.client.stream.finish'#
stream<ClientHttp2Stream>headers<HTTP/2 Headers Object>flags<number>
Emitted when a stream is received on the client.
Event: 'http2.client.stream.bodyChunkSent'#
stream<ClientHttp2Stream>writev<boolean>data<Buffer>|<string>|<Buffer[]>|<Object[]>encoding<string>
Emitted when a chunk of the client stream body is being sent.
Event: 'http2.client.stream.bodySent'#
stream<ClientHttp2Stream>
Emitted after the client stream body has been fully sent.
Event: 'http2.client.stream.close'#
stream<ClientHttp2Stream>
Emitted when a stream is closed on the client. The HTTP/2 error code used when closing the stream can be retrieved using the stream.rstCode property.
Event: 'http2.server.stream.created'#
stream<ServerHttp2Stream>headers<HTTP/2 Headers Object>
Emitted when a stream is created on the server.
Event: 'http2.server.stream.start'#
stream<ServerHttp2Stream>headers<HTTP/2 Headers Object>
Emitted when a stream is started on the server.
Event: 'http2.server.stream.error'#
stream<ServerHttp2Stream>error<Error>
Emitted when an error occurs during the processing of a stream on the server.
Event: 'http2.server.stream.finish'#
stream<ServerHttp2Stream>headers<HTTP/2 Headers Object>flags<number>
Emitted when a stream is sent on the server.
Event: 'http2.server.stream.close'#
stream<ServerHttp2Stream>
Emitted when a stream is closed on the server. The HTTP/2 error code used when closing the stream can be retrieved using the stream.rstCode property.
Modules#
Stability: 1 - Experimental
Event: 'module.require.start'#
event<Object>containing the following propertiesidArgument passed torequire(). Module name.parentFilenameName of the module that attempted to require(id).
Emitted when require() is executed. See start event.
Event: 'module.require.end'#
event<Object>containing the following propertiesidArgument passed torequire(). Module name.parentFilenameName of the module that attempted to require(id).
Emitted when a require() call returns. See end event.
Event: 'module.require.error'#
event<Object>containing the following propertiesidArgument passed torequire(). Module name.parentFilenameName of the module that attempted to require(id).
error<Error>
Emitted when a require() throws an error. See error event.
Event: 'module.import.asyncStart'#
event<Object>containing the following propertiesidArgument passed toimport(). Module name.parentURLURL object of the module that attempted to import(id).
Emitted when import() is invoked. See asyncStart event.
Event: 'module.import.asyncEnd'#
event<Object>containing the following propertiesidArgument passed toimport(). Module name.parentURLURL object of the module that attempted to import(id).
Emitted when import() has completed. See asyncEnd event.
Event: 'module.import.error'#
event<Object>containing the following propertiesidArgument passed toimport(). Module name.parentURLURL object of the module that attempted to import(id).
error<Error>
Emitted when a import() throws an error. See error event.
NET#
Stability: 1 - Experimental
Event: 'net.client.socket'#
socket<net.Socket>|<tls.TLSSocket>
Emitted when a new TCP or pipe client socket connection is created.
Event: 'net.server.socket'#
socket<net.Socket>
Emitted when a new TCP or pipe connection is received.
Event: 'tracing:net.server.listen:asyncStart'#
server<net.Server>options<Object>
Emitted when net.Server.listen() is invoked, before the port or pipe is actually setup.
Event: 'tracing:net.server.listen:asyncEnd'#
server<net.Server>
Emitted when net.Server.listen() has completed and thus the server is ready to accept connection.
Event: 'tracing:net.server.listen:error'#
server<net.Server>error<Error>
Emitted when net.Server.listen() is returning an error.
UDP#
Stability: 1 - Experimental
Event: 'udp.socket'#
socket<dgram.Socket>
Emitted when a new UDP socket is created.
Process#
Stability: 1 - Experimental
Event: 'child_process'#
process<ChildProcess>
Emitted when a new process is created.
tracing:child_process.spawn:start
process<ChildProcess>options<Object>
Emitted when child_process.spawn() is invoked, before the process is actually spawned.
tracing:child_process.spawn:end
process<ChildProcess>
Emitted when child_process.spawn() has completed successfully and the process has been created.
tracing:child_process.spawn:error
process<ChildProcess>error<Error>
Emitted when child_process.spawn() encounters an error.
Event: 'execve'#
execPath<string>args<string[]>env<string[]>
Emitted when process.execve() is invoked.
Worker Thread#
Stability: 1 - Experimental
Event: 'worker_threads'#
worker<Worker>
Emitted when a new thread is created.
DNS#
Stability: 2 - Stable
The node:dns module enables name resolution. For example, use it to look up IP addresses of host names.
Although named for the Domain Name System (DNS), it does not always use the DNS protocol for lookups. dns.lookup() uses the operating system facilities to perform name resolution. It may not need to perform any network communication. To perform name resolution the way other applications on the same system do, use dns.lookup().
import dns from 'node:dns'; dns.lookup('example.org', (err, address, family) => { console.log('address: %j family: IPv%s', address, family); }); // address: "2606:2800:21f:cb07:6820:80da:af6b:8b2c" family: IPv6const dns = require('node:dns'); dns.lookup('example.org', (err, address, family) => { console.log('address: %j family: IPv%s', address, family); }); // address: "2606:2800:21f:cb07:6820:80da:af6b:8b2c" family: IPv6
All other functions in the node:dns module connect to an actual DNS server to perform name resolution. They will always use the network to perform DNS queries. These functions do not use the same set of configuration files used by dns.lookup() (e.g. /etc/hosts). Use these functions to always perform DNS queries, bypassing other name-resolution facilities.
import dns from 'node:dns'; dns.resolve4('archive.org', (err, addresses) => { if (err) throw err; console.log(`addresses: ${JSON.stringify(addresses)}`); addresses.forEach((a) => { dns.reverse(a, (err, hostnames) => { if (err) { throw err; } console.log(`reverse for ${a}: ${JSON.stringify(hostnames)}`); }); }); });const dns = require('node:dns'); dns.resolve4('archive.org', (err, addresses) => { if (err) throw err; console.log(`addresses: ${JSON.stringify(addresses)}`); addresses.forEach((a) => { dns.reverse(a, (err, hostnames) => { if (err) { throw err; } console.log(`reverse for ${a}: ${JSON.stringify(hostnames)}`); }); }); });
See the Implementation considerations section for more information.
Class: dns.Resolver#
An independent resolver for DNS requests.
Creating a new resolver uses the default server settings. Setting the servers used for a resolver using resolver.setServers() does not affect other resolvers:
import { Resolver } from 'node:dns'; const resolver = new Resolver(); resolver.setServers(['4.4.4.4']); // This request will use the server at 4.4.4.4, independent of global settings. resolver.resolve4('example.org', (err, addresses) => { // ... });const { Resolver } = require('node:dns'); const resolver = new Resolver(); resolver.setServers(['4.4.4.4']); // This request will use the server at 4.4.4.4, independent of global settings. resolver.resolve4('example.org', (err, addresses) => { // ... });
The following methods from the node:dns module are available:
resolver.getServers()resolver.resolve()resolver.resolve4()resolver.resolve6()resolver.resolveAny()resolver.resolveCaa()resolver.resolveCname()resolver.resolveMx()resolver.resolveNaptr()resolver.resolveNs()resolver.resolvePtr()resolver.resolveSoa()resolver.resolveSrv()resolver.resolveTlsa()resolver.resolveTxt()resolver.reverse()resolver.setServers()
Resolver([options])#
Create a new resolver.
resolver.cancel()#
Cancel all outstanding DNS queries made by this resolver. The corresponding callbacks will be called with an error with code ECANCELLED.
resolver.setLocalAddress([ipv4][, ipv6])#
ipv4<string>A string representation of an IPv4 address. Default:'0.0.0.0'ipv6<string>A string representation of an IPv6 address. Default:'::0'
The resolver instance will send its requests from the specified IP address. This allows programs to specify outbound interfaces when used on multi-homed systems.
If a v4 or v6 address is not specified, it is set to the default and the operating system will choose a local address automatically.
The resolver will use the v4 local address when making requests to IPv4 DNS servers, and the v6 local address when making requests to IPv6 DNS servers. The rrtype of resolution requests has no impact on the local address used.
dns.getServers()#
- Returns:
<string[]>
Returns an array of IP address strings, formatted according to RFC 5952, that are currently configured for DNS resolution. A string will include a port section if a custom port is used.
[
'8.8.8.8',
'2001:4860:4860::8888',
'8.8.8.8:1053',
'[2001:4860:4860::8888]:1053',
]
dns.lookup(hostname[, options], callback)#
hostname<string>options<integer>|<Object>family<integer>|<string>The record family. Must be4,6, or0. For backward compatibility reasons,'IPv4'and'IPv6'are interpreted as4and6respectively. The value0indicates that either an IPv4 or IPv6 address is returned. If the value0is used with{ all: true }(see below), either one of or both IPv4 and IPv6 addresses are returned, depending on the system's DNS resolver. Default:0.hints<number>One or more supportedgetaddrinfoflags. Multiple flags may be passed by bitwiseORing their values.all<boolean>Whentrue, the callback returns all resolved addresses in an array. Otherwise, returns a single address. Default:false.order<string>Whenverbatim, the resolved addresses are return unsorted. Whenipv4first, the resolved addresses are sorted by placing IPv4 addresses before IPv6 addresses. Whenipv6first, the resolved addresses are sorted by placing IPv6 addresses before IPv4 addresses. Default:verbatim(addresses are not reordered). Default value is configurable usingdns.setDefaultResultOrder()or--dns-result-order.verbatim<boolean>Whentrue, the callback receives IPv4 and IPv6 addresses in the order the DNS resolver returned them. Whenfalse, IPv4 addresses are placed before IPv6 addresses. This option will be deprecated in favor oforder. When both are specified,orderhas higher precedence. New code should only useorder. Default:true(addresses are not reordered). Default value is configurable usingdns.setDefaultResultOrder()or--dns-result-order.
callback<Function>
Resolves a host name (e.g. 'nodejs.org') into the first found A (IPv4) or AAAA (IPv6) record. All option properties are optional. If options is an integer, then it must be 4 or 6 – if options is not provided, then either IPv4 or IPv6 addresses, or both, are returned if found.
With the all option set to true, the arguments for callback change to (err, addresses), with addresses being an array of objects with the properties address and family.
On error, err is an Error object, where err.code is the error code. Keep in mind that err.code will be set to 'ENOTFOUND' not only when the host name does not exist but also when the lookup fails in other ways such as no available file descriptors.
dns.lookup() does not necessarily have anything to do with the DNS protocol. The implementation uses an operating system facility that can associate names with addresses and vice versa. This implementation can have subtle but important consequences on the behavior of any Node.js program. Please take some time to consult the Implementation considerations section before using dns.lookup().
Example usage:
import dns from 'node:dns'; const options = { family: 6, hints: dns.ADDRCONFIG | dns.V4MAPPED, }; dns.lookup('example.org', options, (err, address, family) => console.log('address: %j family: IPv%s', address, family)); // address: "2606:2800:21f:cb07:6820:80da:af6b:8b2c" family: IPv6 // When options.all is true, the result will be an Array. options.all = true; dns.lookup('example.org', options, (err, addresses) => console.log('addresses: %j', addresses)); // addresses: [{"address":"2606:2800:21f:cb07:6820:80da:af6b:8b2c","family":6}]const dns = require('node:dns'); const options = { family: 6, hints: dns.ADDRCONFIG | dns.V4MAPPED, }; dns.lookup('example.org', options, (err, address, family) => console.log('address: %j family: IPv%s', address, family)); // address: "2606:2800:21f:cb07:6820:80da:af6b:8b2c" family: IPv6 // When options.all is true, the result will be an Array. options.all = true; dns.lookup('example.org', options, (err, addresses) => console.log('addresses: %j', addresses)); // addresses: [{"address":"2606:2800:21f:cb07:6820:80da:af6b:8b2c","family":6}]
If this method is invoked as its util.promisify()ed version, and all is not set to true, it returns a Promise for an Object with address and family properties.
Supported getaddrinfo flags#
The following flags can be passed as hints to dns.lookup().
dns.ADDRCONFIG: Limits returned address types to the types of non-loopback addresses configured on the system. For example, IPv4 addresses are only returned if the current system has at least one IPv4 address configured.dns.V4MAPPED: If the IPv6 family was specified, but no IPv6 addresses were found, then return IPv4 mapped IPv6 addresses. It is not supported on some operating systems (e.g. FreeBSD 10.1).dns.ALL: Ifdns.V4MAPPEDis specified, return resolved IPv6 addresses as well as IPv4 mapped IPv6 addresses.
dns.lookupService(address, port, callback)#
address<string>port<number>callback<Function>
Resolves the given address and port into a host name and service using the operating system's underlying getnameinfo implementation.
If address is not a valid IP address, a TypeError will be thrown. The port will be coerced to a number. If it is not a legal port, a TypeError will be thrown.
On an error, err is an Error object, where err.code is the error code.
import dns from 'node:dns'; dns.lookupService('127.0.0.1', 22, (err, hostname, service) => { console.log(hostname, service); // Prints: localhost ssh });const dns = require('node:dns'); dns.lookupService('127.0.0.1', 22, (err, hostname, service) => { console.log(hostname, service); // Prints: localhost ssh });
If this method is invoked as its util.promisify()ed version, it returns a Promise for an Object with hostname and service properties.
dns.resolve(hostname[, rrtype], callback)#
hostname<string>Host name to resolve.rrtype<string>Resource record type. Default:'A'.callback<Function>err<Error>records<string[]>|<Object[]>|<Object>
Uses the DNS protocol to resolve a host name (e.g. 'nodejs.org') into an array of the resource records. The callback function has arguments (err, records). When successful, records will be an array of resource records. The type and structure of individual results varies based on rrtype:
rrtype | records contains | Result type | Shorthand method |
|---|---|---|---|
'A' | IPv4 addresses (default) | <string> | dns.resolve4() |
'AAAA' | IPv6 addresses | <string> | dns.resolve6() |
'ANY' | any records | <Object> | dns.resolveAny() |
'CAA' | CA authorization records | <Object> | dns.resolveCaa() |
'CNAME' | canonical name records | <string> | dns.resolveCname() |
'MX' | mail exchange records | <Object> | dns.resolveMx() |
'NAPTR' | name authority pointer records | <Object> | dns.resolveNaptr() |
'NS' | name server records | <string> | dns.resolveNs() |
'PTR' | pointer records | <string> | dns.resolvePtr() |
'SOA' | start of authority records | <Object> | dns.resolveSoa() |
'SRV' | service records | <Object> | dns.resolveSrv() |
'TLSA' | certificate associations | <Object> | dns.resolveTlsa() |
'TXT' | text records | <string[]> | dns.resolveTxt() |
On error, err is an Error object, where err.code is one of the DNS error codes.
dns.resolve4(hostname[, options], callback)#
hostname<string>Host name to resolve.options<Object>ttl<boolean>Retrieves the Time-To-Live value (TTL) of each record. Whentrue, the callback receives an array of{ address: '1.2.3.4', ttl: 60 }objects rather than an array of strings, with the TTL expressed in seconds.
callback<Function>err<Error>addresses<string[]>|<Object[]>
Uses the DNS protocol to resolve a IPv4 addresses (A records) for the hostname. The addresses argument passed to the callback function will contain an array of IPv4 addresses (e.g. ['74.125.79.104', '74.125.79.105', '74.125.79.106']).
dns.resolve6(hostname[, options], callback)#
hostname<string>Host name to resolve.options<Object>ttl<boolean>Retrieve the Time-To-Live value (TTL) of each record. Whentrue, the callback receives an array of{ address: '0:1:2:3:4:5:6:7', ttl: 60 }objects rather than an array of strings, with the TTL expressed in seconds.
callback<Function>err<Error>addresses<string[]>|<Object[]>
Uses the DNS protocol to resolve IPv6 addresses (AAAA records) for the hostname. The addresses argument passed to the callback function will contain an array of IPv6 addresses.
dns.resolveAny(hostname, callback)#
hostname<string>callback<Function>err<Error>ret<Object[]>
Uses the DNS protocol to resolve all records (also known as ANY or * query). The ret argument passed to the callback function will be an array containing various types of records. Each object has a property type that indicates the type of the current record. And depending on the type, additional properties will be present on the object:
| Type | Properties |
|---|---|
'A' | address/ttl |
'AAAA' | address/ttl |
'CAA' | Refer to dns.resolveCaa() |
'CNAME' | value |
'MX' | Refer to dns.resolveMx() |
'NAPTR' | Refer to dns.resolveNaptr() |
'NS' | value |
'PTR' | value |
'SOA' | Refer to dns.resolveSoa() |
'SRV' | Refer to dns.resolveSrv() |
'TLSA' | Refer to dns.resolveTlsa() |
'TXT' | This type of record contains an array property called entries which refers to dns.resolveTxt(), e.g. { entries: ['...'], type: 'TXT' } |
Here is an example of the ret object passed to the callback:
[ { type: 'A', address: '127.0.0.1', ttl: 299 },
{ type: 'CNAME', value: 'example.com' },
{ type: 'MX', exchange: 'alt4.aspmx.l.example.com', priority: 50 },
{ type: 'NS', value: 'ns1.example.com' },
{ type: 'TXT', entries: [ 'v=spf1 include:_spf.example.com ~all' ] },
{ type: 'SOA',
nsname: 'ns1.example.com',
hostmaster: 'admin.example.com',
serial: 156696742,
refresh: 900,
retry: 900,
expire: 1800,
minttl: 60 } ]
DNS server operators may choose not to respond to ANY queries. It may be better to call individual methods like dns.resolve4(), dns.resolveMx(), and so on. For more details, see RFC 8482.
dns.resolveCname(hostname, callback)#
hostname<string>callback<Function>err<Error>addresses<string[]>
Uses the DNS protocol to resolve CNAME records for the hostname. The addresses argument passed to the callback function will contain an array of canonical name records available for the hostname (e.g. ['bar.example.com']).
dns.resolveCaa(hostname, callback)#
hostname<string>callback<Function>err<Error>records<Object[]>
Uses the DNS protocol to resolve CAA records for the hostname. The addresses argument passed to the callback function will contain an array of certification authority authorization records available for the hostname (e.g. [{critical: 0, iodef: 'mailto:pki@example.com'}, {critical: 128, issue: 'pki.example.com'}]).
dns.resolveMx(hostname, callback)#
hostname<string>callback<Function>err<Error>addresses<Object[]>
Uses the DNS protocol to resolve mail exchange records (MX records) for the hostname. The addresses argument passed to the callback function will contain an array of objects containing both a priority and exchange property (e.g. [{priority: 10, exchange: 'mx.example.com'}, ...]).
dns.resolveNaptr(hostname, callback)#
hostname<string>callback<Function>err<Error>addresses<Object[]>
Uses the DNS protocol to resolve regular expression-based records (NAPTR records) for the hostname. The addresses argument passed to the callback function will contain an array of objects with the following properties:
flagsserviceregexpreplacementorderpreference
{
flags: 's',
service: 'SIP+D2U',
regexp: '',
replacement: '_sip._udp.example.com',
order: 30,
preference: 100
}
dns.resolveNs(hostname, callback)#
hostname<string>callback<Function>err<Error>addresses<string[]>
Uses the DNS protocol to resolve name server records (NS records) for the hostname. The addresses argument passed to the callback function will contain an array of name server records available for hostname (e.g. ['ns1.example.com', 'ns2.example.com']).
dns.resolvePtr(hostname, callback)#
hostname<string>callback<Function>err<Error>addresses<string[]>
Uses the DNS protocol to resolve pointer records (PTR records) for the hostname. The addresses argument passed to the callback function will be an array of strings containing the reply records.
dns.resolveSoa(hostname, callback)#
hostname<string>callback<Function>
Uses the DNS protocol to resolve a start of authority record (SOA record) for the hostname. The address argument passed to the callback function will be an object with the following properties:
nsnamehostmasterserialrefreshretryexpireminttl
{
nsname: 'ns.example.com',
hostmaster: 'root.example.com',
serial: 2013101809,
refresh: 10000,
retry: 2400,
expire: 604800,
minttl: 3600
}
dns.resolveSrv(hostname, callback)#
hostname<string>callback<Function>err<Error>addresses<Object[]>
Uses the DNS protocol to resolve service records (SRV records) for the hostname. The addresses argument passed to the callback function will be an array of objects with the following properties:
priorityweightportname
{
priority: 10,
weight: 5,
port: 21223,
name: 'service.example.com'
}
dns.resolveTlsa(hostname, callback)#
hostname<string>callback<Function>err<Error>records<Object[]>
Uses the DNS protocol to resolve certificate associations (TLSA records) for the hostname. The records argument passed to the callback function is an array of objects with these properties:
certUsageselectormatchdata
{
certUsage: 3,
selector: 1,
match: 1,
data: [ArrayBuffer]
}
dns.resolveTxt(hostname, callback)#
hostname<string>callback<Function>err<Error>records<string[]>
Uses the DNS protocol to resolve text queries (TXT records) for the hostname. The records argument passed to the callback function is a two-dimensional array of the text records available for hostname (e.g. [ ['v=spf1 ip4:0.0.0.0 ', '~all' ] ]). Each sub-array contains TXT chunks of one record. Depending on the use case, these could be either joined together or treated separately.
dns.reverse(ip, callback)#
ip<string>callback<Function>err<Error>hostnames<string[]>
Performs a reverse DNS query that resolves an IPv4 or IPv6 address to an array of host names.
On error, err is an Error object, where err.code is one of the DNS error codes.
dns.setDefaultResultOrder(order)#
order<string>must be'ipv4first','ipv6first'or'verbatim'.
Set the default value of order in dns.lookup() and dnsPromises.lookup(). The value could be:
ipv4first: sets defaultordertoipv4first.ipv6first: sets defaultordertoipv6first.verbatim: sets defaultordertoverbatim.
The default is verbatim and dns.setDefaultResultOrder() have higher priority than --dns-result-order. When using worker threads, dns.setDefaultResultOrder() from the main thread won't affect the default dns orders in workers.
dns.getDefaultResultOrder()#
Get the default value for order in dns.lookup() and dnsPromises.lookup(). The value could be:
ipv4first: fororderdefaulting toipv4first.ipv6first: fororderdefaulting toipv6first.verbatim: fororderdefaulting toverbatim.
dns.setServers(servers)#
servers<string[]>array of RFC 5952 formatted addresses
Sets the IP address and port of servers to be used when performing DNS resolution. The servers argument is an array of RFC 5952 formatted addresses. If the port is the IANA default DNS port (53) it can be omitted.
dns.setServers([
'8.8.8.8',
'[2001:4860:4860::8888]',
'8.8.8.8:1053',
'[2001:4860:4860::8888]:1053',
]);
An error will be thrown if an invalid address is provided.
The dns.setServers() method must not be called while a DNS query is in progress.
The dns.setServers() method affects only dns.resolve(), dns.resolve*() and dns.reverse() (and specifically not dns.lookup()).
This method works much like resolve.conf. That is, if attempting to resolve with the first server provided results in a NOTFOUND error, the resolve() method will not attempt to resolve with subsequent servers provided. Fallback DNS servers will only be used if the earlier ones time out or result in some other error.
DNS promises API#
The dns.promises API provides an alternative set of asynchronous DNS methods that return Promise objects rather than using callbacks. The API is accessible via require('node:dns').promises or require('node:dns/promises').
Class: dnsPromises.Resolver#
An independent resolver for DNS requests.
Creating a new resolver uses the default server settings. Setting the servers used for a resolver using resolver.setServers() does not affect other resolvers:
import { Resolver } from 'node:dns/promises'; const resolver = new Resolver(); resolver.setServers(['4.4.4.4']); // This request will use the server at 4.4.4.4, independent of global settings. const addresses = await resolver.resolve4('example.org');const { Resolver } = require('node:dns').promises; const resolver = new Resolver(); resolver.setServers(['4.4.4.4']); // This request will use the server at 4.4.4.4, independent of global settings. resolver.resolve4('example.org').then((addresses) => { // ... }); // Alternatively, the same code can be written using async-await style. (async function() { const addresses = await resolver.resolve4('example.org'); })();
The following methods from the dnsPromises API are available:
resolver.getServers()resolver.resolve()resolver.resolve4()resolver.resolve6()resolver.resolveAny()resolver.resolveCaa()resolver.resolveCname()resolver.resolveMx()resolver.resolveNaptr()resolver.resolveNs()resolver.resolvePtr()resolver.resolveSoa()resolver.resolveSrv()resolver.resolveTlsa()resolver.resolveTxt()resolver.reverse()resolver.setServers()
resolver.cancel()#
Cancel all outstanding DNS queries made by this resolver. The corresponding promises will be rejected with an error with the code ECANCELLED.
dnsPromises.getServers()#
- Returns:
<string[]>
Returns an array of IP address strings, formatted according to RFC 5952, that are currently configured for DNS resolution. A string will include a port section if a custom port is used.
[
'8.8.8.8',
'2001:4860:4860::8888',
'8.8.8.8:1053',
'[2001:4860:4860::8888]:1053',
]
dnsPromises.lookup(hostname[, options])#
hostname<string>options<integer>|<Object>family<integer>The record family. Must be4,6, or0. The value0indicates that either an IPv4 or IPv6 address is returned. If the value0is used with{ all: true }(see below), either one of or both IPv4 and IPv6 addresses are returned, depending on the system's DNS resolver. Default:0.hints<number>One or more supportedgetaddrinfoflags. Multiple flags may be passed by bitwiseORing their values.all<boolean>Whentrue, thePromiseis resolved with all addresses in an array. Otherwise, returns a single address. Default:false.order<string>Whenverbatim, thePromiseis resolved with IPv4 and IPv6 addresses in the order the DNS resolver returned them. Whenipv4first, IPv4 addresses are placed before IPv6 addresses. Whenipv6first, IPv6 addresses are placed before IPv4 addresses. Default:verbatim(addresses are not reordered). Default value is configurable usingdns.setDefaultResultOrder()or--dns-result-order. New code should use{ order: 'verbatim' }.verbatim<boolean>Whentrue, thePromiseis resolved with IPv4 and IPv6 addresses in the order the DNS resolver returned them. Whenfalse, IPv4 addresses are placed before IPv6 addresses. This option will be deprecated in favor oforder. When both are specified,orderhas higher precedence. New code should only useorder. Default: currentlyfalse(addresses are reordered) but this is expected to change in the not too distant future. Default value is configurable usingdns.setDefaultResultOrder()or--dns-result-order.
Resolves a host name (e.g. 'nodejs.org') into the first found A (IPv4) or AAAA (IPv6) record. All option properties are optional. If options is an integer, then it must be 4 or 6 – if options is not provided, then either IPv4 or IPv6 addresses, or both, are returned if found.
With the all option set to true, the Promise is resolved with addresses being an array of objects with the properties address and family.
On error, the Promise is rejected with an Error object, where err.code is the error code. Keep in mind that err.code will be set to 'ENOTFOUND' not only when the host name does not exist but also when the lookup fails in other ways such as no available file descriptors.
dnsPromises.lookup() does not necessarily have anything to do with the DNS protocol. The implementation uses an operating system facility that can associate names with addresses and vice versa. This implementation can have subtle but important consequences on the behavior of any Node.js program. Please take some time to consult the Implementation considerations section before using dnsPromises.lookup().
Example usage:
import dns from 'node:dns'; const dnsPromises = dns.promises; const options = { family: 6, hints: dns.ADDRCONFIG | dns.V4MAPPED, }; await dnsPromises.lookup('example.org', options).then((result) => { console.log('address: %j family: IPv%s', result.address, result.family); // address: "2606:2800:21f:cb07:6820:80da:af6b:8b2c" family: IPv6 }); // When options.all is true, the result will be an Array. options.all = true; await dnsPromises.lookup('example.org', options).then((result) => { console.log('addresses: %j', result); // addresses: [{"address":"2606:2800:21f:cb07:6820:80da:af6b:8b2c","family":6}] });const dns = require('node:dns'); const dnsPromises = dns.promises; const options = { family: 6, hints: dns.ADDRCONFIG | dns.V4MAPPED, }; dnsPromises.lookup('example.org', options).then((result) => { console.log('address: %j family: IPv%s', result.address, result.family); // address: "2606:2800:21f:cb07:6820:80da:af6b:8b2c" family: IPv6 }); // When options.all is true, the result will be an Array. options.all = true; dnsPromises.lookup('example.org', options).then((result) => { console.log('addresses: %j', result); // addresses: [{"address":"2606:2800:21f:cb07:6820:80da:af6b:8b2c","family":6}] });
dnsPromises.lookupService(address, port)#
Resolves the given address and port into a host name and service using the operating system's underlying getnameinfo implementation.
If address is not a valid IP address, a TypeError will be thrown. The port will be coerced to a number. If it is not a legal port, a TypeError will be thrown.
On error, the Promise is rejected with an Error object, where err.code is the error code.
import dnsPromises from 'node:dns/promises'; const result = await dnsPromises.lookupService('127.0.0.1', 22); console.log(result.hostname, result.service); // Prints: localhost sshconst dnsPromises = require('node:dns').promises; dnsPromises.lookupService('127.0.0.1', 22).then((result) => { console.log(result.hostname, result.service); // Prints: localhost ssh });
dnsPromises.resolve(hostname[, rrtype])#
Uses the DNS protocol to resolve a host name (e.g. 'nodejs.org') into an array of the resource records. When successful, the Promise is resolved with an array of resource records. The type and structure of individual results vary based on rrtype:
rrtype | records contains | Result type | Shorthand method |
|---|---|---|---|
'A' | IPv4 addresses (default) | <string> | dnsPromises.resolve4() |
'AAAA' | IPv6 addresses | <string> | dnsPromises.resolve6() |
'ANY' | any records | <Object> | dnsPromises.resolveAny() |
'CAA' | CA authorization records | <Object> | dnsPromises.resolveCaa() |
'CNAME' | canonical name records | <string> | dnsPromises.resolveCname() |
'MX' | mail exchange records | <Object> | dnsPromises.resolveMx() |
'NAPTR' | name authority pointer records | <Object> | dnsPromises.resolveNaptr() |
'NS' | name server records | <string> | dnsPromises.resolveNs() |
'PTR' | pointer records | <string> | dnsPromises.resolvePtr() |
'SOA' | start of authority records | <Object> | dnsPromises.resolveSoa() |
'SRV' | service records | <Object> | dnsPromises.resolveSrv() |
'TLSA' | certificate associations | <Object> | dnsPromises.resolveTlsa() |
'TXT' | text records | <string[]> | dnsPromises.resolveTxt() |
On error, the Promise is rejected with an Error object, where err.code is one of the DNS error codes.
dnsPromises.resolve4(hostname[, options])#
hostname<string>Host name to resolve.options<Object>ttl<boolean>Retrieve the Time-To-Live value (TTL) of each record. Whentrue, thePromiseis resolved with an array of{ address: '1.2.3.4', ttl: 60 }objects rather than an array of strings, with the TTL expressed in seconds.
Uses the DNS protocol to resolve IPv4 addresses (A records) for the hostname. On success, the Promise is resolved with an array of IPv4 addresses (e.g. ['74.125.79.104', '74.125.79.105', '74.125.79.106']).
dnsPromises.resolve6(hostname[, options])#
hostname<string>Host name to resolve.options<Object>ttl<boolean>Retrieve the Time-To-Live value (TTL) of each record. Whentrue, thePromiseis resolved with an array of{ address: '0:1:2:3:4:5:6:7', ttl: 60 }objects rather than an array of strings, with the TTL expressed in seconds.
Uses the DNS protocol to resolve IPv6 addresses (AAAA records) for the hostname. On success, the Promise is resolved with an array of IPv6 addresses.
dnsPromises.resolveAny(hostname)#
hostname<string>
Uses the DNS protocol to resolve all records (also known as ANY or * query). On success, the Promise is resolved with an array containing various types of records. Each object has a property type that indicates the type of the current record. And depending on the type, additional properties will be present on the object:
| Type | Properties |
|---|---|
'A' | address/ttl |
'AAAA' | address/ttl |
'CAA' | Refer to dnsPromises.resolveCaa() |
'CNAME' | value |
'MX' | Refer to dnsPromises.resolveMx() |
'NAPTR' | Refer to dnsPromises.resolveNaptr() |
'NS' | value |
'PTR' | value |
'SOA' | Refer to dnsPromises.resolveSoa() |
'SRV' | Refer to dnsPromises.resolveSrv() |
'TLSA' | Refer to dnsPromises.resolveTlsa() |
'TXT' | This type of record contains an array property called entries which refers to dnsPromises.resolveTxt(), e.g. { entries: ['...'], type: 'TXT' } |
Here is an example of the result object:
[ { type: 'A', address: '127.0.0.1', ttl: 299 },
{ type: 'CNAME', value: 'example.com' },
{ type: 'MX', exchange: 'alt4.aspmx.l.example.com', priority: 50 },
{ type: 'NS', value: 'ns1.example.com' },
{ type: 'TXT', entries: [ 'v=spf1 include:_spf.example.com ~all' ] },
{ type: 'SOA',
nsname: 'ns1.example.com',
hostmaster: 'admin.example.com',
serial: 156696742,
refresh: 900,
retry: 900,
expire: 1800,
minttl: 60 } ]
dnsPromises.resolveCaa(hostname)#
hostname<string>
Uses the DNS protocol to resolve CAA records for the hostname. On success, the Promise is resolved with an array of objects containing available certification authority authorization records available for the hostname (e.g. [{critical: 0, iodef: 'mailto:pki@example.com'},{critical: 128, issue: 'pki.example.com'}]).
dnsPromises.resolveCname(hostname)#
hostname<string>
Uses the DNS protocol to resolve CNAME records for the hostname. On success, the Promise is resolved with an array of canonical name records available for the hostname (e.g. ['bar.example.com']).
dnsPromises.resolveMx(hostname)#
hostname<string>
Uses the DNS protocol to resolve mail exchange records (MX records) for the hostname. On success, the Promise is resolved with an array of objects containing both a priority and exchange property (e.g. [{priority: 10, exchange: 'mx.example.com'}, ...]).
dnsPromises.resolveNaptr(hostname)#
hostname<string>
Uses the DNS protocol to resolve regular expression-based records (NAPTR records) for the hostname. On success, the Promise is resolved with an array of objects with the following properties:
flagsserviceregexpreplacementorderpreference
{
flags: 's',
service: 'SIP+D2U',
regexp: '',
replacement: '_sip._udp.example.com',
order: 30,
preference: 100
}
dnsPromises.resolveNs(hostname)#
hostname<string>
Uses the DNS protocol to resolve name server records (NS records) for the hostname. On success, the Promise is resolved with an array of name server records available for hostname (e.g. ['ns1.example.com', 'ns2.example.com']).
dnsPromises.resolvePtr(hostname)#
hostname<string>
Uses the DNS protocol to resolve pointer records (PTR records) for the hostname. On success, the Promise is resolved with an array of strings containing the reply records.
dnsPromises.resolveSoa(hostname)#
hostname<string>
Uses the DNS protocol to resolve a start of authority record (SOA record) for the hostname. On success, the Promise is resolved with an object with the following properties:
nsnamehostmasterserialrefreshretryexpireminttl
{
nsname: 'ns.example.com',
hostmaster: 'root.example.com',
serial: 2013101809,
refresh: 10000,
retry: 2400,
expire: 604800,
minttl: 3600
}
dnsPromises.resolveSrv(hostname)#
hostname<string>
Uses the DNS protocol to resolve service records (SRV records) for the hostname. On success, the Promise is resolved with an array of objects with the following properties:
priorityweightportname
{
priority: 10,
weight: 5,
port: 21223,
name: 'service.example.com'
}
dnsPromises.resolveTlsa(hostname)#
hostname<string>
Uses the DNS protocol to resolve certificate associations (TLSA records) for the hostname. On success, the Promise is resolved with an array of objects with these properties:
certUsageselectormatchdata
{
certUsage: 3,
selector: 1,
match: 1,
data: [ArrayBuffer]
}
dnsPromises.resolveTxt(hostname)#
hostname<string>
Uses the DNS protocol to resolve text queries (TXT records) for the hostname. On success, the Promise is resolved with a two-dimensional array of the text records available for hostname (e.g. [ ['v=spf1 ip4:0.0.0.0 ', '~all' ] ]). Each sub-array contains TXT chunks of one record. Depending on the use case, these could be either joined together or treated separately.
dnsPromises.reverse(ip)#
ip<string>
Performs a reverse DNS query that resolves an IPv4 or IPv6 address to an array of host names.
On error, the Promise is rejected with an Error object, where err.code is one of the DNS error codes.
dnsPromises.setDefaultResultOrder(order)#
order<string>must be'ipv4first','ipv6first'or'verbatim'.
Set the default value of order in dns.lookup() and dnsPromises.lookup(). The value could be:
ipv4first: sets defaultordertoipv4first.ipv6first: sets defaultordertoipv6first.verbatim: sets defaultordertoverbatim.
The default is verbatim and dnsPromises.setDefaultResultOrder() have higher priority than --dns-result-order. When using worker threads, dnsPromises.setDefaultResultOrder() from the main thread won't affect the default dns orders in workers.
dnsPromises.getDefaultResultOrder()#
Get the value of dnsOrder.
dnsPromises.setServers(servers)#
servers<string[]>array of RFC 5952 formatted addresses
Sets the IP address and port of servers to be used when performing DNS resolution. The servers argument is an array of RFC 5952 formatted addresses. If the port is the IANA default DNS port (53) it can be omitted.
dnsPromises.setServers([
'8.8.8.8',
'[2001:4860:4860::8888]',
'8.8.8.8:1053',
'[2001:4860:4860::8888]:1053',
]);
An error will be thrown if an invalid address is provided.
The dnsPromises.setServers() method must not be called while a DNS query is in progress.
This method works much like resolve.conf. That is, if attempting to resolve with the first server provided results in a NOTFOUND error, the resolve() method will not attempt to resolve with subsequent servers provided. Fallback DNS servers will only be used if the earlier ones time out or result in some other error.
Error codes#
Each DNS query can return one of the following error codes:
dns.NODATA: DNS server returned an answer with no data.dns.FORMERR: DNS server claims query was misformatted.dns.SERVFAIL: DNS server returned general failure.dns.NOTFOUND: Domain name not found.dns.NOTIMP: DNS server does not implement the requested operation.dns.REFUSED: DNS server refused query.dns.BADQUERY: Misformatted DNS query.dns.BADNAME: Misformatted host name.dns.BADFAMILY: Unsupported address family.dns.BADRESP: Misformatted DNS reply.dns.CONNREFUSED: Could not contact DNS servers.dns.TIMEOUT: Timeout while contacting DNS servers.dns.EOF: End of file.dns.FILE: Error reading file.dns.NOMEM: Out of memory.dns.DESTRUCTION: Channel is being destroyed.dns.BADSTR: Misformatted string.dns.BADFLAGS: Illegal flags specified.dns.NONAME: Given host name is not numeric.dns.BADHINTS: Illegal hints flags specified.dns.NOTINITIALIZED: c-ares library initialization not yet performed.dns.LOADIPHLPAPI: Error loadingiphlpapi.dll.dns.ADDRGETNETWORKPARAMS: Could not findGetNetworkParamsfunction.dns.CANCELLED: DNS query cancelled.
The dnsPromises API also exports the above error codes, e.g., dnsPromises.NODATA.
Implementation considerations#
Although dns.lookup() and the various dns.resolve*()/dns.reverse() functions have the same goal of associating a network name with a network address (or vice versa), their behavior is quite different. These differences can have subtle but significant consequences on the behavior of Node.js programs.
dns.lookup()#
Under the hood, dns.lookup() uses the same operating system facilities as most other programs. For instance, dns.lookup() will almost always resolve a given name the same way as the ping command. On most POSIX-like operating systems, the behavior of the dns.lookup() function can be modified by changing settings in nsswitch.conf(5) and/or resolv.conf(5), but changing these files will change the behavior of all other programs running on the same operating system.
Though the call to dns.lookup() will be asynchronous from JavaScript's perspective, it is implemented as a synchronous call to getaddrinfo(3) that runs on libuv's threadpool. This can have surprising negative performance implications for some applications, see the UV_THREADPOOL_SIZE documentation for more information.
Various networking APIs will call dns.lookup() internally to resolve host names. If that is an issue, consider resolving the host name to an address using dns.resolve() and using the address instead of a host name. Also, some networking APIs (such as socket.connect() and dgram.createSocket()) allow the default resolver, dns.lookup(), to be replaced.
dns.resolve(), dns.resolve*(), and dns.reverse()#
These functions are implemented quite differently than dns.lookup(). They do not use getaddrinfo(3) and they always perform a DNS query on the network. This network communication is always done asynchronously and does not use libuv's threadpool.
As a result, these functions cannot have the same negative impact on other processing that happens on libuv's threadpool that dns.lookup() can have.
They do not use the same set of configuration files that dns.lookup() uses. For instance, they do not use the configuration from /etc/hosts.
Domain#
Stability: 0 - Deprecated
This module is pending deprecation. Once a replacement API has been finalized, this module will be fully deprecated. Most developers should not have cause to use this module. Users who absolutely must have the functionality that domains provide may rely on it for the time being but should expect to have to migrate to a different solution in the future.
Domains provide a way to handle multiple different IO operations as a single group. If any of the event emitters or callbacks registered to a domain emit an 'error' event, or throw an error, then the domain object will be notified, rather than losing the context of the error in the process.on('uncaughtException') handler, or causing the program to exit immediately with an error code.
Warning: Don't ignore errors!#
Domain error handlers are not a substitute for closing down a process when an error occurs.
By the very nature of how throw works in JavaScript, there is almost never any way to safely "pick up where it left off", without leaking references, or creating some other sort of undefined brittle state.
The safest way to respond to a thrown error is to shut down the process. Of course, in a normal web server, there may be many open connections, and it is not reasonable to abruptly shut those down because an error was triggered by someone else.
The better approach is to send an error response to the request that triggered the error, while letting the others finish in their normal time, and stop listening for new requests in that worker.
In this way, domain usage goes hand-in-hand with the cluster module, since the primary process can fork a new worker when a worker encounters an error. For Node.js programs that scale to multiple machines, the terminating proxy or service registry can take note of the failure, and react accordingly.
For example, this is not a good idea:
// XXX WARNING! BAD IDEA!
const d = require('node:domain').create();
d.on('error', (er) => {
// The error won't crash the process, but what it does is worse!
// Though we've prevented abrupt process restarting, we are leaking
// a lot of resources if this ever happens.
// This is no better than process.on('uncaughtException')!
console.log(`error, but oh well ${er.message}`);
});
d.run(() => {
require('node:http').createServer((req, res) => {
handleRequest(req, res);
}).listen(PORT);
});
By using the context of a domain, and the resilience of separating our program into multiple worker processes, we can react more appropriately, and handle errors with much greater safety.
// Much better!
const cluster = require('node:cluster');
const PORT = +process.env.PORT || 1337;
if (cluster.isPrimary) {
// A more realistic scenario would have more than 2 workers,
// and perhaps not put the primary and worker in the same file.
//
// It is also possible to get a bit fancier about logging, and
// implement whatever custom logic is needed to prevent DoS
// attacks and other bad behavior.
//
// See the options in the cluster documentation.
//
// The important thing is that the primary does very little,
// increasing our resilience to unexpected errors.
cluster.fork();
cluster.fork();
cluster.on('disconnect', (worker) => {
console.error('disconnect!');
cluster.fork();
});
} else {
// the worker
//
// This is where we put our bugs!
const domain = require('node:domain');
// See the cluster documentation for more details about using
// worker processes to serve requests. How it works, caveats, etc.
const server = require('node:http').createServer((req, res) => {
const d = domain.create();
d.on('error', (er) => {
console.error(`error ${er.stack}`);
// We're in dangerous territory!
// By definition, something unexpected occurred,
// which we probably didn't want.
// Anything can happen now! Be very careful!
try {
// Make sure we close down within 30 seconds
const killtimer = setTimeout(() => {
process.exit(1);
}, 30000);
// But don't keep the process open just for that!
killtimer.unref();
// Stop taking new requests.
server.close();
// Let the primary know we're dead. This will trigger a
// 'disconnect' in the cluster primary, and then it will fork
// a new worker.
cluster.worker.disconnect();
// Try to send an error to the request that triggered the problem
res.statusCode = 500;
res.setHeader('content-type', 'text/plain');
res.end('Oops, there was a problem!\n');
} catch (er2) {
// Oh well, not much we can do at this point.
console.error(`Error sending 500! ${er2.stack}`);
}
});
// Because req and res were created before this domain existed,
// we need to explicitly add them.
// See the explanation of implicit vs explicit binding below.
d.add(req);
d.add(res);
// Now run the handler function in the domain.
d.run(() => {
handleRequest(req, res);
});
});
server.listen(PORT);
}
// This part is not important. Just an example routing thing.
// Put fancy application logic here.
function handleRequest(req, res) {
switch (req.url) {
case '/error':
// We do some async stuff, and then...
setTimeout(() => {
// Whoops!
flerb.bark();
}, timeout);
break;
default:
res.end('ok');
}
}
Additions to Error objects#
Any time an Error object is routed through a domain, a few extra fields are added to it.
error.domainThe domain that first handled the error.error.domainEmitterThe event emitter that emitted an'error'event with the error object.error.domainBoundThe callback function which was bound to the domain, and passed an error as its first argument.error.domainThrownA boolean indicating whether the error was thrown, emitted, or passed to a bound callback function.
Implicit binding#
If domains are in use, then all new EventEmitter objects (including Stream objects, requests, responses, etc.) will be implicitly bound to the active domain at the time of their creation.
Additionally, callbacks passed to low-level event loop requests (such as to fs.open(), or other callback-taking methods) will automatically be bound to the active domain. If they throw, then the domain will catch the error.
In order to prevent excessive memory usage, Domain objects themselves are not implicitly added as children of the active domain. If they were, then it would be too easy to prevent request and response objects from being properly garbage collected.
To nest Domain objects as children of a parent Domain they must be explicitly added.
Implicit binding routes thrown errors and 'error' events to the Domain's 'error' event, but does not register the EventEmitter on the Domain. Implicit binding only takes care of thrown errors and 'error' events.
Explicit binding#
Sometimes, the domain in use is not the one that ought to be used for a specific event emitter. Or, the event emitter could have been created in the context of one domain, but ought to instead be bound to some other domain.
For example, there could be one domain in use for an HTTP server, but perhaps we would like to have a separate domain to use for each request.
That is possible via explicit binding.
// Create a top-level domain for the server
const domain = require('node:domain');
const http = require('node:http');
const serverDomain = domain.create();
serverDomain.run(() => {
// Server is created in the scope of serverDomain
http.createServer((req, res) => {
// Req and res are also created in the scope of serverDomain
// however, we'd prefer to have a separate domain for each request.
// create it first thing, and add req and res to it.
const reqd = domain.create();
reqd.add(req);
reqd.add(res);
reqd.on('error', (er) => {
console.error('Error', er, req.url);
try {
res.writeHead(500);
res.end('Error occurred, sorry.');
} catch (er2) {
console.error('Error sending 500', er2, req.url);
}
});
}).listen(1337);
});
domain.create()#
- Returns:
<Domain>
Class: Domain#
- Extends:
<EventEmitter>
The Domain class encapsulates the functionality of routing errors and uncaught exceptions to the active Domain object.
To handle the errors that it catches, listen to its 'error' event.
domain.members#
- Type:
<Array>
An array of event emitters that have been explicitly added to the domain.
domain.add(emitter)#
emitter<EventEmitter>emitter to be added to the domain
Explicitly adds an emitter to the domain. If any event handlers called by the emitter throw an error, or if the emitter emits an 'error' event, it will be routed to the domain's 'error' event, just like with implicit binding.
If the EventEmitter was already bound to a domain, it is removed from that one, and bound to this one instead.
domain.bind(callback)#
callback<Function>The callback function- Returns:
<Function>The bound function
The returned function will be a wrapper around the supplied callback function. When the returned function is called, any errors that are thrown will be routed to the domain's 'error' event.
const d = domain.create();
function readSomeFile(filename, cb) {
fs.readFile(filename, 'utf8', d.bind((er, data) => {
// If this throws, it will also be passed to the domain.
return cb(er, data ? JSON.parse(data) : null);
}));
}
d.on('error', (er) => {
// An error occurred somewhere. If we throw it now, it will crash the program
// with the normal line number and stack message.
});
domain.enter()#
The enter() method is plumbing used by the run(), bind(), and intercept() methods to set the active domain. It sets domain.active and process.domain to the domain, and implicitly pushes the domain onto the domain stack managed by the domain module (see domain.exit() for details on the domain stack). The call to enter() delimits the beginning of a chain of asynchronous calls and I/O operations bound to a domain.
Calling enter() changes only the active domain, and does not alter the domain itself. enter() and exit() can be called an arbitrary number of times on a single domain.
domain.exit()#
The exit() method exits the current domain, popping it off the domain stack. Any time execution is going to switch to the context of a different chain of asynchronous calls, it's important to ensure that the current domain is exited. The call to exit() delimits either the end of or an interruption to the chain of asynchronous calls and I/O operations bound to a domain.
If there are multiple, nested domains bound to the current execution context, exit() will exit any domains nested within this domain.
Calling exit() changes only the active domain, and does not alter the domain itself. enter() and exit() can be called an arbitrary number of times on a single domain.
domain.intercept(callback)#
callback<Function>The callback function- Returns:
<Function>The intercepted function
This method is almost identical to domain.bind(callback). However, in addition to catching thrown errors, it will also intercept Error objects sent as the first argument to the function.
In this way, the common if (err) return callback(err); pattern can be replaced with a single error handler in a single place.
const d = domain.create();
function readSomeFile(filename, cb) {
fs.readFile(filename, 'utf8', d.intercept((data) => {
// Note, the first argument is never passed to the
// callback since it is assumed to be the 'Error' argument
// and thus intercepted by the domain.
// If this throws, it will also be passed to the domain
// so the error-handling logic can be moved to the 'error'
// event on the domain instead of being repeated throughout
// the program.
return cb(null, JSON.parse(data));
}));
}
d.on('error', (er) => {
// An error occurred somewhere. If we throw it now, it will crash the program
// with the normal line number and stack message.
});
domain.remove(emitter)#
emitter<EventEmitter>emitter to be removed from the domain
The opposite of domain.add(emitter). Removes domain handling from the specified emitter.
domain.run(fn[, ...args])#
fn<Function>...args<any>
Run the supplied function in the context of the domain, implicitly binding all event emitters, timers, and low-level requests that are created in that context. Optionally, arguments can be passed to the function.
This is the most basic way to use a domain.
const domain = require('node:domain');
const fs = require('node:fs');
const d = domain.create();
d.on('error', (er) => {
console.error('Caught error!', er);
});
d.run(() => {
process.nextTick(() => {
setTimeout(() => { // Simulating some various async stuff
fs.open('non-existent file', 'r', (er, fd) => {
if (er) throw er;
// proceed...
});
}, 100);
});
});
In this example, the d.on('error') handler will be triggered, rather than crashing the program.
Domains and promises#
As of Node.js 8.0.0, the handlers of promises are run inside the domain in which the call to .then() or .catch() itself was made:
const d1 = domain.create();
const d2 = domain.create();
let p;
d1.run(() => {
p = Promise.resolve(42);
});
d2.run(() => {
p.then((v) => {
// running in d2
});
});
A callback may be bound to a specific domain using domain.bind(callback):
const d1 = domain.create();
const d2 = domain.create();
let p;
d1.run(() => {
p = Promise.resolve(42);
});
d2.run(() => {
p.then(p.domain.bind((v) => {
// running in d1
}));
});
Domains will not interfere with the error handling mechanisms for promises. In other words, no 'error' event will be emitted for unhandled Promise rejections.
Environment Variables#
Environment variables are variables associated to the environment the Node.js process runs in.
CLI Environment Variables#
There is a set of environment variables that can be defined to customize the behavior of Node.js, for more details refer to the CLI Environment Variables documentation.
process.env#
The basic API for interacting with environment variables is process.env, it consists of an object with pre-populated user environment variables that can be modified and expanded.
For more details refer to the process.env documentation.
DotEnv#
Stability: 2 - Stable
Set of utilities for dealing with additional environment variables defined in .env files.
.env files#
.env files (also known as dotenv files) are files that define environment variables, which Node.js applications can then interact with (popularized by the dotenv package).
The following is an example of the content of a basic .env file:
MY_VAR_A = "my variable A"
MY_VAR_B = "my variable B"
This type of file is used in various different programming languages and platforms but there is no formal specification for it, therefore Node.js defines its own specification described below.
A .env file is a file that contains key-value pairs, each pair is represented by a variable name followed by the equal sign (=) followed by a variable value.
The name of such files is usually .env or it starts with .env (like for example .env.dev where dev indicates a specific target environment). This is the recommended naming scheme but it is not mandatory and dotenv files can have any arbitrary file name.
Variable Names#
A valid variable name must contain only letters (uppercase or lowercase), digits and underscores (_) and it can't begin with a digit.
More specifically a valid variable name must match the following regular expression:
^[a-zA-Z_]+[a-zA-Z0-9_]*$
The recommended convention is to use capital letters with underscores and digits when necessary, but any variable name respecting the above definition will work just fine.
For example, the following are some valid variable names: MY_VAR, MY_VAR_1, my_var, my_var_1, myVar, My_Var123, while these are instead not valid: 1_VAR, 'my-var', "my var", VAR_#1.
Variable Values#
Variable values are comprised by any arbitrary text, which can optionally be wrapped inside single (') or double (") quotes.
Quoted variables can span across multiple lines, while non quoted ones are restricted to a single line.
Noting that when parsed by Node.js all values are interpreted as text, meaning that any value will result in a JavaScript string inside Node.js. For example the following values: 0, true and { "hello": "world" } will result in the literal strings '0', 'true' and '{ "hello": "world" }' instead of the number zero, the boolean true and an object with the hello property respectively.
Examples of valid variables:
MY_SIMPLE_VAR = a simple single line variable
MY_EQUALS_VAR = "this variable contains an = sign!"
MY_HASH_VAR = 'this variable contains a # symbol!'
MY_MULTILINE_VAR = '
this is a multiline variable containing
two separate lines\nSorry, I meant three lines'
Spacing#
Leading and trailing whitespace characters around variable keys and values are ignored unless they are enclosed within quotes.
For example:
MY_VAR_A = my variable a
MY_VAR_B = ' my variable b '
will be treated identically to:
MY_VAR_A = my variable a
MY_VAR_B = ' my variable b '
Comments#
Hash-tag (#) characters denote the beginning of a comment, meaning that the rest of the line will be completely ignored.
Hash-tags found within quotes are however treated as any other standard character.
For example:
# This is a comment
MY_VAR = my variable # This is also a comment
MY_VAR_A = "# this is NOT a comment"
export prefixes#
The export keyword can optionally be added in front of variable declarations, such keyword will be completely ignored by all processing done on the file.
This is useful so that the file can be sourced, without modifications, in shell terminals.
Example:
export MY_VAR = my variable
CLI Options#
.env files can be used to populate the process.env object via one the following CLI options:
Programmatic APIs#
There following two functions allow you to directly interact with .env files:
process.loadEnvFileloads an.envfile and populatesprocess.envwith its variablesutil.parseEnvparses the row content of an.envfile and returns its value in an object
Errors#
Applications running in Node.js will generally experience the following categories of errors:
- Standard JavaScript errors such as
<EvalError>,<SyntaxError>,<RangeError>,<ReferenceError>,<TypeError>, and<URIError>. - Standard
DOMExceptions. - System errors triggered by underlying operating system constraints such as attempting to open a file that does not exist or attempting to send data over a closed socket.
AssertionErrors are a special class of error that can be triggered when Node.js detects an exceptional logic violation that should never occur. These are raised typically by thenode:assertmodule.- User-specified errors triggered by application code.
All JavaScript and system errors raised by Node.js inherit from, or are instances of, the standard JavaScript <Error> class and are guaranteed to provide at least the properties available on that class.
The error.message property of errors raised by Node.js may be changed in any versions. Use error.code to identify an error instead. For a DOMException, use domException.name to identify its type.
Error propagation and interception#
Node.js supports several mechanisms for propagating and handling errors that occur while an application is running. How these errors are reported and handled depends entirely on the type of Error and the style of the API that is called.
All JavaScript errors are handled as exceptions that immediately generate and throw an error using the standard JavaScript throw mechanism. These are handled using the try…catch construct provided by the JavaScript language.
// Throws with a ReferenceError because z is not defined.
try {
const m = 1;
const n = m + z;
} catch (err) {
// Handle the error here.
}
Any use of the JavaScript throw mechanism will raise an exception that must be handled or the Node.js process will exit immediately.
With few exceptions, Synchronous APIs (any blocking method that does not return a <Promise> nor accept a callback function, such as fs.readFileSync), will use throw to report errors.
Errors that occur within Asynchronous APIs may be reported in multiple ways:
Some asynchronous methods returns a
<Promise>, you should always take into account that it might be rejected. See--unhandled-rejectionsflag for how the process will react to an unhandled promise rejection.const fs = require('node:fs/promises'); (async () => { let data; try { data = await fs.readFile('a file that does not exist'); } catch (err) { console.error('There was an error reading the file!', err); return; } // Otherwise handle the data })();Most asynchronous methods that accept a
callbackfunction will accept anErrorobject passed as the first argument to that function. If that first argument is notnulland is an instance ofError, then an error occurred that should be handled.const fs = require('node:fs'); fs.readFile('a file that does not exist', (err, data) => { if (err) { console.error('There was an error reading the file!', err); return; } // Otherwise handle the data });When an asynchronous method is called on an object that is an
EventEmitter, errors can be routed to that object's'error'event.const net = require('node:net'); const connection = net.connect('localhost'); // Adding an 'error' event handler to a stream: connection.on('error', (err) => { // If the connection is reset by the server, or if it can't // connect at all, or on any sort of error encountered by // the connection, the error will be sent here. console.error(err); }); connection.pipe(process.stdout);A handful of typically asynchronous methods in the Node.js API may still use the
throwmechanism to raise exceptions that must be handled usingtry…catch. There is no comprehensive list of such methods; please refer to the documentation of each method to determine the appropriate error handling mechanism required.
The use of the 'error' event mechanism is most common for stream-based and event emitter-based APIs, which themselves represent a series of asynchronous operations over time (as opposed to a single operation that may pass or fail).
For all EventEmitter objects, if an 'error' event handler is not provided, the error will be thrown, causing the Node.js process to report an uncaught exception and crash unless either: a handler has been registered for the 'uncaughtException' event, or the deprecated node:domain module is used.
const EventEmitter = require('node:events');
const ee = new EventEmitter();
setImmediate(() => {
// This will crash the process because no 'error' event
// handler has been added.
ee.emit('error', new Error('This will crash'));
});
Errors generated in this way cannot be intercepted using try…catch as they are thrown after the calling code has already exited.
Developers must refer to the documentation for each method to determine exactly how errors raised by those methods are propagated.
Class: Error#
A generic JavaScript <Error> object that does not denote any specific circumstance of why the error occurred. Error objects capture a "stack trace" detailing the point in the code at which the Error was instantiated, and may provide a text description of the error.
All errors generated by Node.js, including all system and JavaScript errors, will either be instances of, or inherit from, the Error class.
new Error(message[, options])#
Creates a new Error object and sets the error.message property to the provided text message. If an object is passed as message, the text message is generated by calling String(message). If the cause option is provided, it is assigned to the error.cause property. The error.stack property will represent the point in the code at which new Error() was called. Stack traces are dependent on V8's stack trace API. Stack traces extend only to either (a) the beginning of synchronous code execution, or (b) the number of frames given by the property Error.stackTraceLimit, whichever is smaller.
Error.captureStackTrace(targetObject[, constructorOpt])#
targetObject<Object>constructorOpt<Function>
Creates a .stack property on targetObject, which when accessed returns a string representing the location in the code at which Error.captureStackTrace() was called.
const myObject = {};
Error.captureStackTrace(myObject);
myObject.stack; // Similar to `new Error().stack`
The first line of the trace will be prefixed with ${myObject.name}: ${myObject.message}.
The optional constructorOpt argument accepts a function. If given, all frames above constructorOpt, including constructorOpt, will be omitted from the generated stack trace.
The constructorOpt argument is useful for hiding implementation details of error generation from the user. For instance:
function a() {
b();
}
function b() {
c();
}
function c() {
// Create an error without stack trace to avoid calculating the stack trace twice.
const { stackTraceLimit } = Error;
Error.stackTraceLimit = 0;
const error = new Error();
Error.stackTraceLimit = stackTraceLimit;
// Capture the stack trace above function b
Error.captureStackTrace(error, b); // Neither function c, nor b is included in the stack trace
throw error;
}
a();
Error.stackTraceLimit#
- Type:
<number>
The Error.stackTraceLimit property specifies the number of stack frames collected by a stack trace (whether generated by new Error().stack or Error.captureStackTrace(obj)).
The default value is 10 but may be set to any valid JavaScript number. Changes will affect any stack trace captured after the value has been changed.
If set to a non-number value, or set to a negative number, stack traces will not capture any frames.
error.cause#
- Type:
<any>
If present, the error.cause property is the underlying cause of the Error. It is used when catching an error and throwing a new one with a different message or code in order to still have access to the original error.
The error.cause property is typically set by calling new Error(message, { cause }). It is not set by the constructor if the cause option is not provided.
This property allows errors to be chained. When serializing Error objects, util.inspect() recursively serializes error.cause if it is set.
const cause = new Error('The remote HTTP server responded with a 500 status');
const symptom = new Error('The message failed to send', { cause });
console.log(symptom);
// Prints:
// Error: The message failed to send
// at REPL2:1:17
// at Script.runInThisContext (node:vm:130:12)
// ... 7 lines matching cause stack trace ...
// at [_line] [as _line] (node:internal/readline/interface:886:18) {
// [cause]: Error: The remote HTTP server responded with a 500 status
// at REPL1:1:15
// at Script.runInThisContext (node:vm:130:12)
// at REPLServer.defaultEval (node:repl:574:29)
// at bound (node:domain:426:15)
// at REPLServer.runBound [as eval] (node:domain:437:12)
// at REPLServer.onLine (node:repl:902:10)
// at REPLServer.emit (node:events:549:35)
// at REPLServer.emit (node:domain:482:12)
// at [_onLine] [as _onLine] (node:internal/readline/interface:425:12)
// at [_line] [as _line] (node:internal/readline/interface:886:18)
error.code#
- Type:
<string>
The error.code property is a string label that identifies the kind of error. error.code is the most stable way to identify an error. It will only change between major versions of Node.js. In contrast, error.message strings may change between any versions of Node.js. See Node.js error codes for details about specific codes.
error.message#
- Type:
<string>
The error.message property is the string description of the error as set by calling new Error(message). The message passed to the constructor will also appear in the first line of the stack trace of the Error, however changing this property after the Error object is created may not change the first line of the stack trace (for example, when error.stack is read before this property is changed).
const err = new Error('The message');
console.error(err.message);
// Prints: The message
error.stack#
- Type:
<string>
The error.stack property is a string describing the point in the code at which the Error was instantiated.
Error: Things keep happening!
at /home/gbusey/file.js:525:2
at Frobnicator.refrobulate (/home/gbusey/business-logic.js:424:21)
at Actor.<anonymous> (/home/gbusey/actors.js:400:8)
at increaseSynergy (/home/gbusey/actors.js:701:6)
The first line is formatted as <error class name>: <error message>, and is followed by a series of stack frames (each line beginning with "at "). Each frame describes a call site within the code that lead to the error being generated. V8 attempts to display a name for each function (by variable name, function name, or object method name), but occasionally it will not be able to find a suitable name. If V8 cannot determine a name for the function, only location information will be displayed for that frame. Otherwise, the determined function name will be displayed with location information appended in parentheses.
Frames are only generated for JavaScript functions. If, for example, execution synchronously passes through a C++ addon function called cheetahify which itself calls a JavaScript function, the frame representing the cheetahify call will not be present in the stack traces:
const cheetahify = require('./native-binding.node');
function makeFaster() {
// `cheetahify()` *synchronously* calls speedy.
cheetahify(function speedy() {
throw new Error('oh no!');
});
}
makeFaster();
// will throw:
// /home/gbusey/file.js:6
// throw new Error('oh no!');
// ^
// Error: oh no!
// at speedy (/home/gbusey/file.js:6:11)
// at makeFaster (/home/gbusey/file.js:5:3)
// at Object.<anonymous> (/home/gbusey/file.js:10:1)
// at Module._compile (module.js:456:26)
// at Object.Module._extensions..js (module.js:474:10)
// at Module.load (module.js:356:32)
// at Function.Module._load (module.js:312:12)
// at Function.Module.runMain (module.js:497:10)
// at startup (node.js:119:16)
// at node.js:906:3
The location information will be one of:
native, if the frame represents a call internal to V8 (as in[].forEach).plain-filename.js:line:column, if the frame represents a call internal to Node.js./absolute/path/to/file.js:line:column, if the frame represents a call in a user program (using CommonJS module system), or its dependencies.<transport-protocol>:///url/to/module/file.mjs:line:column, if the frame represents a call in a user program (using ES module system), or its dependencies.
The number of frames captured by the stack trace is bounded by the smaller of Error.stackTraceLimit or the number of available frames on the current event loop tick.
error.stack is a getter/setter for a hidden internal property which is only present on builtin Error objects (those for which Error.isError returns true). If error is not a builtin error object, then the error.stack getter will always return undefined, and the setter will do nothing. This can occur if the accessor is manually invoked with a this value that is not a builtin error object, such as a <Proxy>.
Class: AssertionError#
- Extends:
<errors.Error>
Indicates the failure of an assertion. For details, see Class: assert.AssertionError.
Class: RangeError#
- Extends:
<errors.Error>
Indicates that a provided argument was not within the set or range of acceptable values for a function; whether that is a numeric range, or outside the set of options for a given function parameter.
require('node:net').connect(-1);
// Throws "RangeError: "port" option should be >= 0 and < 65536: -1"
Node.js will generate and throw RangeError instances immediately as a form of argument validation.
Class: ReferenceError#
- Extends:
<errors.Error>
Indicates that an attempt is being made to access a variable that is not defined. Such errors commonly indicate typos in code, or an otherwise broken program.
While client code may generate and propagate these errors, in practice, only V8 will do so.
doesNotExist;
// Throws ReferenceError, doesNotExist is not a variable in this program.
Unless an application is dynamically generating and running code, ReferenceError instances indicate a bug in the code or its dependencies.
Class: SyntaxError#
- Extends:
<errors.Error>
Indicates that a program is not valid JavaScript. These errors may only be generated and propagated as a result of code evaluation. Code evaluation may happen as a result of eval, Function, require, or vm. These errors are almost always indicative of a broken program.
try {
require('node:vm').runInThisContext('binary ! isNotOk');
} catch (err) {
// 'err' will be a SyntaxError.
}
SyntaxError instances are unrecoverable in the context that created them – they may only be caught by other contexts.
Class: SystemError#
- Extends:
<errors.Error>
Node.js generates system errors when exceptions occur within its runtime environment. These usually occur when an application violates an operating system constraint. For example, a system error will occur if an application attempts to read a file that does not exist.
address<string>If present, the address to which a network connection failedcode<string>The string error codedest<string>If present, the file path destination when reporting a file system errorerrno<number>The system-provided error numberinfo<Object>If present, extra details about the error conditionmessage<string>A system-provided human-readable description of the errorpath<string>If present, the file path when reporting a file system errorport<number>If present, the network connection port that is not availablesyscall<string>The name of the system call that triggered the error
error.address#
- Type:
<string>
If present, error.address is a string describing the address to which a network connection failed.
error.code#
- Type:
<string>
The error.code property is a string representing the error code.
error.dest#
- Type:
<string>
If present, error.dest is the file path destination when reporting a file system error.
error.errno#
- Type:
<number>
The error.errno property is a negative number which corresponds to the error code defined in libuv Error handling.
On Windows the error number provided by the system will be normalized by libuv.
To get the string representation of the error code, use util.getSystemErrorName(error.errno).
error.info#
- Type:
<Object>
If present, error.info is an object with details about the error condition.
error.message#
- Type:
<string>
error.message is a system-provided human-readable description of the error.
error.path#
- Type:
<string>
If present, error.path is a string containing a relevant invalid pathname.
error.port#
- Type:
<number>
If present, error.port is the network connection port that is not available.
error.syscall#
- Type:
<string>
The error.syscall property is a string describing the syscall that failed.
Common system errors#
This is a list of system errors commonly-encountered when writing a Node.js program. For a comprehensive list, see the errno(3) man page.
EACCES(Permission denied): An attempt was made to access a file in a way forbidden by its file access permissions.EADDRINUSE(Address already in use): An attempt to bind a server (net,http, orhttps) to a local address failed due to another server on the local system already occupying that address.ECONNREFUSED(Connection refused): No connection could be made because the target machine actively refused it. This usually results from trying to connect to a service that is inactive on the foreign host.ECONNRESET(Connection reset by peer): A connection was forcibly closed by a peer. This normally results from a loss of the connection on the remote socket due to a timeout or reboot. Commonly encountered via thehttpandnetmodules.EEXIST(File exists): An existing file was the target of an operation that required that the target not exist.EISDIR(Is a directory): An operation expected a file, but the given pathname was a directory.EMFILE(Too many open files in system): Maximum number of file descriptors allowable on the system has been reached, and requests for another descriptor cannot be fulfilled until at least one has been closed. This is encountered when opening many files at once in parallel, especially on systems (in particular, macOS) where there is a low file descriptor limit for processes. To remedy a low limit, runulimit -n 2048in the same shell that will run the Node.js process.ENOENT(No such file or directory): Commonly raised byfsoperations to indicate that a component of the specified pathname does not exist. No entity (file or directory) could be found by the given path.ENOTDIR(Not a directory): A component of the given pathname existed, but was not a directory as expected. Commonly raised byfs.readdir.ENOTEMPTY(Directory not empty): A directory with entries was the target of an operation that requires an empty directory, usuallyfs.unlink.ENOTFOUND(DNS lookup failed): Indicates a DNS failure of eitherEAI_NODATAorEAI_NONAME. This is not a standard POSIX error.EPERM(Operation not permitted): An attempt was made to perform an operation that requires elevated privileges.EPIPE(Broken pipe): A write on a pipe, socket, or FIFO for which there is no process to read the data. Commonly encountered at thenetandhttplayers, indicative that the remote side of the stream being written to has been closed.ETIMEDOUT(Operation timed out): A connect or send request failed because the connected party did not properly respond after a period of time. Usually encountered byhttpornet. Often a sign that asocket.end()was not properly called.
Class: TypeError#
- Extends
<errors.Error>
Indicates that a provided argument is not an allowable type. For example, passing a function to a parameter which expects a string would be a TypeError.
require('node:url').parse(() => { });
// Throws TypeError, since it expected a string.
Node.js will generate and throw TypeError instances immediately as a form of argument validation.
Exceptions vs. errors#
A JavaScript exception is a value that is thrown as a result of an invalid operation or as the target of a throw statement. While it is not required that these values are instances of Error or classes which inherit from Error, all exceptions thrown by Node.js or the JavaScript runtime will be instances of Error.
Some exceptions are unrecoverable at the JavaScript layer. Such exceptions will always cause the Node.js process to crash. Examples include assert() checks or abort() calls in the C++ layer.
OpenSSL errors#
Errors originating in crypto or tls are of class Error, and in addition to the standard .code and .message properties, may have some additional OpenSSL-specific properties.
error.opensslErrorStack#
An array of errors that can give context to where in the OpenSSL library an error originates from.
error.function#
The OpenSSL function the error originates in.
error.library#
The OpenSSL library the error originates in.
error.reason#
A human-readable string describing the reason for the error.
Node.js error codes#
ABORT_ERR#
Used when an operation has been aborted (typically using an AbortController).
APIs not using AbortSignals typically do not raise an error with this code.
This code does not use the regular ERR_* convention Node.js errors use in order to be compatible with the web platform's AbortError.
ERR_ACCESS_DENIED#
A special type of error that is triggered whenever Node.js tries to get access to a resource restricted by the Permission Model.
ERR_AMBIGUOUS_ARGUMENT#
A function argument is being used in a way that suggests that the function signature may be misunderstood. This is thrown by the node:assert module when the message parameter in assert.throws(block, message) matches the error message thrown by block because that usage suggests that the user believes message is the expected message rather than the message the AssertionError will display if block does not throw.
ERR_ARG_NOT_ITERABLE#
An iterable argument (i.e. a value that works with for...of loops) was required, but not provided to a Node.js API.
ERR_ASSERTION#
A special type of error that can be triggered whenever Node.js detects an exceptional logic violation that should never occur. These are raised typically by the node:assert module.
ERR_ASYNC_CALLBACK#
An attempt was made to register something that is not a function as an AsyncHooks callback.
ERR_ASYNC_LOADER_REQUEST_NEVER_SETTLED#
An operation related to module loading is customized by an asynchronous loader hook that never settled the promise before the loader thread exits.
ERR_ASYNC_TYPE#
The type of an asynchronous resource was invalid. Users are also able to define their own types if using the public embedder API.
ERR_BROTLI_COMPRESSION_FAILED#
Data passed to a Brotli stream was not successfully compressed.
ERR_BROTLI_INVALID_PARAM#
An invalid parameter key was passed during construction of a Brotli stream.
ERR_BUFFER_CONTEXT_NOT_AVAILABLE#
An attempt was made to create a Node.js Buffer instance from addon or embedder code, while in a JS engine Context that is not associated with a Node.js instance. The data passed to the Buffer method will have been released by the time the method returns.
When encountering this error, a possible alternative to creating a Buffer instance is to create a normal Uint8Array, which only differs in the prototype of the resulting object. Uint8Arrays are generally accepted in all Node.js core APIs where Buffers are; they are available in all Contexts.
ERR_BUFFER_OUT_OF_BOUNDS#
An operation outside the bounds of a Buffer was attempted.
ERR_BUFFER_TOO_LARGE#
An attempt has been made to create a Buffer larger than the maximum allowed size.
ERR_CANNOT_WATCH_SIGINT#
Node.js was unable to watch for the SIGINT signal.
ERR_CHILD_CLOSED_BEFORE_REPLY#
A child process was closed before the parent received a reply.
ERR_CHILD_PROCESS_IPC_REQUIRED#
Used when a child process is being forked without specifying an IPC channel.
ERR_CHILD_PROCESS_STDIO_MAXBUFFER#
Used when the main process is trying to read data from the child process's STDERR/STDOUT, and the data's length is longer than the maxBuffer option.
ERR_CLOSED_MESSAGE_PORT#
There was an attempt to use a MessagePort instance in a closed state, usually after .close() has been called.
ERR_CONSOLE_WRITABLE_STREAM#
Console was instantiated without stdout stream, or Console has a non-writable stdout or stderr stream.
ERR_CONSTRUCT_CALL_INVALID#
A class constructor was called that is not callable.
ERR_CONSTRUCT_CALL_REQUIRED#
A constructor for a class was called without new.
ERR_CONTEXT_NOT_INITIALIZED#
The vm context passed into the API is not yet initialized. This could happen when an error occurs (and is caught) during the creation of the context, for example, when the allocation fails or the maximum call stack size is reached when the context is created.
ERR_CPU_PROFILE_ALREADY_STARTED#
The CPU profile with the given name is already started.
ERR_CPU_PROFILE_NOT_STARTED#
The CPU profile with the given name is not started.
ERR_CPU_PROFILE_TOO_MANY#
There are too many CPU profiles being collected.
ERR_CRYPTO_ARGON2_NOT_SUPPORTED#
Argon2 is not supported by the current version of OpenSSL being used.
ERR_CRYPTO_CUSTOM_ENGINE_NOT_SUPPORTED#
An OpenSSL engine was requested (for example, through the clientCertEngine or privateKeyEngine TLS options) that is not supported by the version of OpenSSL being used, likely due to the compile-time flag OPENSSL_NO_ENGINE.
ERR_CRYPTO_ECDH_INVALID_FORMAT#
An invalid value for the format argument was passed to the crypto.ECDH() class getPublicKey() method.
ERR_CRYPTO_ECDH_INVALID_PUBLIC_KEY#
An invalid value for the key argument has been passed to the crypto.ECDH() class computeSecret() method. It means that the public key lies outside of the elliptic curve.
ERR_CRYPTO_ENGINE_UNKNOWN#
An invalid crypto engine identifier was passed to require('node:crypto').setEngine().
ERR_CRYPTO_FIPS_FORCED#
The --force-fips command-line argument was used but there was an attempt to enable or disable FIPS mode in the node:crypto module.
ERR_CRYPTO_FIPS_UNAVAILABLE#
An attempt was made to enable or disable FIPS mode, but FIPS mode was not available.
ERR_CRYPTO_HASH_FINALIZED#
hash.digest() was called multiple times. The hash.digest() method must be called no more than one time per instance of a Hash object.
ERR_CRYPTO_HASH_UPDATE_FAILED#
hash.update() failed for any reason. This should rarely, if ever, happen.
ERR_CRYPTO_INCOMPATIBLE_KEY#
The given crypto keys are incompatible with the attempted operation.
ERR_CRYPTO_INCOMPATIBLE_KEY_OPTIONS#
The selected public or private key encoding is incompatible with other options.
ERR_CRYPTO_INITIALIZATION_FAILED#
Initialization of the crypto subsystem failed.
ERR_CRYPTO_INVALID_AUTH_TAG#
An invalid authentication tag was provided.
ERR_CRYPTO_INVALID_COUNTER#
An invalid counter was provided for a counter-mode cipher.
ERR_CRYPTO_INVALID_CURVE#
An invalid elliptic-curve was provided.
ERR_CRYPTO_INVALID_DIGEST#
An invalid crypto digest algorithm was specified.
ERR_CRYPTO_INVALID_IV#
An invalid initialization vector was provided.
ERR_CRYPTO_INVALID_JWK#
An invalid JSON Web Key was provided.
ERR_CRYPTO_INVALID_KEYLEN#
An invalid key length was provided.
ERR_CRYPTO_INVALID_KEYPAIR#
An invalid key pair was provided.
ERR_CRYPTO_INVALID_KEYTYPE#
An invalid key type was provided.
ERR_CRYPTO_INVALID_KEY_OBJECT_TYPE#
The given crypto key object's type is invalid for the attempted operation.
ERR_CRYPTO_INVALID_MESSAGELEN#
An invalid message length was provided.
ERR_CRYPTO_INVALID_SCRYPT_PARAMS#
One or more crypto.scrypt() or crypto.scryptSync() parameters are outside their legal range.
ERR_CRYPTO_INVALID_STATE#
A crypto method was used on an object that was in an invalid state. For instance, calling cipher.getAuthTag() before calling cipher.final().
ERR_CRYPTO_INVALID_TAG_LENGTH#
An invalid authentication tag length was provided.
ERR_CRYPTO_JOB_INIT_FAILED#
Initialization of an asynchronous crypto operation failed.
ERR_CRYPTO_JWK_UNSUPPORTED_CURVE#
Key's Elliptic Curve is not registered for use in the JSON Web Key Elliptic Curve Registry.
ERR_CRYPTO_JWK_UNSUPPORTED_KEY_TYPE#
Key's Asymmetric Key Type is not registered for use in the JSON Web Key Types Registry.
ERR_CRYPTO_KEM_NOT_SUPPORTED#
Attempted to use KEM operations while Node.js was not compiled with OpenSSL with KEM support.
ERR_CRYPTO_OPERATION_FAILED#
A crypto operation failed for an otherwise unspecified reason.
ERR_CRYPTO_PBKDF2_ERROR#
The PBKDF2 algorithm failed for unspecified reasons. OpenSSL does not provide more details and therefore neither does Node.js.
ERR_CRYPTO_SCRYPT_NOT_SUPPORTED#
Node.js was compiled without scrypt support. Not possible with the official release binaries but can happen with custom builds, including distro builds.
ERR_CRYPTO_SIGN_KEY_REQUIRED#
A signing key was not provided to the sign.sign() method.
ERR_CRYPTO_TIMING_SAFE_EQUAL_LENGTH#
crypto.timingSafeEqual() was called with Buffer, TypedArray, or DataView arguments of different lengths.
ERR_CRYPTO_UNKNOWN_CIPHER#
An unknown cipher was specified.
ERR_CRYPTO_UNKNOWN_DH_GROUP#
An unknown Diffie-Hellman group name was given. See crypto.getDiffieHellman() for a list of valid group names.
ERR_CRYPTO_UNSUPPORTED_OPERATION#
An attempt to invoke an unsupported crypto operation was made.
ERR_DEBUGGER_ERROR#
An error occurred with the debugger.
ERR_DEBUGGER_STARTUP_ERROR#
The debugger timed out waiting for the required host/port to be free.
ERR_DIR_CLOSED#
The fs.Dir was previously closed.
ERR_DIR_CONCURRENT_OPERATION#
A synchronous read or close call was attempted on an fs.Dir which has ongoing asynchronous operations.
ERR_DLOPEN_DISABLED#
Loading native addons has been disabled using --no-addons.
ERR_DLOPEN_FAILED#
A call to process.dlopen() failed.
ERR_DNS_SET_SERVERS_FAILED#
c-ares failed to set the DNS server.
ERR_DOMAIN_CALLBACK_NOT_AVAILABLE#
The node:domain module was not usable since it could not establish the required error handling hooks, because process.setUncaughtExceptionCaptureCallback() had been called at an earlier point in time.
ERR_DOMAIN_CANNOT_SET_UNCAUGHT_EXCEPTION_CAPTURE#
process.setUncaughtExceptionCaptureCallback() could not be called because the node:domain module has been loaded at an earlier point in time.
The stack trace is extended to include the point in time at which the node:domain module had been loaded.
ERR_DUPLICATE_STARTUP_SNAPSHOT_MAIN_FUNCTION#
v8.startupSnapshot.setDeserializeMainFunction() could not be called because it had already been called before.
ERR_ENCODING_INVALID_ENCODED_DATA#
Data provided to TextDecoder() API was invalid according to the encoding provided.
ERR_ENCODING_NOT_SUPPORTED#
Encoding provided to TextDecoder() API was not one of the WHATWG Supported Encodings.
ERR_EVAL_ESM_CANNOT_PRINT#
--print cannot be used with ESM input.
ERR_EVENT_RECURSION#
Thrown when an attempt is made to recursively dispatch an event on EventTarget.
ERR_EXECUTION_ENVIRONMENT_NOT_AVAILABLE#
The JS execution context is not associated with a Node.js environment. This may occur when Node.js is used as an embedded library and some hooks for the JS engine are not set up properly.
ERR_FALSY_VALUE_REJECTION#
A Promise that was callbackified via util.callbackify() was rejected with a falsy value.
ERR_FEATURE_UNAVAILABLE_ON_PLATFORM#
Used when a feature that is not available to the current platform which is running Node.js is used.
ERR_FS_CP_DIR_TO_NON_DIR#
An attempt was made to copy a directory to a non-directory (file, symlink, etc.) using fs.cp().
ERR_FS_CP_EEXIST#
An attempt was made to copy over a file that already existed with fs.cp(), with the force and errorOnExist set to true.
ERR_FS_CP_EINVAL#
When using fs.cp(), src or dest pointed to an invalid path.
ERR_FS_CP_FIFO_PIPE#
An attempt was made to copy a named pipe with fs.cp().
ERR_FS_CP_NON_DIR_TO_DIR#
An attempt was made to copy a non-directory (file, symlink, etc.) to a directory using fs.cp().
ERR_FS_CP_SOCKET#
An attempt was made to copy to a socket with fs.cp().
ERR_FS_CP_SYMLINK_TO_SUBDIRECTORY#
When using fs.cp(), a symlink in dest pointed to a subdirectory of src.
ERR_FS_CP_UNKNOWN#
An attempt was made to copy to an unknown file type with fs.cp().
ERR_FS_EISDIR#
Path is a directory.
ERR_FS_FILE_TOO_LARGE#
An attempt was made to read a file larger than the supported 2 GiB limit for fs.readFile(). This is not a limitation of Buffer, but an internal I/O constraint. For handling larger files, consider using fs.createReadStream() to read the file in chunks.
ERR_FS_WATCH_QUEUE_OVERFLOW#
The number of file system events queued without being handled exceeded the size specified in maxQueue in fs.watch().
ERR_HTTP2_ALTSVC_INVALID_ORIGIN#
HTTP/2 ALTSVC frames require a valid origin.
ERR_HTTP2_ALTSVC_LENGTH#
HTTP/2 ALTSVC frames are limited to a maximum of 16,382 payload bytes.
ERR_HTTP2_CONNECT_AUTHORITY#
For HTTP/2 requests using the CONNECT method, the :authority pseudo-header is required.
ERR_HTTP2_CONNECT_PATH#
For HTTP/2 requests using the CONNECT method, the :path pseudo-header is forbidden.
ERR_HTTP2_CONNECT_SCHEME#
For HTTP/2 requests using the CONNECT method, the :scheme pseudo-header is forbidden.
ERR_HTTP2_ERROR#
A non-specific HTTP/2 error has occurred.
ERR_HTTP2_GOAWAY_SESSION#
New HTTP/2 Streams may not be opened after the Http2Session has received a GOAWAY frame from the connected peer.
ERR_HTTP2_HEADERS_AFTER_RESPOND#
An additional headers was specified after an HTTP/2 response was initiated.
ERR_HTTP2_HEADERS_SENT#
An attempt was made to send multiple response headers.
ERR_HTTP2_HEADER_SINGLE_VALUE#
Multiple values were provided for an HTTP/2 header field that was required to have only a single value.
ERR_HTTP2_INFO_STATUS_NOT_ALLOWED#
Informational HTTP status codes (1xx) may not be set as the response status code on HTTP/2 responses.
ERR_HTTP2_INVALID_CONNECTION_HEADERS#
HTTP/1 connection specific headers are forbidden to be used in HTTP/2 requests and responses.
ERR_HTTP2_INVALID_HEADER_VALUE#
An invalid HTTP/2 header value was specified.
ERR_HTTP2_INVALID_INFO_STATUS#
An invalid HTTP informational status code has been specified. Informational status codes must be an integer between 100 and 199 (inclusive).
ERR_HTTP2_INVALID_ORIGIN#
HTTP/2 ORIGIN frames require a valid origin.
ERR_HTTP2_INVALID_PACKED_SETTINGS_LENGTH#
Input Buffer and Uint8Array instances passed to the http2.getUnpackedSettings() API must have a length that is a multiple of six.
ERR_HTTP2_INVALID_PSEUDOHEADER#
Only valid HTTP/2 pseudoheaders (:status, :path, :authority, :scheme, and :method) may be used.
ERR_HTTP2_INVALID_SESSION#
An action was performed on an Http2Session object that had already been destroyed.
ERR_HTTP2_INVALID_SETTING_VALUE#
An invalid value has been specified for an HTTP/2 setting.
ERR_HTTP2_INVALID_STREAM#
An operation was performed on a stream that had already been destroyed.
ERR_HTTP2_MAX_PENDING_SETTINGS_ACK#
Whenever an HTTP/2 SETTINGS frame is sent to a connected peer, the peer is required to send an acknowledgment that it has received and applied the new SETTINGS. By default, a maximum number of unacknowledged SETTINGS frames may be sent at any given time. This error code is used when that limit has been reached.
ERR_HTTP2_NESTED_PUSH#
An attempt was made to initiate a new push stream from within a push stream. Nested push streams are not permitted.
ERR_HTTP2_NO_MEM#
Out of memory when using the http2session.setLocalWindowSize(windowSize) API.
ERR_HTTP2_NO_SOCKET_MANIPULATION#
An attempt was made to directly manipulate (read, write, pause, resume, etc.) a socket attached to an Http2Session.
ERR_HTTP2_ORIGIN_LENGTH#
HTTP/2 ORIGIN frames are limited to a length of 16382 bytes.
ERR_HTTP2_OUT_OF_STREAMS#
The number of streams created on a single HTTP/2 session reached the maximum limit.
ERR_HTTP2_PAYLOAD_FORBIDDEN#
A message payload was specified for an HTTP response code for which a payload is forbidden.
ERR_HTTP2_PING_CANCEL#
An HTTP/2 ping was canceled.
ERR_HTTP2_PING_LENGTH#
HTTP/2 ping payloads must be exactly 8 bytes in length.
ERR_HTTP2_PSEUDOHEADER_NOT_ALLOWED#
An HTTP/2 pseudo-header has been used inappropriately. Pseudo-headers are header key names that begin with the : prefix.
ERR_HTTP2_PUSH_DISABLED#
An attempt was made to create a push stream, which had been disabled by the client.
ERR_HTTP2_SEND_FILE#
An attempt was made to use the Http2Stream.prototype.responseWithFile() API to send a directory.
ERR_HTTP2_SEND_FILE_NOSEEK#
An attempt was made to use the Http2Stream.prototype.responseWithFile() API to send something other than a regular file, but offset or length options were provided.
ERR_HTTP2_SESSION_ERROR#
The Http2Session closed with a non-zero error code.
ERR_HTTP2_SETTINGS_CANCEL#
The Http2Session settings canceled.
ERR_HTTP2_SOCKET_BOUND#
An attempt was made to connect a Http2Session object to a net.Socket or tls.TLSSocket that had already been bound to another Http2Session object.
ERR_HTTP2_SOCKET_UNBOUND#
An attempt was made to use the socket property of an Http2Session that has already been closed.
ERR_HTTP2_STATUS_101#
Use of the 101 Informational status code is forbidden in HTTP/2.
ERR_HTTP2_STATUS_INVALID#
An invalid HTTP status code has been specified. Status codes must be an integer between 100 and 599 (inclusive).
ERR_HTTP2_STREAM_CANCEL#
An Http2Stream was destroyed before any data was transmitted to the connected peer.
ERR_HTTP2_STREAM_ERROR#
A non-zero error code was been specified in an RST_STREAM frame.
ERR_HTTP2_STREAM_SELF_DEPENDENCY#
When setting the priority for an HTTP/2 stream, the stream may be marked as a dependency for a parent stream. This error code is used when an attempt is made to mark a stream and dependent of itself.
ERR_HTTP2_TOO_MANY_CUSTOM_SETTINGS#
The number of supported custom settings (10) has been exceeded.
ERR_HTTP2_TOO_MANY_INVALID_FRAMES#
The limit of acceptable invalid HTTP/2 protocol frames sent by the peer, as specified through the maxSessionInvalidFrames option, has been exceeded.
ERR_HTTP2_TRAILERS_ALREADY_SENT#
Trailing headers have already been sent on the Http2Stream.
ERR_HTTP2_TRAILERS_NOT_READY#
The http2stream.sendTrailers() method cannot be called until after the 'wantTrailers' event is emitted on an Http2Stream object. The 'wantTrailers' event will only be emitted if the waitForTrailers option is set for the Http2Stream.
ERR_HTTP2_UNSUPPORTED_PROTOCOL#
http2.connect() was passed a URL that uses any protocol other than http: or https:.
ERR_HTTP_BODY_NOT_ALLOWED#
An error is thrown when writing to an HTTP response which does not allow contents.
ERR_HTTP_CONTENT_LENGTH_MISMATCH#
Response body size doesn't match with the specified content-length header value.
ERR_HTTP_HEADERS_SENT#
An attempt was made to add more headers after the headers had already been sent.
ERR_HTTP_INVALID_HEADER_VALUE#
An invalid HTTP header value was specified.
ERR_HTTP_INVALID_STATUS_CODE#
Status code was outside the regular status code range (100-999).
ERR_HTTP_REQUEST_TIMEOUT#
The client has not sent the entire request within the allowed time.
ERR_HTTP_SOCKET_ASSIGNED#
The given ServerResponse was already assigned a socket.
ERR_HTTP_SOCKET_ENCODING#
Changing the socket encoding is not allowed per RFC 7230 Section 3.
ERR_HTTP_TRAILER_INVALID#
The Trailer header was set even though the transfer encoding does not support that.
ERR_ILLEGAL_CONSTRUCTOR#
An attempt was made to construct an object using a non-public constructor.
ERR_IMPORT_ATTRIBUTE_MISSING#
An import attribute is missing, preventing the specified module to be imported.
ERR_IMPORT_ATTRIBUTE_TYPE_INCOMPATIBLE#
An import type attribute was provided, but the specified module is of a different type.
ERR_IMPORT_ATTRIBUTE_UNSUPPORTED#
An import attribute is not supported by this version of Node.js.
ERR_INCOMPATIBLE_OPTION_PAIR#
An option pair is incompatible with each other and cannot be used at the same time.
ERR_INPUT_TYPE_NOT_ALLOWED#
The --input-type flag was used to attempt to execute a file. This flag can only be used with input via --eval, --print, or STDIN.
ERR_INSPECTOR_ALREADY_ACTIVATED#
While using the node:inspector module, an attempt was made to activate the inspector when it already started to listen on a port. Use inspector.close() before activating it on a different address.
ERR_INSPECTOR_ALREADY_CONNECTED#
While using the node:inspector module, an attempt was made to connect when the inspector was already connected.
ERR_INSPECTOR_CLOSED#
While using the node:inspector module, an attempt was made to use the inspector after the session had already closed.
ERR_INSPECTOR_COMMAND#
An error occurred while issuing a command via the node:inspector module.
ERR_INSPECTOR_NOT_ACTIVE#
The inspector is not active when inspector.waitForDebugger() is called.
ERR_INSPECTOR_NOT_AVAILABLE#
The node:inspector module is not available for use.
ERR_INSPECTOR_NOT_CONNECTED#
While using the node:inspector module, an attempt was made to use the inspector before it was connected.
ERR_INSPECTOR_NOT_WORKER#
An API was called on the main thread that can only be used from the worker thread.
ERR_INTERNAL_ASSERTION#
There was a bug in Node.js or incorrect usage of Node.js internals. To fix the error, open an issue at https://github.com/nodejs/node/issues.
ERR_INVALID_ADDRESS#
The provided address is not understood by the Node.js API.
ERR_INVALID_ADDRESS_FAMILY#
The provided address family is not understood by the Node.js API.
ERR_INVALID_ARG_TYPE#
An argument of the wrong type was passed to a Node.js API.
ERR_INVALID_ARG_VALUE#
An invalid or unsupported value was passed for a given argument.
ERR_INVALID_ASYNC_ID#
An invalid asyncId or triggerAsyncId was passed using AsyncHooks. An id less than -1 should never happen.
ERR_INVALID_BUFFER_SIZE#
A swap was performed on a Buffer but its size was not compatible with the operation.
ERR_INVALID_CHAR#
Invalid characters were detected in headers.
ERR_INVALID_CURSOR_POS#
A cursor on a given stream cannot be moved to a specified row without a specified column.
ERR_INVALID_FD#
A file descriptor ('fd') was not valid (e.g. it was a negative value).
ERR_INVALID_FD_TYPE#
A file descriptor ('fd') type was not valid.
ERR_INVALID_FILE_URL_HOST#
A Node.js API that consumes file: URLs (such as certain functions in the fs module) encountered a file URL with an incompatible host. This situation can only occur on Unix-like systems where only localhost or an empty host is supported.
ERR_INVALID_FILE_URL_PATH#
A Node.js API that consumes file: URLs (such as certain functions in the fs module) encountered a file URL with an incompatible path. The exact semantics for determining whether a path can be used is platform-dependent.
The thrown error object includes an input property that contains the URL object of the invalid file: URL.
ERR_INVALID_HANDLE_TYPE#
An attempt was made to send an unsupported "handle" over an IPC communication channel to a child process. See subprocess.send() and process.send() for more information.
ERR_INVALID_HTTP_TOKEN#
An invalid HTTP token was supplied.
ERR_INVALID_IP_ADDRESS#
An IP address is not valid.
ERR_INVALID_MIME_SYNTAX#
The syntax of a MIME is not valid.
ERR_INVALID_MODULE#
An attempt was made to load a module that does not exist or was otherwise not valid.
ERR_INVALID_MODULE_SPECIFIER#
The imported module string is an invalid URL, package name, or package subpath specifier.
ERR_INVALID_OBJECT_DEFINE_PROPERTY#
An error occurred while setting an invalid attribute on the property of an object.
ERR_INVALID_PACKAGE_CONFIG#
An invalid package.json file failed parsing.
ERR_INVALID_PACKAGE_TARGET#
The package.json "exports" field contains an invalid target mapping value for the attempted module resolution.
ERR_INVALID_PROTOCOL#
An invalid options.protocol was passed to http.request().
ERR_INVALID_REPL_EVAL_CONFIG#
Both breakEvalOnSigint and eval options were set in the REPL config, which is not supported.
ERR_INVALID_REPL_INPUT#
The input may not be used in the REPL. The conditions under which this error is used are described in the REPL documentation.
ERR_INVALID_RETURN_PROPERTY#
Thrown in case a function option does not provide a valid value for one of its returned object properties on execution.
ERR_INVALID_RETURN_PROPERTY_VALUE#
Thrown in case a function option does not provide an expected value type for one of its returned object properties on execution.
ERR_INVALID_RETURN_VALUE#
Thrown in case a function option does not return an expected value type on execution, such as when a function is expected to return a promise.
ERR_INVALID_STATE#
Indicates that an operation cannot be completed due to an invalid state. For instance, an object may have already been destroyed, or may be performing another operation.
ERR_INVALID_SYNC_FORK_INPUT#
A Buffer, TypedArray, DataView, or string was provided as stdio input to an asynchronous fork. See the documentation for the child_process module for more information.
ERR_INVALID_THIS#
A Node.js API function was called with an incompatible this value.
const urlSearchParams = new URLSearchParams('foo=bar&baz=new');
const buf = Buffer.alloc(1);
urlSearchParams.has.call(buf, 'foo');
// Throws a TypeError with code 'ERR_INVALID_THIS'
ERR_INVALID_TUPLE#
An element in the iterable provided to the WHATWG URLSearchParams constructor did not represent a [name, value] tuple – that is, if an element is not iterable, or does not consist of exactly two elements.
ERR_INVALID_TYPESCRIPT_SYNTAX#
The provided TypeScript syntax is not valid.
ERR_INVALID_URI#
An invalid URI was passed.
ERR_INVALID_URL#
An invalid URL was passed to the WHATWG URL constructor or the legacy url.parse() to be parsed. The thrown error object typically has an additional property 'input' that contains the URL that failed to parse.
ERR_INVALID_URL_PATTERN#
An invalid URLPattern was passed to the WHATWG URLPattern constructor to be parsed.
ERR_INVALID_URL_SCHEME#
An attempt was made to use a URL of an incompatible scheme (protocol) for a specific purpose. It is only used in the WHATWG URL API support in the fs module (which only accepts URLs with 'file' scheme), but may be used in other Node.js APIs as well in the future.
ERR_IPC_CHANNEL_CLOSED#
An attempt was made to use an IPC communication channel that was already closed.
ERR_IPC_DISCONNECTED#
An attempt was made to disconnect an IPC communication channel that was already disconnected. See the documentation for the child_process module for more information.
ERR_IPC_ONE_PIPE#
An attempt was made to create a child Node.js process using more than one IPC communication channel. See the documentation for the child_process module for more information.
ERR_IPC_SYNC_FORK#
An attempt was made to open an IPC communication channel with a synchronously forked Node.js process. See the documentation for the child_process module for more information.
ERR_IP_BLOCKED#
IP is blocked by net.BlockList.
ERR_LOADER_CHAIN_INCOMPLETE#
An ESM loader hook returned without calling next() and without explicitly signaling a short circuit.
ERR_LOAD_SQLITE_EXTENSION#
An error occurred while loading a SQLite extension.
ERR_MEMORY_ALLOCATION_FAILED#
An attempt was made to allocate memory (usually in the C++ layer) but it failed.
ERR_MESSAGE_TARGET_CONTEXT_UNAVAILABLE#
A message posted to a MessagePort could not be deserialized in the target vm Context. Not all Node.js objects can be successfully instantiated in any context at this time, and attempting to transfer them using postMessage() can fail on the receiving side in that case.
ERR_METHOD_NOT_IMPLEMENTED#
A method is required but not implemented.
ERR_MISSING_ARGS#
A required argument of a Node.js API was not passed. This is only used for strict compliance with the API specification (which in some cases may accept func(undefined) but not func()). In most native Node.js APIs, func(undefined) and func() are treated identically, and the ERR_INVALID_ARG_TYPE error code may be used instead.
ERR_MISSING_OPTION#
For APIs that accept options objects, some options might be mandatory. This code is thrown if a required option is missing.
ERR_MISSING_PASSPHRASE#
An attempt was made to read an encrypted key without specifying a passphrase.
ERR_MISSING_PLATFORM_FOR_WORKER#
The V8 platform used by this instance of Node.js does not support creating Workers. This is caused by lack of embedder support for Workers. In particular, this error will not occur with standard builds of Node.js.
ERR_MODULE_LINK_MISMATCH#
A module can not be linked because the same module requests in it are not resolved to the same module.
ERR_MODULE_NOT_FOUND#
A module file could not be resolved by the ECMAScript modules loader while attempting an import operation or when loading the program entry point.
ERR_MULTIPLE_CALLBACK#
A callback was called more than once.
A callback is almost always meant to only be called once as the query can either be fulfilled or rejected but not both at the same time. The latter would be possible by calling a callback more than once.
ERR_NAPI_CONS_FUNCTION#
While using Node-API, a constructor passed was not a function.
ERR_NAPI_INVALID_DATAVIEW_ARGS#
While calling napi_create_dataview(), a given offset was outside the bounds of the dataview or offset + length was larger than a length of given buffer.
ERR_NAPI_INVALID_TYPEDARRAY_ALIGNMENT#
While calling napi_create_typedarray(), the provided offset was not a multiple of the element size.
ERR_NAPI_INVALID_TYPEDARRAY_LENGTH#
While calling napi_create_typedarray(), (length * size_of_element) + byte_offset was larger than the length of given buffer.
ERR_NAPI_TSFN_CALL_JS#
An error occurred while invoking the JavaScript portion of the thread-safe function.
ERR_NAPI_TSFN_GET_UNDEFINED#
An error occurred while attempting to retrieve the JavaScript undefined value.
ERR_NON_CONTEXT_AWARE_DISABLED#
A non-context-aware native addon was loaded in a process that disallows them.
ERR_NOT_BUILDING_SNAPSHOT#
An attempt was made to use operations that can only be used when building V8 startup snapshot even though Node.js isn't building one.
ERR_NOT_IN_SINGLE_EXECUTABLE_APPLICATION#
The operation cannot be performed when it's not in a single-executable application.
ERR_NOT_SUPPORTED_IN_SNAPSHOT#
An attempt was made to perform operations that are not supported when building a startup snapshot.
ERR_NO_CRYPTO#
An attempt was made to use crypto features while Node.js was not compiled with OpenSSL crypto support.
ERR_NO_ICU#
An attempt was made to use features that require ICU, but Node.js was not compiled with ICU support.
ERR_NO_TYPESCRIPT#
An attempt was made to use features that require Native TypeScript support, but Node.js was not compiled with TypeScript support.
ERR_OPERATION_FAILED#
An operation failed. This is typically used to signal the general failure of an asynchronous operation.
ERR_OPTIONS_BEFORE_BOOTSTRAPPING#
An attempt was made to get options before the bootstrapping was completed.
ERR_OUT_OF_RANGE#
A given value is out of the accepted range.
ERR_PACKAGE_IMPORT_NOT_DEFINED#
The package.json "imports" field does not define the given internal package specifier mapping.
ERR_PACKAGE_PATH_NOT_EXPORTED#
The package.json "exports" field does not export the requested subpath. Because exports are encapsulated, private internal modules that are not exported cannot be imported through the package resolution, unless using an absolute URL.
ERR_PARSE_ARGS_INVALID_OPTION_VALUE#
When strict set to true, thrown by util.parseArgs() if a <boolean> value is provided for an option of type <string>, or if a <string> value is provided for an option of type <boolean>.
ERR_PARSE_ARGS_UNEXPECTED_POSITIONAL#
Thrown by util.parseArgs(), when a positional argument is provided and allowPositionals is set to false.
ERR_PARSE_ARGS_UNKNOWN_OPTION#
When strict set to true, thrown by util.parseArgs() if an argument is not configured in options.
ERR_PERFORMANCE_INVALID_TIMESTAMP#
An invalid timestamp value was provided for a performance mark or measure.
ERR_PERFORMANCE_MEASURE_INVALID_OPTIONS#
Invalid options were provided for a performance measure.
ERR_PROTO_ACCESS#
Accessing Object.prototype.__proto__ has been forbidden using --disable-proto=throw. Object.getPrototypeOf and Object.setPrototypeOf should be used to get and set the prototype of an object.
ERR_PROXY_INVALID_CONFIG#
Failed to proxy a request because the proxy configuration is invalid.
ERR_PROXY_TUNNEL#
Failed to establish proxy tunnel when NODE_USE_ENV_PROXY or --use-env-proxy is enabled.
ERR_QUIC_APPLICATION_ERROR#
Stability: 1 - Experimental
A QUIC application error occurred.
ERR_QUIC_CONNECTION_FAILED#
Stability: 1 - Experimental
Establishing a QUIC connection failed.
ERR_QUIC_ENDPOINT_CLOSED#
Stability: 1 - Experimental
A QUIC Endpoint closed with an error.
ERR_QUIC_OPEN_STREAM_FAILED#
Stability: 1 - Experimental
Opening a QUIC stream failed.
ERR_QUIC_TRANSPORT_ERROR#
Stability: 1 - Experimental
A QUIC transport error occurred.
ERR_QUIC_VERSION_NEGOTIATION_ERROR#
Stability: 1 - Experimental
A QUIC session failed because version negotiation is required.
ERR_REQUIRE_ASYNC_MODULE#
When trying to require() a ES Module, the module turns out to be asynchronous. That is, it contains top-level await.
To see where the top-level await is, use --experimental-print-required-tla (this would execute the modules before looking for the top-level awaits).
ERR_REQUIRE_CYCLE_MODULE#
When trying to require() a ES Module, a CommonJS to ESM or ESM to CommonJS edge participates in an immediate cycle. This is not allowed because ES Modules cannot be evaluated while they are already being evaluated.
To avoid the cycle, the require() call involved in a cycle should not happen at the top-level of either an ES Module (via createRequire()) or a CommonJS module, and should be done lazily in an inner function.
ERR_REQUIRE_ESM#
Stability: 0 - Deprecated
An attempt was made to require() an ES Module.
This error has been deprecated since require() now supports loading synchronous ES modules. When require() encounters an ES module that contains top-level await, it will throw ERR_REQUIRE_ASYNC_MODULE instead.
ERR_SCRIPT_EXECUTION_INTERRUPTED#
Script execution was interrupted by SIGINT (For example, Ctrl+C was pressed.)
ERR_SCRIPT_EXECUTION_TIMEOUT#
Script execution timed out, possibly due to bugs in the script being executed.
ERR_SERVER_ALREADY_LISTEN#
The server.listen() method was called while a net.Server was already listening. This applies to all instances of net.Server, including HTTP, HTTPS, and HTTP/2 Server instances.
ERR_SERVER_NOT_RUNNING#
The server.close() method was called when a net.Server was not running. This applies to all instances of net.Server, including HTTP, HTTPS, and HTTP/2 Server instances.
ERR_SINGLE_EXECUTABLE_APPLICATION_ASSET_NOT_FOUND#
A key was passed to single executable application APIs to identify an asset, but no match could be found.
ERR_SOCKET_ALREADY_BOUND#
An attempt was made to bind a socket that has already been bound.
ERR_SOCKET_BAD_BUFFER_SIZE#
An invalid (negative) size was passed for either the recvBufferSize or sendBufferSize options in dgram.createSocket().
ERR_SOCKET_BAD_PORT#
An API function expecting a port >= 0 and < 65536 received an invalid value.
ERR_SOCKET_BAD_TYPE#
An API function expecting a socket type (udp4 or udp6) received an invalid value.
ERR_SOCKET_BUFFER_SIZE#
While using dgram.createSocket(), the size of the receive or send Buffer could not be determined.
ERR_SOCKET_CLOSED#
An attempt was made to operate on an already closed socket.
ERR_SOCKET_CLOSED_BEFORE_CONNECTION#
When calling net.Socket.write() on a connecting socket and the socket was closed before the connection was established.
ERR_SOCKET_CONNECTION_TIMEOUT#
The socket was unable to connect to any address returned by the DNS within the allowed timeout when using the family autoselection algorithm.
ERR_SOCKET_DGRAM_IS_CONNECTED#
A dgram.connect() call was made on an already connected socket.
ERR_SOCKET_DGRAM_NOT_CONNECTED#
A dgram.disconnect() or dgram.remoteAddress() call was made on a disconnected socket.
ERR_SOCKET_DGRAM_NOT_RUNNING#
A call was made and the UDP subsystem was not running.
ERR_SOURCE_MAP_CORRUPT#
The source map could not be parsed because it does not exist, or is corrupt.
ERR_SOURCE_MAP_MISSING_SOURCE#
A file imported from a source map was not found.
ERR_SOURCE_PHASE_NOT_DEFINED#
The provided module import does not provide a source phase imports representation for source phase import syntax import source x from 'x' or import.source(x).
ERR_SQLITE_ERROR#
An error was returned from SQLite.
ERR_SRI_PARSE#
A string was provided for a Subresource Integrity check, but was unable to be parsed. Check the format of integrity attributes by looking at the Subresource Integrity specification.
ERR_STREAM_ALREADY_FINISHED#
A stream method was called that cannot complete because the stream was finished.
ERR_STREAM_CANNOT_PIPE#
An attempt was made to call stream.pipe() on a Writable stream.
ERR_STREAM_DESTROYED#
A stream method was called that cannot complete because the stream was destroyed using stream.destroy().
ERR_STREAM_NULL_VALUES#
An attempt was made to call stream.write() with a null chunk.
ERR_STREAM_PREMATURE_CLOSE#
An error returned by stream.finished() and stream.pipeline(), when a stream or a pipeline ends non gracefully with no explicit error.
ERR_STREAM_PUSH_AFTER_EOF#
An attempt was made to call stream.push() after a null(EOF) had been pushed to the stream.
ERR_STREAM_UNABLE_TO_PIPE#
An attempt was made to pipe to a closed or destroyed stream in a pipeline.
ERR_STREAM_UNSHIFT_AFTER_END_EVENT#
An attempt was made to call stream.unshift() after the 'end' event was emitted.
ERR_STREAM_WRAP#
Prevents an abort if a string decoder was set on the Socket or if the decoder is in objectMode.
const Socket = require('node:net').Socket;
const instance = new Socket();
instance.setEncoding('utf8');
ERR_STREAM_WRITE_AFTER_END#
An attempt was made to call stream.write() after stream.end() has been called.
ERR_STRING_TOO_LONG#
An attempt has been made to create a string longer than the maximum allowed length.
ERR_SYNTHETIC#
An artificial error object used to capture the call stack for diagnostic reports.
ERR_SYSTEM_ERROR#
An unspecified or non-specific system error has occurred within the Node.js process. The error object will have an err.info object property with additional details.
ERR_TEST_FAILURE#
This error represents a failed test. Additional information about the failure is available via the cause property. The failureType property specifies what the test was doing when the failure occurred.
ERR_TLS_ALPN_CALLBACK_INVALID_RESULT#
This error is thrown when an ALPNCallback returns a value that is not in the list of ALPN protocols offered by the client.
ERR_TLS_ALPN_CALLBACK_WITH_PROTOCOLS#
This error is thrown when creating a TLSServer if the TLS options include both ALPNProtocols and ALPNCallback. These options are mutually exclusive.
ERR_TLS_CERT_ALTNAME_FORMAT#
This error is thrown by checkServerIdentity if a user-supplied subjectaltname property violates encoding rules. Certificate objects produced by Node.js itself always comply with encoding rules and will never cause this error.
ERR_TLS_CERT_ALTNAME_INVALID#
While using TLS, the host name/IP of the peer did not match any of the subjectAltNames in its certificate.
ERR_TLS_DH_PARAM_SIZE#
While using TLS, the parameter offered for the Diffie-Hellman (DH) key-agreement protocol is too small. By default, the key length must be greater than or equal to 1024 bits to avoid vulnerabilities, even though it is strongly recommended to use 2048 bits or larger for stronger security.
ERR_TLS_HANDSHAKE_TIMEOUT#
A TLS/SSL handshake timed out. In this case, the server must also abort the connection.
ERR_TLS_INVALID_CONTEXT#
The context must be a SecureContext.
ERR_TLS_INVALID_PROTOCOL_METHOD#
The specified secureProtocol method is invalid. It is either unknown, or disabled because it is insecure.
ERR_TLS_INVALID_PROTOCOL_VERSION#
Valid TLS protocol versions are 'TLSv1', 'TLSv1.1', or 'TLSv1.2'.
ERR_TLS_INVALID_STATE#
The TLS socket must be connected and securely established. Ensure the 'secure' event is emitted before continuing.
ERR_TLS_PROTOCOL_VERSION_CONFLICT#
Attempting to set a TLS protocol minVersion or maxVersion conflicts with an attempt to set the secureProtocol explicitly. Use one mechanism or the other.
ERR_TLS_PSK_SET_IDENTITY_HINT_FAILED#
Failed to set PSK identity hint. Hint may be too long.
ERR_TLS_RENEGOTIATION_DISABLED#
An attempt was made to renegotiate TLS on a socket instance with renegotiation disabled.
ERR_TLS_REQUIRED_SERVER_NAME#
While using TLS, the server.addContext() method was called without providing a host name in the first parameter.
ERR_TLS_SESSION_ATTACK#
An excessive amount of TLS renegotiations is detected, which is a potential vector for denial-of-service attacks.
ERR_TLS_SNI_FROM_SERVER#
An attempt was made to issue Server Name Indication from a TLS server-side socket, which is only valid from a client.
ERR_TRACE_EVENTS_CATEGORY_REQUIRED#
The trace_events.createTracing() method requires at least one trace event category.
ERR_TRACE_EVENTS_UNAVAILABLE#
The node:trace_events module could not be loaded because Node.js was compiled with the --without-v8-platform flag.
ERR_TRAILING_JUNK_AFTER_STREAM_END#
Trailing junk found after the end of the compressed stream. This error is thrown when extra, unexpected data is detected after the end of a compressed stream (for example, in zlib or gzip decompression).
ERR_TRANSFORM_ALREADY_TRANSFORMING#
A Transform stream finished while it was still transforming.
ERR_TRANSFORM_WITH_LENGTH_0#
A Transform stream finished with data still in the write buffer.
ERR_TTY_INIT_FAILED#
The initialization of a TTY failed due to a system error.
ERR_UNAVAILABLE_DURING_EXIT#
Function was called within a process.on('exit') handler that shouldn't be called within process.on('exit') handler.
ERR_UNCAUGHT_EXCEPTION_CAPTURE_ALREADY_SET#
process.setUncaughtExceptionCaptureCallback() was called twice, without first resetting the callback to null.
This error is designed to prevent accidentally overwriting a callback registered from another module.
ERR_UNESCAPED_CHARACTERS#
A string that contained unescaped characters was received.
ERR_UNHANDLED_ERROR#
An unhandled error occurred (for instance, when an 'error' event is emitted by an EventEmitter but an 'error' handler is not registered).
ERR_UNKNOWN_BUILTIN_MODULE#
Used to identify a specific kind of internal Node.js error that should not typically be triggered by user code. Instances of this error point to an internal bug within the Node.js binary itself.
ERR_UNKNOWN_CREDENTIAL#
A Unix group or user identifier that does not exist was passed.
ERR_UNKNOWN_ENCODING#
An invalid or unknown encoding option was passed to an API.
ERR_UNKNOWN_FILE_EXTENSION#
An attempt was made to load a module with an unknown or unsupported file extension.
ERR_UNKNOWN_MODULE_FORMAT#
An attempt was made to load a module with an unknown or unsupported format.
ERR_UNKNOWN_SIGNAL#
An invalid or unknown process signal was passed to an API expecting a valid signal (such as subprocess.kill()).
ERR_UNSUPPORTED_DIR_IMPORT#
import a directory URL is unsupported. Instead, self-reference a package using its name and define a custom subpath in the "exports" field of the package.json file.
import './'; // unsupported
import './index.js'; // supported
import 'package-name'; // supported
ERR_UNSUPPORTED_ESM_URL_SCHEME#
import with URL schemes other than file and data is unsupported.
ERR_UNSUPPORTED_NODE_MODULES_TYPE_STRIPPING#
Type stripping is not supported for files descendent of a node_modules directory.
ERR_UNSUPPORTED_RESOLVE_REQUEST#
An attempt was made to resolve an invalid module referrer. This can happen when importing or calling import.meta.resolve() with either:
- a bare specifier that is not a builtin module from a module whose URL scheme is not
file. - a relative URL from a module whose URL scheme is not a special scheme.
try {
// Trying to import the package 'bare-specifier' from a `data:` URL module:
await import('data:text/javascript,import "bare-specifier"');
} catch (e) {
console.log(e.code); // ERR_UNSUPPORTED_RESOLVE_REQUEST
}
ERR_UNSUPPORTED_TYPESCRIPT_SYNTAX#
The provided TypeScript syntax is unsupported. This could happen when using TypeScript syntax that requires transformation with type-stripping.
ERR_USE_AFTER_CLOSE#
An attempt was made to use something that was already closed.
ERR_VALID_PERFORMANCE_ENTRY_TYPE#
While using the Performance Timing API (perf_hooks), no valid performance entry types are found.
ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING#
A dynamic import callback was not specified.
ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING_FLAG#
A dynamic import callback was invoked without --experimental-vm-modules.
ERR_VM_MODULE_ALREADY_LINKED#
The module attempted to be linked is not eligible for linking, because of one of the following reasons:
- It has already been linked (
linkingStatusis'linked') - It is being linked (
linkingStatusis'linking') - Linking has failed for this module (
linkingStatusis'errored')
ERR_VM_MODULE_CACHED_DATA_REJECTED#
The cachedData option passed to a module constructor is invalid.
ERR_VM_MODULE_CANNOT_CREATE_CACHED_DATA#
Cached data cannot be created for modules which have already been evaluated.
ERR_VM_MODULE_DIFFERENT_CONTEXT#
The module being returned from the linker function is from a different context than the parent module. Linked modules must share the same context.
ERR_VM_MODULE_LINK_FAILURE#
The module was unable to be linked due to a failure.
ERR_VM_MODULE_NOT_MODULE#
The fulfilled value of a linking promise is not a vm.Module object.
ERR_VM_MODULE_STATUS#
The current module's status does not allow for this operation. The specific meaning of the error depends on the specific function.
ERR_WASI_ALREADY_STARTED#
The WASI instance has already started.
ERR_WASI_NOT_STARTED#
The WASI instance has not been started.
ERR_WEBASSEMBLY_NOT_SUPPORTED#
A feature requiring WebAssembly was used, but WebAssembly is not supported or has been disabled in the current environment (for example, when running with --jitless).
ERR_WEBASSEMBLY_RESPONSE#
The Response that has been passed to WebAssembly.compileStreaming or to WebAssembly.instantiateStreaming is not a valid WebAssembly response.
ERR_WORKER_INIT_FAILED#
The Worker initialization failed.
ERR_WORKER_INVALID_EXEC_ARGV#
The execArgv option passed to the Worker constructor contains invalid flags.
ERR_WORKER_MESSAGING_ERRORED#
Stability: 1.1 - Active development
The destination thread threw an error while processing a message sent via postMessageToThread().
ERR_WORKER_MESSAGING_FAILED#
Stability: 1.1 - Active development
The thread requested in postMessageToThread() is invalid or has no workerMessage listener.
ERR_WORKER_MESSAGING_SAME_THREAD#
Stability: 1.1 - Active development
The thread id requested in postMessageToThread() is the current thread id.
ERR_WORKER_MESSAGING_TIMEOUT#
Stability: 1.1 - Active development
Sending a message via postMessageToThread() timed out.
ERR_WORKER_NOT_RUNNING#
An operation failed because the Worker instance is not currently running.
ERR_WORKER_OUT_OF_MEMORY#
The Worker instance terminated because it reached its memory limit.
ERR_WORKER_PATH#
The path for the main script of a worker is neither an absolute path nor a relative path starting with ./ or ../.
ERR_WORKER_UNSERIALIZABLE_ERROR#
All attempts at serializing an uncaught exception from a worker thread failed.
ERR_WORKER_UNSUPPORTED_OPERATION#
The requested functionality is not supported in worker threads.
ERR_ZLIB_INITIALIZATION_FAILED#
Creation of a zlib object failed due to incorrect configuration.
ERR_ZSTD_INVALID_PARAM#
An invalid parameter key was passed during construction of a Zstd stream.
HPE_CHUNK_EXTENSIONS_OVERFLOW#
Too much data was received for a chunk extensions. In order to protect against malicious or malconfigured clients, if more than 16 KiB of data is received then an Error with this code will be emitted.
HPE_HEADER_OVERFLOW#
Too much HTTP header data was received. In order to protect against malicious or malconfigured clients, if more than maxHeaderSize of HTTP header data is received then HTTP parsing will abort without a request or response object being created, and an Error with this code will be emitted.
HPE_UNEXPECTED_CONTENT_LENGTH#
Server is sending both a Content-Length header and Transfer-Encoding: chunked.
Transfer-Encoding: chunked allows the server to maintain an HTTP persistent connection for dynamically generated content. In this case, the Content-Length HTTP header cannot be used.
Use Content-Length or Transfer-Encoding: chunked.
MODULE_NOT_FOUND#
A module file could not be resolved by the CommonJS modules loader while attempting a require() operation or when loading the program entry point.
Legacy Node.js error codes#
Stability: 0 - Deprecated. These error codes are either inconsistent, or have been removed.
ERR_CANNOT_TRANSFER_OBJECT#
The value passed to postMessage() contained an object that is not supported for transferring.
ERR_CPU_USAGE#
The native call from process.cpuUsage could not be processed.
ERR_CRYPTO_HASH_DIGEST_NO_UTF16#
The UTF-16 encoding was used with hash.digest(). While the hash.digest() method does allow an encoding argument to be passed in, causing the method to return a string rather than a Buffer, the UTF-16 encoding (e.g. ucs or utf16le) is not supported.
ERR_CRYPTO_SCRYPT_INVALID_PARAMETER#
An incompatible combination of options was passed to crypto.scrypt() or crypto.scryptSync(). New versions of Node.js use the error code ERR_INCOMPATIBLE_OPTION_PAIR instead, which is consistent with other APIs.
ERR_FS_INVALID_SYMLINK_TYPE#
An invalid symlink type was passed to the fs.symlink() or fs.symlinkSync() methods.
ERR_HTTP2_FRAME_ERROR#
Used when a failure occurs sending an individual frame on the HTTP/2 session.
ERR_HTTP2_HEADERS_OBJECT#
Used when an HTTP/2 Headers Object is expected.
ERR_HTTP2_HEADER_REQUIRED#
Used when a required header is missing in an HTTP/2 message.
ERR_HTTP2_INFO_HEADERS_AFTER_RESPOND#
HTTP/2 informational headers must only be sent prior to calling the Http2Stream.prototype.respond() method.
ERR_HTTP2_STREAM_CLOSED#
Used when an action has been performed on an HTTP/2 Stream that has already been closed.
ERR_HTTP_INVALID_CHAR#
Used when an invalid character is found in an HTTP response status message (reason phrase).
ERR_IMPORT_ASSERTION_TYPE_FAILED#
An import assertion has failed, preventing the specified module to be imported.
ERR_IMPORT_ASSERTION_TYPE_MISSING#
An import assertion is missing, preventing the specified module to be imported.
ERR_IMPORT_ASSERTION_TYPE_UNSUPPORTED#
An import attribute is not supported by this version of Node.js.
ERR_INDEX_OUT_OF_RANGE#
A given index was out of the accepted range (e.g. negative offsets).
ERR_INVALID_OPT_VALUE#
An invalid or unexpected value was passed in an options object.
ERR_INVALID_OPT_VALUE_ENCODING#
An invalid or unknown file encoding was passed.
ERR_INVALID_PERFORMANCE_MARK#
While using the Performance Timing API (perf_hooks), a performance mark is invalid.
ERR_INVALID_TRANSFER_OBJECT#
An invalid transfer object was passed to postMessage().
ERR_MANIFEST_ASSERT_INTEGRITY#
An attempt was made to load a resource, but the resource did not match the integrity defined by the policy manifest. See the documentation for policy manifests for more information.
ERR_MANIFEST_DEPENDENCY_MISSING#
An attempt was made to load a resource, but the resource was not listed as a dependency from the location that attempted to load it. See the documentation for policy manifests for more information.
ERR_MANIFEST_INTEGRITY_MISMATCH#
An attempt was made to load a policy manifest, but the manifest had multiple entries for a resource which did not match each other. Update the manifest entries to match in order to resolve this error. See the documentation for policy manifests for more information.
ERR_MANIFEST_INVALID_RESOURCE_FIELD#
A policy manifest resource had an invalid value for one of its fields. Update the manifest entry to match in order to resolve this error. See the documentation for policy manifests for more information.
ERR_MANIFEST_INVALID_SPECIFIER#
A policy manifest resource had an invalid value for one of its dependency mappings. Update the manifest entry to match to resolve this error. See the documentation for policy manifests for more information.
ERR_MANIFEST_PARSE_POLICY#
An attempt was made to load a policy manifest, but the manifest was unable to be parsed. See the documentation for policy manifests for more information.
ERR_MANIFEST_TDZ#
An attempt was made to read from a policy manifest, but the manifest initialization has not yet taken place. This is likely a bug in Node.js.
ERR_MANIFEST_UNKNOWN_ONERROR#
A policy manifest was loaded, but had an unknown value for its "onerror" behavior. See the documentation for policy manifests for more information.
ERR_MISSING_MESSAGE_PORT_IN_TRANSFER_LIST#
This error code was replaced by ERR_MISSING_TRANSFERABLE_IN_TRANSFER_LIST in Node.js 15.0.0, because it is no longer accurate as other types of transferable objects also exist now.
ERR_MISSING_TRANSFERABLE_IN_TRANSFER_LIST#
An object that needs to be explicitly listed in the transferList argument is in the object passed to a postMessage() call, but is not provided in the transferList for that call. Usually, this is a MessagePort.
In Node.js versions prior to v15.0.0, the error code being used here was ERR_MISSING_MESSAGE_PORT_IN_TRANSFER_LIST. However, the set of transferable object types has been expanded to cover more types than MessagePort.
ERR_NAPI_CONS_PROTOTYPE_OBJECT#
Used by the Node-API when Constructor.prototype is not an object.
ERR_NAPI_TSFN_START_IDLE_LOOP#
On the main thread, values are removed from the queue associated with the thread-safe function in an idle loop. This error indicates that an error has occurred when attempting to start the loop.
ERR_NAPI_TSFN_STOP_IDLE_LOOP#
Once no more items are left in the queue, the idle loop must be suspended. This error indicates that the idle loop has failed to stop.
ERR_NO_LONGER_SUPPORTED#
A Node.js API was called in an unsupported manner, such as Buffer.write(string, encoding, offset[, length]).
ERR_OUTOFMEMORY#
Used generically to identify that an operation caused an out of memory condition.
ERR_PARSE_HISTORY_DATA#
The node:repl module was unable to parse data from the REPL history file.
ERR_SOCKET_CANNOT_SEND#
Data could not be sent on a socket.
ERR_STDERR_CLOSE#
An attempt was made to close the process.stderr stream. By design, Node.js does not allow stdout or stderr streams to be closed by user code.
ERR_STDOUT_CLOSE#
An attempt was made to close the process.stdout stream. By design, Node.js does not allow stdout or stderr streams to be closed by user code.
ERR_STREAM_READ_NOT_IMPLEMENTED#
Used when an attempt is made to use a readable stream that has not implemented readable._read().
ERR_TAP_LEXER_ERROR#
An error representing a failing lexer state.
ERR_TAP_PARSER_ERROR#
An error representing a failing parser state. Additional information about the token causing the error is available via the cause property.
ERR_TAP_VALIDATION_ERROR#
This error represents a failed TAP validation.
ERR_TLS_RENEGOTIATION_FAILED#
Used when a TLS renegotiation request has failed in a non-specific way.
ERR_TRANSFERRING_EXTERNALIZED_SHAREDARRAYBUFFER#
A SharedArrayBuffer whose memory is not managed by the JavaScript engine or by Node.js was encountered during serialization. Such a SharedArrayBuffer cannot be serialized.
This can only happen when native addons create SharedArrayBuffers in "externalized" mode, or put existing SharedArrayBuffer into externalized mode.
ERR_UNKNOWN_STDIN_TYPE#
An attempt was made to launch a Node.js process with an unknown stdin file type. This error is usually an indication of a bug within Node.js itself, although it is possible for user code to trigger it.
ERR_UNKNOWN_STREAM_TYPE#
An attempt was made to launch a Node.js process with an unknown stdout or stderr file type. This error is usually an indication of a bug within Node.js itself, although it is possible for user code to trigger it.
ERR_V8BREAKITERATOR#
The V8 BreakIterator API was used but the full ICU data set is not installed.
ERR_VALUE_OUT_OF_RANGE#
Used when a given value is out of the accepted range.
ERR_VM_MODULE_LINKING_ERRORED#
The linker function returned a module for which linking has failed.
ERR_VM_MODULE_NOT_LINKED#
The module must be successfully linked before instantiation.
ERR_WORKER_UNSUPPORTED_EXTENSION#
The pathname used for the main script of a worker has an unknown file extension.
ERR_ZLIB_BINDING_CLOSED#
Used when an attempt is made to use a zlib object after it has already been closed.
OpenSSL Error Codes#
Time Validity Errors#
CERT_NOT_YET_VALID#
The certificate is not yet valid: the notBefore date is after the current time.
CERT_HAS_EXPIRED#
The certificate has expired: the notAfter date is before the current time.
CRL_NOT_YET_VALID#
The certificate revocation list (CRL) has a future issue date.
CRL_HAS_EXPIRED#
The certificate revocation list (CRL) has expired.
CERT_REVOKED#
The certificate has been revoked; it is on a certificate revocation list (CRL).
Trust or Chain Related Errors#
UNABLE_TO_GET_ISSUER_CERT#
The issuer certificate of a looked up certificate could not be found. This normally means the list of trusted certificates is not complete.
UNABLE_TO_GET_ISSUER_CERT_LOCALLY#
The certificate’s issuer is not known. This is the case if the issuer is not included in the trusted certificate list.
DEPTH_ZERO_SELF_SIGNED_CERT#
The passed certificate is self-signed and the same certificate cannot be found in the list of trusted certificates.
SELF_SIGNED_CERT_IN_CHAIN#
The certificate’s issuer is not known. This is the case if the issuer is not included in the trusted certificate list.
CERT_CHAIN_TOO_LONG#
The certificate chain length is greater than the maximum depth.
UNABLE_TO_GET_CRL#
The CRL reference by the certificate could not be found.
UNABLE_TO_VERIFY_LEAF_SIGNATURE#
No signatures could be verified because the chain contains only one certificate and it is not self signed.
CERT_UNTRUSTED#
The root certificate authority (CA) is not marked as trusted for the specified purpose.
Basic Extension Errors#
INVALID_CA#
A CA certificate is invalid. Either it is not a CA or its extensions are not consistent with the supplied purpose.
PATH_LENGTH_EXCEEDED#
The basicConstraints pathlength parameter has been exceeded.
Name Related Errors#
HOSTNAME_MISMATCH#
Certificate does not match provided name.
Usage and Policy Errors#
INVALID_PURPOSE#
The supplied certificate cannot be used for the specified purpose.
CERT_REJECTED#
The root CA is marked to reject the specified purpose.
Formatting Errors#
CERT_SIGNATURE_FAILURE#
The signature of the certificate is invalid.
CRL_SIGNATURE_FAILURE#
The signature of the certificate revocation list (CRL) is invalid.
ERROR_IN_CERT_NOT_BEFORE_FIELD#
The certificate notBefore field contains an invalid time.
ERROR_IN_CERT_NOT_AFTER_FIELD#
The certificate notAfter field contains an invalid time.
ERROR_IN_CRL_LAST_UPDATE_FIELD#
The CRL lastUpdate field contains an invalid time.
ERROR_IN_CRL_NEXT_UPDATE_FIELD#
The CRL nextUpdate field contains an invalid time.
UNABLE_TO_DECRYPT_CERT_SIGNATURE#
The certificate signature could not be decrypted. This means that the actual signature value could not be determined rather than it not matching the expected value, this is only meaningful for RSA keys.
UNABLE_TO_DECRYPT_CRL_SIGNATURE#
The certificate revocation list (CRL) signature could not be decrypted: this means that the actual signature value could not be determined rather than it not matching the expected value.
UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY#
The public key in the certificate SubjectPublicKeyInfo could not be read.
Other OpenSSL Errors#
OUT_OF_MEM#
An error occurred trying to allocate memory. This should never happen.
Modules: CommonJS modules#
Stability: 2 - Stable
CommonJS modules are the original way to package JavaScript code for Node.js. Node.js also supports the ECMAScript modules standard used by browsers and other JavaScript runtimes.
In Node.js, each file is treated as a separate module. For example, consider a file named foo.js:
const circle = require('./circle.js');
console.log(`The area of a circle of radius 4 is ${circle.area(4)}`);
On the first line, foo.js loads the module circle.js that is in the same directory as foo.js.
Here are the contents of circle.js:
const { PI } = Math;
exports.area = (r) => PI * r ** 2;
exports.circumference = (r) => 2 * PI * r;
The module circle.js has exported the functions area() and circumference(). Functions and objects are added to the root of a module by specifying additional properties on the special exports object.
Variables local to the module will be private, because the module is wrapped in a function by Node.js (see module wrapper). In this example, the variable PI is private to circle.js.
The module.exports property can be assigned a new value (such as a function or object).
In the following code, bar.js makes use of the square module, which exports a Square class:
const Square = require('./square.js');
const mySquare = new Square(2);
console.log(`The area of mySquare is ${mySquare.area()}`);
The square module is defined in square.js:
// Assigning to exports will not modify module, must use module.exports
module.exports = class Square {
constructor(width) {
this.width = width;
}
area() {
return this.width ** 2;
}
};
The CommonJS module system is implemented in the module core module.
Enabling#
Node.js has two module systems: CommonJS modules and ECMAScript modules.
By default, Node.js will treat the following as CommonJS modules:
Files with a
.cjsextension;Files with a
.jsextension when the nearest parentpackage.jsonfile contains a top-level field"type"with a value of"commonjs".Files with a
.jsextension or without an extension, when the nearest parentpackage.jsonfile doesn't contain a top-level field"type"or there is nopackage.jsonin any parent folder; unless the file contains syntax that errors unless it is evaluated as an ES module. Package authors should include the"type"field, even in packages where all sources are CommonJS. Being explicit about thetypeof the package will make things easier for build tools and loaders to determine how the files in the package should be interpreted.Files with an extension that is not
.mjs,.cjs,.json,.node, or.js(when the nearest parentpackage.jsonfile contains a top-level field"type"with a value of"module", those files will be recognized as CommonJS modules only if they are being included viarequire(), not when used as the command-line entry point of the program).
See Determining module system for more details.
Calling require() always use the CommonJS module loader. Calling import() always use the ECMAScript module loader.
Accessing the main module#
When a file is run directly from Node.js, require.main is set to its module. That means that it is possible to determine whether a file has been run directly by testing require.main === module.
For a file foo.js, this will be true if run via node foo.js, but false if run by require('./foo').
When the entry point is not a CommonJS module, require.main is undefined, and the main module is out of reach.
Package manager tips#
The semantics of the Node.js require() function were designed to be general enough to support reasonable directory structures. Package manager programs such as dpkg, rpm, and npm will hopefully find it possible to build native packages from Node.js modules without modification.
In the following, we give a suggested directory structure that could work:
Let's say that we wanted to have the folder at /usr/lib/node/<some-package>/<some-version> hold the contents of a specific version of a package.
Packages can depend on one another. In order to install package foo, it may be necessary to install a specific version of package bar. The bar package may itself have dependencies, and in some cases, these may even collide or form cyclic dependencies.
Because Node.js looks up the realpath of any modules it loads (that is, it resolves symlinks) and then looks for their dependencies in node_modules folders, this situation can be resolved with the following architecture:
/usr/lib/node/foo/1.2.3/: Contents of thefoopackage, version 1.2.3./usr/lib/node/bar/4.3.2/: Contents of thebarpackage thatfoodepends on./usr/lib/node/foo/1.2.3/node_modules/bar: Symbolic link to/usr/lib/node/bar/4.3.2/./usr/lib/node/bar/4.3.2/node_modules/*: Symbolic links to the packages thatbardepends on.
Thus, even if a cycle is encountered, or if there are dependency conflicts, every module will be able to get a version of its dependency that it can use.
When the code in the foo package does require('bar'), it will get the version that is symlinked into /usr/lib/node/foo/1.2.3/node_modules/bar. Then, when the code in the bar package calls require('quux'), it'll get the version that is symlinked into /usr/lib/node/bar/4.3.2/node_modules/quux.
Furthermore, to make the module lookup process even more optimal, rather than putting packages directly in /usr/lib/node, we could put them in /usr/lib/node_modules/<name>/<version>. Then Node.js will not bother looking for missing dependencies in /usr/node_modules or /node_modules.
In order to make modules available to the Node.js REPL, it might be useful to also add the /usr/lib/node_modules folder to the $NODE_PATH environment variable. Since the module lookups using node_modules folders are all relative, and based on the real path of the files making the calls to require(), the packages themselves can be anywhere.
Loading ECMAScript modules using require()#
The .mjs extension is reserved for ECMAScript Modules. See Determining module system section for more info regarding which files are parsed as ECMAScript modules.
require() only supports loading ECMAScript modules that meet the following requirements:
- The module is fully synchronous (contains no top-level
await); and - One of these conditions are met:
- The file has a
.mjsextension. - The file has a
.jsextension, and the closestpackage.jsoncontains"type": "module" - The file has a
.jsextension, the closestpackage.jsondoes not contain"type": "commonjs", and the module contains ES module syntax.
- The file has a
If the ES Module being loaded meets the requirements, require() can load it and return the module namespace object. In this case it is similar to dynamic import() but is run synchronously and returns the name space object directly.
With the following ES Modules:
// distance.mjs export function distance(a, b) { return Math.sqrt((b.x - a.x) ** 2 + (b.y - a.y) ** 2); }// point.mjs export default class Point { constructor(x, y) { this.x = x; this.y = y; } }
A CommonJS module can load them with require():
const distance = require('./distance.mjs');
console.log(distance);
// [Module: null prototype] {
// distance: [Function: distance]
// }
const point = require('./point.mjs');
console.log(point);
// [Module: null prototype] {
// default: [class Point],
// __esModule: true,
// }
For interoperability with existing tools that convert ES Modules into CommonJS, which could then load real ES Modules through require(), the returned namespace would contain a __esModule: true property if it has a default export so that consuming code generated by tools can recognize the default exports in real ES Modules. If the namespace already defines __esModule, this would not be added. This property is experimental and can change in the future. It should only be used by tools converting ES modules into CommonJS modules, following existing ecosystem conventions. Code authored directly in CommonJS should avoid depending on it.
The result returned by require() is the module namespace object, which places the default export in the .default property, similar to the results returned by import(). To customize what should be returned by require(esm) directly, the ES Module can export the desired value using the string name "module.exports".
// point.mjs export default class Point { constructor(x, y) { this.x = x; this.y = y; } } // `distance` is lost to CommonJS consumers of this module, unless it's // added to `Point` as a static property. export function distance(a, b) { return Math.sqrt((b.x - a.x) ** 2 + (b.y - a.y) ** 2); } export { Point as 'module.exports' }const Point = require('./point.mjs'); console.log(Point); // [class Point] // Named exports are lost when 'module.exports' is used const { distance } = require('./point.mjs'); console.log(distance); // undefined
Notice in the example above, when the module.exports export name is used, named exports will be lost to CommonJS consumers. To allow CommonJS consumers to continue accessing named exports, the module can make sure that the default export is an object with the named exports attached to it as properties. For example with the example above, distance can be attached to the default export, the Point class, as a static method.
export function distance(a, b) { return Math.sqrt((b.x - a.x) ** 2 + (b.y - a.y) ** 2); } export default class Point { constructor(x, y) { this.x = x; this.y = y; } static distance = distance; } export { Point as 'module.exports' }const Point = require('./point.mjs'); console.log(Point); // [class Point] const { distance } = require('./point.mjs'); console.log(distance); // [Function: distance]
If the module being require()'d contains top-level await, or the module graph it imports contains top-level await, ERR_REQUIRE_ASYNC_MODULE will be thrown. In this case, users should load the asynchronous module using import().
If --experimental-print-required-tla is enabled, instead of throwing ERR_REQUIRE_ASYNC_MODULE before evaluation, Node.js will evaluate the module, try to locate the top-level awaits, and print their location to help users fix them.
If support for loading ES modules using require() results in unexpected breakage, it can be disabled using --no-require-module. To print where this feature is used, use --trace-require-module.
This feature can be detected by checking if process.features.require_module is true.
All together#
To get the exact filename that will be loaded when require() is called, use the require.resolve() function.
Putting together all of the above, here is the high-level algorithm in pseudocode of what require() does:
require(X) from module at path Y
1. If X is a core module,
a. return the core module
b. STOP
2. If X begins with '/'
a. set Y to the file system root
3. If X is equal to '.', or X begins with './', '/' or '../'
a. LOAD_AS_FILE(Y + X)
b. LOAD_AS_DIRECTORY(Y + X)
c. THROW "not found"
4. If X begins with '#'
a. LOAD_PACKAGE_IMPORTS(X, dirname(Y))
5. LOAD_PACKAGE_SELF(X, dirname(Y))
6. LOAD_NODE_MODULES(X, dirname(Y))
7. THROW "not found"
MAYBE_DETECT_AND_LOAD(X)
1. If X parses as a CommonJS module, load X as a CommonJS module. STOP.
2. Else, if the source code of X can be parsed as ECMAScript module using
<a href="esm.md#resolver-algorithm-specification">DETECT_MODULE_SYNTAX defined in
the ESM resolver</a>,
a. Load X as an ECMAScript module. STOP.
3. THROW the SyntaxError from attempting to parse X as CommonJS in 1. STOP.
LOAD_AS_FILE(X)
1. If X is a file, load X as its file extension format. STOP
2. If X.js is a file,
a. Find the closest package scope SCOPE to X.
b. If no scope was found
1. MAYBE_DETECT_AND_LOAD(X.js)
c. If the SCOPE/package.json contains "type" field,
1. If the "type" field is "module", load X.js as an ECMAScript module. STOP.
2. If the "type" field is "commonjs", load X.js as a CommonJS module. STOP.
d. MAYBE_DETECT_AND_LOAD(X.js)
3. If X.json is a file, load X.json to a JavaScript Object. STOP
4. If X.node is a file, load X.node as binary addon. STOP
LOAD_INDEX(X)
1. If X/index.js is a file
a. Find the closest package scope SCOPE to X.
b. If no scope was found, load X/index.js as a CommonJS module. STOP.
c. If the SCOPE/package.json contains "type" field,
1. If the "type" field is "module", load X/index.js as an ECMAScript module. STOP.
2. Else, load X/index.js as a CommonJS module. STOP.
2. If X/index.json is a file, parse X/index.json to a JavaScript object. STOP
3. If X/index.node is a file, load X/index.node as binary addon. STOP
LOAD_AS_DIRECTORY(X)
1. If X/package.json is a file,
a. Parse X/package.json, and look for "main" field.
b. If "main" is a falsy value, GOTO 2.
c. let M = X + (json main field)
d. LOAD_AS_FILE(M)
e. LOAD_INDEX(M)
f. LOAD_INDEX(X) DEPRECATED
g. THROW "not found"
2. LOAD_INDEX(X)
LOAD_NODE_MODULES(X, START)
1. let DIRS = NODE_MODULES_PATHS(START)
2. for each DIR in DIRS:
a. LOAD_PACKAGE_EXPORTS(X, DIR)
b. LOAD_AS_FILE(DIR/X)
c. LOAD_AS_DIRECTORY(DIR/X)
NODE_MODULES_PATHS(START)
1. let PARTS = path split(START)
2. let I = count of PARTS - 1
3. let DIRS = []
4. while I >= 0,
a. if PARTS[I] = "node_modules", GOTO d.
b. DIR = path join(PARTS[0 .. I] + "node_modules")
c. DIRS = DIRS + DIR
d. let I = I - 1
5. return DIRS + GLOBAL_FOLDERS
LOAD_PACKAGE_IMPORTS(X, DIR)
1. Find the closest package scope SCOPE to DIR.
2. If no scope was found, return.
3. If the SCOPE/package.json "imports" is null or undefined, return.
4. If `--no-require-module` is not enabled
a. let CONDITIONS = ["node", "require", "module-sync"]
b. Else, let CONDITIONS = ["node", "require"]
5. let MATCH = PACKAGE_IMPORTS_RESOLVE(X, pathToFileURL(SCOPE),
CONDITIONS) <a href="esm.md#resolver-algorithm-specification">defined in the ESM resolver</a>.
6. RESOLVE_ESM_MATCH(MATCH).
LOAD_PACKAGE_EXPORTS(X, DIR)
1. Try to interpret X as a combination of NAME and SUBPATH where the name
may have a @scope/ prefix and the subpath begins with a slash (`/`).
2. If X does not match this pattern or DIR/NAME/package.json is not a file,
return.
3. Parse DIR/NAME/package.json, and look for "exports" field.
4. If "exports" is null or undefined, return.
5. If `--no-require-module` is not enabled
a. let CONDITIONS = ["node", "require", "module-sync"]
b. Else, let CONDITIONS = ["node", "require"]
6. let MATCH = PACKAGE_EXPORTS_RESOLVE(pathToFileURL(DIR/NAME), "." + SUBPATH,
`package.json` "exports", CONDITIONS) <a href="esm.md#resolver-algorithm-specification">defined in the ESM resolver</a>.
7. RESOLVE_ESM_MATCH(MATCH)
LOAD_PACKAGE_SELF(X, DIR)
1. Find the closest package scope SCOPE to DIR.
2. If no scope was found, return.
3. If the SCOPE/package.json "exports" is null or undefined, return.
4. If the SCOPE/package.json "name" is not the first segment of X, return.
5. let MATCH = PACKAGE_EXPORTS_RESOLVE(pathToFileURL(SCOPE),
"." + X.slice("name".length), `package.json` "exports", ["node", "require"])
<a href="esm.md#resolver-algorithm-specification">defined in the ESM resolver</a>.
6. RESOLVE_ESM_MATCH(MATCH)
RESOLVE_ESM_MATCH(MATCH)
1. let RESOLVED_PATH = fileURLToPath(MATCH)
2. If the file at RESOLVED_PATH exists, load RESOLVED_PATH as its extension
format. STOP
3. THROW "not found"
Caching#
Modules are cached after the first time they are loaded. This means (among other things) that every call to require('foo') will get exactly the same object returned, if it would resolve to the same file.
Provided require.cache is not modified, multiple calls to require('foo') will not cause the module code to be executed multiple times. This is an important feature. With it, "partially done" objects can be returned, thus allowing transitive dependencies to be loaded even when they would cause cycles.
To have a module execute code multiple times, export a function, and call that function.
Module caching caveats#
Modules are cached based on their resolved filename. Since modules may resolve to a different filename based on the location of the calling module (loading from node_modules folders), it is not a guarantee that require('foo') will always return the exact same object, if it would resolve to different files.
Additionally, on case-insensitive file systems or operating systems, different resolved filenames can point to the same file, but the cache will still treat them as different modules and will reload the file multiple times. For example, require('./foo') and require('./FOO') return two different objects, irrespective of whether or not ./foo and ./FOO are the same file.
Built-in modules#
Node.js has several modules compiled into the binary. These modules are described in greater detail elsewhere in this documentation.
The built-in modules are defined within the Node.js source and are located in the lib/ folder.
Built-in modules can be identified using the node: prefix, in which case it bypasses the require cache. For instance, require('node:http') will always return the built in HTTP module, even if there is require.cache entry by that name.
Some built-in modules are always preferentially loaded if their identifier is passed to require(). For instance, require('http') will always return the built-in HTTP module, even if there is a file by that name.
The list of all the built-in modules can be retrieved from module.builtinModules. The modules being all listed without the node: prefix, except those that mandate such prefix (as explained in the next section).
Built-in modules with mandatory node: prefix#
When being loaded by require(), some built-in modules must be requested with the node: prefix. This requirement exists to prevent newly introduced built-in modules from having a conflict with user land packages that already have taken the name. Currently the built-in modules that requires the node: prefix are:
The list of these modules is exposed in module.builtinModules, including the prefix.
Cycles#
When there are circular require() calls, a module might not have finished executing when it is returned.
Consider this situation:
a.js:
console.log('a starting');
exports.done = false;
const b = require('./b.js');
console.log('in a, b.done = %j', b.done);
exports.done = true;
console.log('a done');
b.js:
console.log('b starting');
exports.done = false;
const a = require('./a.js');
console.log('in b, a.done = %j', a.done);
exports.done = true;
console.log('b done');
main.js:
console.log('main starting');
const a = require('./a.js');
const b = require('./b.js');
console.log('in main, a.done = %j, b.done = %j', a.done, b.done);
When main.js loads a.js, then a.js in turn loads b.js. At that point, b.js tries to load a.js. In order to prevent an infinite loop, an unfinished copy of the a.js exports object is returned to the b.js module. b.js then finishes loading, and its exports object is provided to the a.js module.
By the time main.js has loaded both modules, they're both finished. The output of this program would thus be:
$ node main.js
main starting
a starting
b starting
in b, a.done = false
b done
in a, b.done = true
a done
in main, a.done = true, b.done = true
Careful planning is required to allow cyclic module dependencies to work correctly within an application.
File modules#
If the exact filename is not found, then Node.js will attempt to load the required filename with the added extensions: .js, .json, and finally .node. When loading a file that has a different extension (e.g. .cjs), its full name must be passed to require(), including its file extension (e.g. require('./file.cjs')).
.json files are parsed as JSON text files, .node files are interpreted as compiled addon modules loaded with process.dlopen(). Files using any other extension (or no extension at all) are parsed as JavaScript text files. Refer to the Determining module system section to understand what parse goal will be used.
A required module prefixed with '/' is an absolute path to the file. For example, require('/home/marco/foo.js') will load the file at /home/marco/foo.js.
A required module prefixed with './' is relative to the file calling require(). That is, circle.js must be in the same directory as foo.js for require('./circle') to find it.
Without a leading '/', './', or '../' to indicate a file, the module must either be a core module or is loaded from a node_modules folder.
If the given path does not exist, require() will throw a MODULE_NOT_FOUND error.
Folders as modules#
Stability: 3 - Legacy: Use subpath exports or subpath imports instead.
There are three ways in which a folder may be passed to require() as an argument.
The first is to create a package.json file in the root of the folder, which specifies a main module. An example package.json file might look like this:
{ "name" : "some-library",
"main" : "./lib/some-library.js" }
If this was in a folder at ./some-library, then require('./some-library') would attempt to load ./some-library/lib/some-library.js.
If there is no package.json file present in the directory, or if the "main" entry is missing or cannot be resolved, then Node.js will attempt to load an index.js or index.node file out of that directory. For example, if there was no package.json file in the previous example, then require('./some-library') would attempt to load:
./some-library/index.js./some-library/index.node
If these attempts fail, then Node.js will report the entire module as missing with the default error:
Error: Cannot find module 'some-library'
In all three above cases, an import('./some-library') call would result in a ERR_UNSUPPORTED_DIR_IMPORT error. Using package subpath exports or subpath imports can provide the same containment organization benefits as folders as modules, and work for both require and import.
Loading from node_modules folders#
If the module identifier passed to require() is not a built-in module, and does not begin with '/', '../', or './', then Node.js starts at the directory of the current module, and adds /node_modules, and attempts to load the module from that location. Node.js will not append node_modules to a path already ending in node_modules.
If it is not found there, then it moves to the parent directory, and so on, until the root of the file system is reached.
For example, if the file at '/home/ry/projects/foo.js' called require('bar.js'), then Node.js would look in the following locations, in this order:
/home/ry/projects/node_modules/bar.js/home/ry/node_modules/bar.js/home/node_modules/bar.js/node_modules/bar.js
This allows programs to localize their dependencies, so that they do not clash.
It is possible to require specific files or sub modules distributed with a module by including a path suffix after the module name. For instance require('example-module/path/to/file') would resolve path/to/file relative to where example-module is located. The suffixed path follows the same module resolution semantics.
Loading from the global folders#
If the NODE_PATH environment variable is set to a colon-delimited list of absolute paths, then Node.js will search those paths for modules if they are not found elsewhere.
On Windows, NODE_PATH is delimited by semicolons (;) instead of colons.
NODE_PATH was originally created to support loading modules from varying paths before the current module resolution algorithm was defined.
NODE_PATH is still supported, but is less necessary now that the Node.js ecosystem has settled on a convention for locating dependent modules. Sometimes deployments that rely on NODE_PATH show surprising behavior when people are unaware that NODE_PATH must be set. Sometimes a module's dependencies change, causing a different version (or even a different module) to be loaded as the NODE_PATH is searched.
Additionally, Node.js will search in the following list of GLOBAL_FOLDERS:
- 1:
$HOME/.node_modules - 2:
$HOME/.node_libraries - 3:
$PREFIX/lib/node
Where $HOME is the user's home directory, and $PREFIX is the Node.js configured node_prefix.
These are mostly for historic reasons.
It is strongly encouraged to place dependencies in the local node_modules folder. These will be loaded faster, and more reliably.
The module wrapper#
Before a module's code is executed, Node.js will wrap it with a function wrapper that looks like the following:
(function(exports, require, module, __filename, __dirname) {
// Module code actually lives in here
});
By doing this, Node.js achieves a few things:
- It keeps top-level variables (defined with
var,const, orlet) scoped to the module rather than the global object. - It helps to provide some global-looking variables that are actually specific to the module, such as:
- The
moduleandexportsobjects that the implementor can use to export values from the module. - The convenience variables
__filenameand__dirname, containing the module's absolute filename and directory path.
- The
The module scope#
__dirname#
- Type:
<string>
The directory name of the current module. This is the same as the path.dirname() of the __filename.
Example: running node example.js from /Users/mjr
console.log(__dirname);
// Prints: /Users/mjr
console.log(path.dirname(__filename));
// Prints: /Users/mjr
__filename#
- Type:
<string>
The file name of the current module. This is the current module file's absolute path with symlinks resolved.
For a main program this is not necessarily the same as the file name used in the command line.
See __dirname for the directory name of the current module.
Examples:
Running node example.js from /Users/mjr
console.log(__filename);
// Prints: /Users/mjr/example.js
console.log(__dirname);
// Prints: /Users/mjr
Given two modules: a and b, where b is a dependency of a and there is a directory structure of:
/Users/mjr/app/a.js/Users/mjr/app/node_modules/b/b.js
References to __filename within b.js will return /Users/mjr/app/node_modules/b/b.js while references to __filename within a.js will return /Users/mjr/app/a.js.
exports#
- Type:
<Object>
A reference to the module.exports that is shorter to type. See the section about the exports shortcut for details on when to use exports and when to use module.exports.
module#
- Type:
<module>
A reference to the current module, see the section about the module object. In particular, module.exports is used for defining what a module exports and makes available through require().
require(id)#
Used to import modules, JSON, and local files. Modules can be imported from node_modules. Local modules and JSON files can be imported using a relative path (e.g. ./, ./foo, ./bar/baz, ../foo) that will be resolved against the directory named by __dirname (if defined) or the current working directory. The relative paths of POSIX style are resolved in an OS independent fashion, meaning that the examples above will work on Windows in the same way they would on Unix systems.
// Importing a local module with a path relative to the `__dirname` or current
// working directory. (On Windows, this would resolve to .\path\myLocalModule.)
const myLocalModule = require('./path/myLocalModule');
// Importing a JSON file:
const jsonData = require('./path/filename.json');
// Importing a module from node_modules or Node.js built-in module:
const crypto = require('node:crypto');
require.cache#
- Type:
<Object>
Modules are cached in this object when they are required. By deleting a key value from this object, the next require will reload the module. This does not apply to native addons, for which reloading will result in an error.
Adding or replacing entries is also possible. This cache is checked before built-in modules and if a name matching a built-in module is added to the cache, only node:-prefixed require calls are going to receive the built-in module. Use with care!
const assert = require('node:assert');
const realFs = require('node:fs');
const fakeFs = {};
require.cache.fs = { exports: fakeFs };
assert.strictEqual(require('fs'), fakeFs);
assert.strictEqual(require('node:fs'), realFs);
require.extensions#
Stability: 0 - Deprecated
- Type:
<Object>
Instruct require on how to handle certain file extensions.
Process files with the extension .sjs as .js:
require.extensions['.sjs'] = require.extensions['.js'];
Deprecated. In the past, this list has been used to load non-JavaScript modules into Node.js by compiling them on-demand. However, in practice, there are much better ways to do this, such as loading modules via some other Node.js program, or compiling them to JavaScript ahead of time.
Avoid using require.extensions. Use could cause subtle bugs and resolving the extensions gets slower with each registered extension.
require.main#
- Type:
<module>|<undefined>
The Module object representing the entry script loaded when the Node.js process launched, or undefined if the entry point of the program is not a CommonJS module. See "Accessing the main module".
In entry.js script:
console.log(require.main);
node entry.js
Module {
id: '.',
path: '/absolute/path/to',
exports: {},
filename: '/absolute/path/to/entry.js',
loaded: false,
children: [],
paths:
[ '/absolute/path/to/node_modules',
'/absolute/path/node_modules',
'/absolute/node_modules',
'/node_modules' ] }
require.resolve(request[, options])#
request<string>The module path to resolve.options<Object>paths<string[]>Paths to resolve module location from. If present, these paths are used instead of the default resolution paths, with the exception of GLOBAL_FOLDERS like$HOME/.node_modules, which are always included. Each of these paths is used as a starting point for the module resolution algorithm, meaning that thenode_moduleshierarchy is checked from this location.
- Returns:
<string>
Use the internal require() machinery to look up the location of a module, but rather than loading the module, just return the resolved filename.
If the module can not be found, a MODULE_NOT_FOUND error is thrown.
require.resolve.paths(request)#
request<string>The module path whose lookup paths are being retrieved.- Returns:
<string[]>|<null>
Returns an array containing the paths searched during resolution of request or null if the request string references a core module, for example http or fs.
The module object#
- Type:
<Object>
In each module, the module free variable is a reference to the object representing the current module. For convenience, module.exports is also accessible via the exports module-global. module is not actually a global but rather local to each module.
module.children#
- Type:
<module[]>
The module objects required for the first time by this one.
module.exports#
- Type:
<Object>
The module.exports object is created by the Module system. Sometimes this is not acceptable; many want their module to be an instance of some class. To do this, assign the desired export object to module.exports. Assigning the desired object to exports will simply rebind the local exports variable, which is probably not what is desired.
For example, suppose we were making a module called a.js:
const EventEmitter = require('node:events');
module.exports = new EventEmitter();
// Do some work, and after some time emit
// the 'ready' event from the module itself.
setTimeout(() => {
module.exports.emit('ready');
}, 1000);
Then in another file we could do:
const a = require('./a');
a.on('ready', () => {
console.log('module "a" is ready');
});
Assignment to module.exports must be done immediately. It cannot be done in any callbacks. This does not work:
x.js:
setTimeout(() => {
module.exports = { a: 'hello' };
}, 0);
y.js:
const x = require('./x');
console.log(x.a);
exports shortcut#
The exports variable is available within a module's file-level scope, and is assigned the value of module.exports before the module is evaluated.
It allows a shortcut, so that module.exports.f = ... can be written more succinctly as exports.f = .... However, be aware that like any variable, if a new value is assigned to exports, it is no longer bound to module.exports:
module.exports.hello = true; // Exported from require of module
exports = { hello: false }; // Not exported, only available in the module
When the module.exports property is being completely replaced by a new object, it is common to also reassign exports:
module.exports = exports = function Constructor() {
// ... etc.
};
To illustrate the behavior, imagine this hypothetical implementation of require(), which is quite similar to what is actually done by require():
function require(/* ... */) {
const module = { exports: {} };
((module, exports) => {
// Module code here. In this example, define a function.
function someFunc() {}
exports = someFunc;
// At this point, exports is no longer a shortcut to module.exports, and
// this module will still export an empty default object.
module.exports = someFunc;
// At this point, the module will now export someFunc, instead of the
// default object.
})(module, module.exports);
return module.exports;
}
module.filename#
- Type:
<string>
The fully resolved filename of the module.
module.id#
- Type:
<string>
The identifier for the module. Typically this is the fully resolved filename.
module.isPreloading#
- Type:
<boolean>trueif the module is running during the Node.js preload phase.
module.loaded#
- Type:
<boolean>
Whether or not the module is done loading, or is in the process of loading.
module.parent#
Stability: 0 - Deprecated: Please use require.main and module.children instead.
- Type:
<module>|<null>|<undefined>
The module that first required this one, or null if the current module is the entry point of the current process, or undefined if the module was loaded by something that is not a CommonJS module (E.G.: REPL or import).
module.path#
- Type:
<string>
The directory name of the module. This is usually the same as the path.dirname() of the module.id.
module.paths#
- Type:
<string[]>
The search paths for the module.
module.require(id)#
The module.require() method provides a way to load a module as if require() was called from the original module.
In order to do this, it is necessary to get a reference to the module object. Since require() returns the module.exports, and the module is typically only available within a specific module's code, it must be explicitly exported in order to be used.
The Module object#
This section was moved to Modules: module core module.
Source map v3 support#
This section was moved to Modules: module core module.
Modules: ECMAScript modules#
Stability: 2 - Stable
Introduction#
ECMAScript modules are the official standard format to package JavaScript code for reuse. Modules are defined using a variety of import and export statements.
The following example of an ES module exports a function:
// addTwo.mjs
function addTwo(num) {
return num + 2;
}
export { addTwo };
The following example of an ES module imports the function from addTwo.mjs:
// app.mjs
import { addTwo } from './addTwo.mjs';
// Prints: 6
console.log(addTwo(4));
Node.js fully supports ECMAScript modules as they are currently specified and provides interoperability between them and its original module format, CommonJS.
Enabling#
Node.js has two module systems: CommonJS modules and ECMAScript modules.
Authors can tell Node.js to interpret JavaScript as an ES module via the .mjs file extension, the package.json "type" field with a value "module", or the --input-type flag with a value of "module". These are explicit markers of code being intended to run as an ES module.
Inversely, authors can explicitly tell Node.js to interpret JavaScript as CommonJS via the .cjs file extension, the package.json "type" field with a value "commonjs", or the --input-type flag with a value of "commonjs".
When code lacks explicit markers for either module system, Node.js will inspect the source code of a module to look for ES module syntax. If such syntax is found, Node.js will run the code as an ES module; otherwise it will run the module as CommonJS. See Determining module system for more details.
Packages#
This section was moved to Modules: Packages.
import Specifiers#
Terminology#
The specifier of an import statement is the string after the from keyword, e.g. 'node:path' in import { sep } from 'node:path'. Specifiers are also used in export from statements, and as the argument to an import() expression.
There are three types of specifiers:
Relative specifiers like
'./startup.js'or'../config.mjs'. They refer to a path relative to the location of the importing file. The file extension is always necessary for these.Bare specifiers like
'some-package'or'some-package/shuffle'. They can refer to the main entry point of a package by the package name, or a specific feature module within a package prefixed by the package name as per the examples respectively. Including the file extension is only necessary for packages without an"exports"field.Absolute specifiers like
'file:///opt/nodejs/config.js'. They refer directly and explicitly to a full path.
Bare specifier resolutions are handled by the Node.js module resolution and loading algorithm. All other specifier resolutions are always only resolved with the standard relative URL resolution semantics.
Like in CommonJS, module files within packages can be accessed by appending a path to the package name unless the package's package.json contains an "exports" field, in which case files within packages can only be accessed via the paths defined in "exports".
For details on these package resolution rules that apply to bare specifiers in the Node.js module resolution, see the packages documentation.
Mandatory file extensions#
A file extension must be provided when using the import keyword to resolve relative or absolute specifiers. Directory indexes (e.g. './startup/index.js') must also be fully specified.
This behavior matches how import behaves in browser environments, assuming a typically configured server.
URLs#
ES modules are resolved and cached as URLs. This means that special characters must be percent-encoded, such as # with %23 and ? with %3F.
file:, node:, and data: URL schemes are supported. A specifier like 'https://example.com/app.js' is not supported natively in Node.js unless using a custom HTTPS loader.
file: URLs#
Modules are loaded multiple times if the import specifier used to resolve them has a different query or fragment.
import './foo.mjs?query=1'; // loads ./foo.mjs with query of "?query=1"
import './foo.mjs?query=2'; // loads ./foo.mjs with query of "?query=2"
The volume root may be referenced via /, //, or file:///. Given the differences between URL and path resolution (such as percent encoding details), it is recommended to use url.pathToFileURL when importing a path.
data: imports#
data: URLs are supported for importing with the following MIME types:
text/javascriptfor ES modulesapplication/jsonfor JSONapplication/wasmfor Wasm
import 'data:text/javascript,console.log("hello!");';
import _ from 'data:application/json,"world!"' with { type: 'json' };
data: URLs only resolve bare specifiers for builtin modules and absolute specifiers. Resolving relative specifiers does not work because data: is not a special scheme. For example, attempting to load ./foo from data:text/javascript,import "./foo"; fails to resolve because there is no concept of relative resolution for data: URLs.
node: imports#
node: URLs are supported as an alternative means to load Node.js builtin modules. This URL scheme allows for builtin modules to be referenced by valid absolute URL strings.
import fs from 'node:fs/promises';
Import attributes#
Import attributes are an inline syntax for module import statements to pass on more information alongside the module specifier.
import fooData from './foo.json' with { type: 'json' };
const { default: barData } =
await import('./bar.json', { with: { type: 'json' } });
Node.js only supports the type attribute, for which it supports the following values:
Attribute type | Needed for |
|---|---|
'json' | JSON modules |
The type: 'json' attribute is mandatory when importing JSON modules.
Built-in modules#
Built-in modules provide named exports of their public API. A default export is also provided which is the value of the CommonJS exports. The default export can be used for, among other things, modifying the named exports. Named exports of built-in modules are updated only by calling module.syncBuiltinESMExports().
import EventEmitter from 'node:events';
const e = new EventEmitter();
import { readFile } from 'node:fs';
readFile('./foo.txt', (err, source) => {
if (err) {
console.error(err);
} else {
console.log(source);
}
});
import fs, { readFileSync } from 'node:fs';
import { syncBuiltinESMExports } from 'node:module';
import { Buffer } from 'node:buffer';
fs.readFileSync = () => Buffer.from('Hello, ESM');
syncBuiltinESMExports();
fs.readFileSync === readFileSync;
When importing built-in modules, all the named exports (i.e. properties of the module exports object) are populated even if they are not individually accessed. This can make initial imports of built-in modules slightly slower compared to loading them with
require()orprocess.getBuiltinModule(), where the module exports object is evaluated immediately, but some of its properties may only be initialized when first accessed individually.
import() expressions#
Dynamic import() provides an asynchronous way to import modules. It is supported in both CommonJS and ES modules, and can be used to load both CommonJS and ES modules.
import.meta#
- Type:
<Object>
The import.meta meta property is an Object that contains the following properties. It is only supported in ES modules.
import.meta.dirname#
- Type:
<string>The directory name of the current module.
This is the same as the path.dirname() of the import.meta.filename.
Caveat: only present on
file:modules.
import.meta.filename#
- Type:
<string>The full absolute path and filename of the current module, with symlinks resolved.
This is the same as the url.fileURLToPath() of the import.meta.url.
Caveat only local modules support this property. Modules not using the
file:protocol will not provide it.
import.meta.url#
- Type:
<string>The absolutefile:URL of the module.
This is defined exactly the same as it is in browsers providing the URL of the current module file.
This enables useful patterns such as relative file loading:
import { readFileSync } from 'node:fs';
const buffer = readFileSync(new URL('./data.proto', import.meta.url));
import.meta.main#
Stability: 1.0 - Early development
- Type:
<boolean>truewhen the current module is the entry point of the current process;falseotherwise.
Equivalent to require.main === module in CommonJS.
Analogous to Python's __name__ == "__main__".
export function foo() {
return 'Hello, world';
}
function main() {
const message = foo();
console.log(message);
}
if (import.meta.main) main();
// `foo` can be imported from another module without possible side-effects from `main`
import.meta.resolve(specifier)#
Stability: 1.2 - Release candidate
specifier<string>The module specifier to resolve relative to the current module.- Returns:
<string>The absolute URL string that the specifier would resolve to.
import.meta.resolve is a module-relative resolution function scoped to each module, returning the URL string.
const dependencyAsset = import.meta.resolve('component-lib/asset.css');
// file:///app/node_modules/component-lib/asset.css
import.meta.resolve('./dep.js');
// file:///app/dep.js
All features of the Node.js module resolution are supported. Dependency resolutions are subject to the permitted exports resolutions within the package.
Caveats:
- This can result in synchronous file-system operations, which can impact performance similarly to
require.resolve. - This feature is not available within custom loaders (it would create a deadlock).
Non-standard API:
When using the --experimental-import-meta-resolve flag, that function accepts a second argument:
Interoperability with CommonJS#
import statements#
An import statement can reference an ES module or a CommonJS module. import statements are permitted only in ES modules, but dynamic import() expressions are supported in CommonJS for loading ES modules.
When importing CommonJS modules, the module.exports object is provided as the default export. Named exports may be available, provided by static analysis as a convenience for better ecosystem compatibility.
require#
The CommonJS module require currently only supports loading synchronous ES modules (that is, ES modules that do not use top-level await).
See Loading ECMAScript modules using require() for details.
CommonJS Namespaces#
CommonJS modules consist of a module.exports object which can be of any type.
To support this, when importing CommonJS from an ECMAScript module, a namespace wrapper for the CommonJS module is constructed, which always provides a default export key pointing to the CommonJS module.exports value.
In addition, a heuristic static analysis is performed against the source text of the CommonJS module to get a best-effort static list of exports to provide on the namespace from values on module.exports. This is necessary since these namespaces must be constructed prior to the evaluation of the CJS module.
These CommonJS namespace objects also provide the default export as a 'module.exports' named export, in order to unambiguously indicate that their representation in CommonJS uses this value, and not the namespace value. This mirrors the semantics of the handling of the 'module.exports' export name in require(esm) interop support.
When importing a CommonJS module, it can be reliably imported using the ES module default import or its corresponding sugar syntax:
import { default as cjs } from 'cjs';
// Identical to the above
import cjsSugar from 'cjs';
console.log(cjs);
console.log(cjs === cjsSugar);
// Prints:
// <module.exports>
// true
This Module Namespace Exotic Object can be directly observed either when using import * as m from 'cjs' or a dynamic import:
import * as m from 'cjs';
console.log(m);
console.log(m === await import('cjs'));
// Prints:
// [Module] { default: <module.exports>, 'module.exports': <module.exports> }
// true
For better compatibility with existing usage in the JS ecosystem, Node.js in addition attempts to determine the CommonJS named exports of every imported CommonJS module to provide them as separate ES module exports using a static analysis process.
For example, consider a CommonJS module written:
// cjs.cjs
exports.name = 'exported';
The preceding module supports named imports in ES modules:
import { name } from './cjs.cjs';
console.log(name);
// Prints: 'exported'
import cjs from './cjs.cjs';
console.log(cjs);
// Prints: { name: 'exported' }
import * as m from './cjs.cjs';
console.log(m);
// Prints:
// [Module] {
// default: { name: 'exported' },
// 'module.exports': { name: 'exported' },
// name: 'exported'
// }
As can be seen from the last example of the Module Namespace Exotic Object being logged, the name export is copied off of the module.exports object and set directly on the ES module namespace when the module is imported.
Live binding updates or new exports added to module.exports are not detected for these named exports.
The detection of named exports is based on common syntax patterns but does not always correctly detect named exports. In these cases, using the default import form described above can be a better option.
Named exports detection covers many common export patterns, reexport patterns and build tool and transpiler outputs. See merve for the exact semantics implemented.
Differences between ES modules and CommonJS#
No require, exports, or module.exports#
In most cases, the ES module import can be used to load CommonJS modules.
If needed, a require function can be constructed within an ES module using module.createRequire().
No __filename or __dirname#
These CommonJS variables are not available in ES modules.
__filename and __dirname use cases can be replicated via import.meta.filename and import.meta.dirname.
No Addon Loading#
Addons are not currently supported with ES module imports.
They can instead be loaded with module.createRequire() or process.dlopen.
No require.main#
To replace require.main === module, there is the import.meta.main API.
No require.resolve#
Relative resolution can be handled via new URL('./local', import.meta.url).
For a complete require.resolve replacement, there is the import.meta.resolve API.
Alternatively module.createRequire() can be used.
No NODE_PATH#
NODE_PATH is not part of resolving import specifiers. Please use symlinks if this behavior is desired.
No require.extensions#
require.extensions is not used by import. Module customization hooks can provide a replacement.
No require.cache#
require.cache is not used by import as the ES module loader has its own separate cache.
JSON modules#
JSON files can be referenced by import:
import packageConfig from './package.json' with { type: 'json' };
The with { type: 'json' } syntax is mandatory; see Import Attributes.
The imported JSON only exposes a default export. There is no support for named exports. A cache entry is created in the CommonJS cache to avoid duplication. The same object is returned in CommonJS if the JSON module has already been imported from the same path.
Wasm modules#
Importing both WebAssembly module instances and WebAssembly source phase imports is supported.
Both of these integrations are in line with the ES Module Integration Proposal for WebAssembly.
Wasm Source Phase Imports#
Stability: 1.2 - Release candidate
The Source Phase Imports proposal allows the import source keyword combination to import a WebAssembly.Module object directly, instead of getting a module instance already instantiated with its dependencies.
This is useful when needing custom instantiations for Wasm, while still resolving and loading it through the ES module integration.
For example, to create multiple instances of a module, or to pass custom imports into a new instance of library.wasm:
import source libraryModule from './library.wasm';
const instance1 = await WebAssembly.instantiate(libraryModule, importObject1);
const instance2 = await WebAssembly.instantiate(libraryModule, importObject2);
In addition to the static source phase, there is also a dynamic variant of the source phase via the import.source dynamic phase import syntax:
const dynamicLibrary = await import.source('./library.wasm');
const instance = await WebAssembly.instantiate(dynamicLibrary, importObject);
JavaScript String Builtins#
Stability: 1.2 - Release candidate
When importing WebAssembly modules, the WebAssembly JS String Builtins Proposal is automatically enabled through the ESM Integration. This allows WebAssembly modules to directly use efficient compile-time string builtins from the wasm:js-string namespace.
For example, the following Wasm module exports a string getLength function using the wasm:js-string length builtin:
(module
;; Compile-time import of the string length builtin.
(import "wasm:js-string" "length" (func $string_length (param externref) (result i32)))
;; Define getLength, taking a JS value parameter assumed to be a string,
;; calling string length on it and returning the result.
(func $getLength (param $str externref) (result i32)
local.get $str
call $string_length
)
;; Export the getLength function.
(export "getLength" (func $get_length))
)
import { getLength } from './string-len.wasm';
getLength('foo'); // Returns 3.
Wasm builtins are compile-time imports that are linked during module compilation rather than during instantiation. They do not behave like normal module graph imports and they cannot be inspected via WebAssembly.Module.imports(mod) or virtualized unless recompiling the module using the direct WebAssembly.compile API with string builtins disabled.
Importing a module in the source phase before it has been instantiated will also use the compile-time builtins automatically:
import source mod from './string-len.wasm';
const { exports: { getLength } } = await WebAssembly.instantiate(mod, {});
getLength('foo'); // Also returns 3.
Wasm Instance Phase Imports#
Stability: 1.1 - Active development
Instance imports allow any .wasm files to be imported as normal modules, supporting their module imports in turn.
For example, an index.js containing:
import * as M from './library.wasm';
console.log(M);
executed under:
node index.mjs
would provide the exports interface for the instantiation of library.wasm.
Reserved Wasm Namespaces#
When importing WebAssembly module instances, they cannot use import module names or import/export names that start with reserved prefixes:
wasm-js:- reserved in all module import names, module names and export names.wasm:- reserved in module import names and export names (imported module names are allowed in order to support future builtin polyfills).
Importing a module using the above reserved names will throw a WebAssembly.LinkError.
Top-level await#
The await keyword may be used in the top level body of an ECMAScript module.
Assuming an a.mjs with
export const five = await Promise.resolve(5);
And a b.mjs with
import { five } from './a.mjs';
console.log(five); // Logs `5`
node b.mjs # works
If a top level await expression never resolves, the node process will exit with a 13 status code.
import { spawn } from 'node:child_process';
import { execPath } from 'node:process';
spawn(execPath, [
'--input-type=module',
'--eval',
// Never-resolving Promise:
'await new Promise(() => {})',
]).once('exit', (code) => {
console.log(code); // Logs `13`
});
Loaders#
The former Loaders documentation is now at Modules: Customization hooks.
Resolution and loading algorithm#
Features#
The default resolver has the following properties:
- FileURL-based resolution as is used by ES modules
- Relative and absolute URL resolution
- No default extensions
- No folder mains
- Bare specifier package resolution lookup through node_modules
- Does not fail on unknown extensions or protocols
- Can optionally provide a hint of the format to the loading phase
The default loader has the following properties
- Support for builtin module loading via
node:URLs - Support for "inline" module loading via
data:URLs - Support for
file:module loading - Fails on any other URL protocol
- Fails on unknown extensions for
file:loading (supports only.cjs,.js, and.mjs)
Resolution algorithm#
The algorithm to load an ES module specifier is given through the ESM_RESOLVE method below. It returns the resolved URL for a module specifier relative to a parentURL.
The resolution algorithm determines the full resolved URL for a module load, along with its suggested module format. The resolution algorithm does not determine whether the resolved URL protocol can be loaded, or whether the file extensions are permitted, instead these validations are applied by Node.js during the load phase (for example, if it was asked to load a URL that has a protocol that is not file:, data: or node:.
The algorithm also tries to determine the format of the file based on the extension (see ESM_FILE_FORMAT algorithm below). If it does not recognize the file extension (eg if it is not .mjs, .cjs, or .json), then a format of undefined is returned, which will throw during the load phase.
The algorithm to determine the module format of a resolved URL is provided by ESM_FILE_FORMAT, which returns the unique module format for any file. The "module" format is returned for an ECMAScript Module, while the "commonjs" format is used to indicate loading through the legacy CommonJS loader. Additional formats such as "addon" can be extended in future updates.
In the following algorithms, all subroutine errors are propagated as errors of these top-level routines unless stated otherwise.
defaultConditions is the conditional environment name array, ["node", "import"].
The resolver can throw the following errors:
- Invalid Module Specifier: Module specifier is an invalid URL, package name or package subpath specifier.
- Invalid Package Configuration: package.json configuration is invalid or contains an invalid configuration.
- Invalid Package Target: Package exports or imports define a target module for the package that is an invalid type or string target.
- Package Path Not Exported: Package exports do not define or permit a target subpath in the package for the given module.
- Package Import Not Defined: Package imports do not define the specifier.
- Module Not Found: The package or module requested does not exist.
- Unsupported Directory Import: The resolved path corresponds to a directory, which is not a supported target for module imports.
Resolution Algorithm Specification#
ESM_RESOLVE(specifier, parentURL)
- Let resolved be undefined.
- If specifier is a valid URL, then
- Set resolved to the result of parsing and reserializing specifier as a URL.
- Otherwise, if specifier starts with "/", "./", or "../", then
- Set resolved to the URL resolution of specifier relative to parentURL.
- Otherwise, if specifier starts with "#", then
- Set resolved to the result of PACKAGE_IMPORTS_RESOLVE(specifier, parentURL, defaultConditions).
- Otherwise,
- Note: specifier is now a bare specifier.
- Set resolved the result of PACKAGE_RESOLVE(specifier, parentURL).
- Let format be undefined.
- If resolved is a "file:" URL, then
- If resolved contains any percent encodings of "/" or "\" ("%2F" and "%5C" respectively), then
- Throw an Invalid Module Specifier error.
- If the file at resolved is a directory, then
- Throw an Unsupported Directory Import error.
- If the file at resolved does not exist, then
- Throw a Module Not Found error.
- Set resolved to the real path of resolved, maintaining the same URL querystring and fragment components.
- Set format to the result of ESM_FILE_FORMAT(resolved).
- Otherwise,
- Set format the module format of the content type associated with the URL resolved.
- Return format and resolved to the loading phase
PACKAGE_RESOLVE(packageSpecifier, parentURL)
- Let packageName be undefined.
- If packageSpecifier is an empty string, then
- Throw an Invalid Module Specifier error.
- If packageSpecifier is a Node.js builtin module name, then
- Return the string "node:" concatenated with packageSpecifier.
- If packageSpecifier does not start with "@", then
- Set packageName to the substring of packageSpecifier until the first "/" separator or the end of the string.
- Otherwise,
- If packageSpecifier does not contain a "/" separator, then
- Throw an Invalid Module Specifier error.
- Set packageName to the substring of packageSpecifier until the second "/" separator or the end of the string.
- If packageName starts with "." or contains "\" or "%", then
- Throw an Invalid Module Specifier error.
- Let packageSubpath be "." concatenated with the substring of packageSpecifier from the position at the length of packageName.
- Let selfUrl be the result of PACKAGE_SELF_RESOLVE(packageName, packageSubpath, parentURL).
- If selfUrl is not undefined, return selfUrl.
- While parentURL is not the file system root,
- Let packageURL be the URL resolution of "node_modules/" concatenated with packageName, relative to parentURL.
- Set parentURL to the parent folder URL of parentURL.
- If the folder at packageURL does not exist, then
- Continue the next loop iteration.
- Let pjson be the result of READ_PACKAGE_JSON(packageURL).
- If pjson is not null and pjson.exports is not null or undefined, then
- Return the result of PACKAGE_EXPORTS_RESOLVE(packageURL, packageSubpath, pjson.exports, defaultConditions).
- Otherwise, if packageSubpath is equal to ".", then
- If pjson.main is a string, then
- Return the URL resolution of main in packageURL.
- Otherwise,
- Return the URL resolution of packageSubpath in packageURL.
- Throw a Module Not Found error.
PACKAGE_SELF_RESOLVE(packageName, packageSubpath, parentURL)
- Let packageURL be the result of LOOKUP_PACKAGE_SCOPE(parentURL).
- If packageURL is null, then
- Return undefined.
- Let pjson be the result of READ_PACKAGE_JSON(packageURL).
- If pjson is null or if pjson.exports is null or undefined, then
- Return undefined.
- If pjson.name is equal to packageName, then
- Return the result of PACKAGE_EXPORTS_RESOLVE(packageURL, packageSubpath, pjson.exports, defaultConditions).
- Otherwise, return undefined.
PACKAGE_EXPORTS_RESOLVE(packageURL, subpath, exports, conditions)
Note: This function is directly invoked by the CommonJS resolution algorithm.
- If exports is an Object with both a key starting with "." and a key not starting with ".", throw an Invalid Package Configuration error.
- If subpath is equal to ".", then
- Let mainExport be undefined.
- If exports is a String or Array, or an Object containing no keys starting with ".", then
- Set mainExport to exports.
- Otherwise if exports is an Object containing a "." property, then
- Set mainExport to exports["."].
- If mainExport is not undefined, then
- Let resolved be the result of PACKAGE_TARGET_RESOLVE( packageURL, mainExport, null, false, conditions).
- If resolved is not null or undefined, return resolved.
- Otherwise, if exports is an Object and all keys of exports start with ".", then
- Assert: subpath begins with "./".
- Let resolved be the result of PACKAGE_IMPORTS_EXPORTS_RESOLVE( subpath, exports, packageURL, false, conditions).
- If resolved is not null or undefined, return resolved.
- Throw a Package Path Not Exported error.
PACKAGE_IMPORTS_RESOLVE(specifier, parentURL, conditions)
Note: This function is directly invoked by the CommonJS resolution algorithm.
- Assert: specifier begins with "#".
- If specifier is exactly equal to "#", then
- Throw an Invalid Module Specifier error.
- Let packageURL be the result of LOOKUP_PACKAGE_SCOPE(parentURL).
- If packageURL is not null, then
- Let pjson be the result of READ_PACKAGE_JSON(packageURL).
- If pjson.imports is a non-null Object, then
- Let resolved be the result of PACKAGE_IMPORTS_EXPORTS_RESOLVE( specifier, pjson.imports, packageURL, true, conditions).
- If resolved is not null or undefined, return resolved.
- Throw a Package Import Not Defined error.
PACKAGE_IMPORTS_EXPORTS_RESOLVE(matchKey, matchObj, packageURL, isImports, conditions)
- If matchKey ends in "/", then
- Throw an Invalid Module Specifier error.
- If matchKey is a key of matchObj and does not contain "*", then
- Let target be the value of matchObj[matchKey].
- Return the result of PACKAGE_TARGET_RESOLVE(packageURL, target, null, isImports, conditions).
- Let expansionKeys be the list of keys of matchObj containing only a single "*", sorted by the sorting function PATTERN_KEY_COMPARE which orders in descending order of specificity.
- For each key expansionKey in expansionKeys, do
- Let patternBase be the substring of expansionKey up to but excluding the first "*" character.
- If matchKey starts with but is not equal to patternBase, then
- Let patternTrailer be the substring of expansionKey from the index after the first "*" character.
- If patternTrailer has zero length, or if matchKey ends with patternTrailer and the length of matchKey is greater than or equal to the length of expansionKey, then
- Let target be the value of matchObj[expansionKey].
- Let patternMatch be the substring of matchKey starting at the index of the length of patternBase up to the length of matchKey minus the length of patternTrailer.
- Return the result of PACKAGE_TARGET_RESOLVE(packageURL, target, patternMatch, isImports, conditions).
- Return null.
PATTERN_KEY_COMPARE(keyA, keyB)
- Assert: keyA contains only a single "*".
- Assert: keyB contains only a single "*".
- Let baseLengthA be the index of "*" in keyA.
- Let baseLengthB be the index of "*" in keyB.
- If baseLengthA is greater than baseLengthB, return -1.
- If baseLengthB is greater than baseLengthA, return 1.
- If the length of keyA is greater than the length of keyB, return -1.
- If the length of keyB is greater than the length of keyA, return 1.
- Return 0.
PACKAGE_TARGET_RESOLVE(packageURL, target, patternMatch, isImports, conditions)
- If target is a String, then
- If target does not start with "./", then
- If isImports is false, or if target starts with "../" or "/", or if target is a valid URL, then
- Throw an Invalid Package Target error.
- If patternMatch is a String, then
- Return PACKAGE_RESOLVE(target with every instance of "*" replaced by patternMatch, packageURL + "/").
- Return PACKAGE_RESOLVE(target, packageURL + "/").
- If target split on "/" or "\" contains any "", ".", "..", or "node_modules" segments after the first "." segment, case insensitive and including percent encoded variants, throw an Invalid Package Target error.
- Let resolvedTarget be the URL resolution of the concatenation of packageURL and target.
- Assert: packageURL is contained in resolvedTarget.
- If patternMatch is null, then
- Return resolvedTarget.
- If patternMatch split on "/" or "\" contains any "", ".", "..", or "node_modules" segments, case insensitive and including percent encoded variants, throw an Invalid Module Specifier error.
- Return the URL resolution of resolvedTarget with every instance of "*" replaced with patternMatch.
- Otherwise, if target is a non-null Object, then
- If target contains any index property keys, as defined in ECMA-262 6.1.7 Array Index, throw an Invalid Package Configuration error.
- For each property p of target, in object insertion order as,
- If p equals "default" or conditions contains an entry for p, then
- Let targetValue be the value of the p property in target.
- Let resolved be the result of PACKAGE_TARGET_RESOLVE( packageURL, targetValue, patternMatch, isImports, conditions).
- If resolved is equal to undefined, continue the loop.
- Return resolved.
- Return undefined.
- Otherwise, if target is an Array, then
- If _target.length is zero, return null.
- For each item targetValue in target, do
- Let resolved be the result of PACKAGE_TARGET_RESOLVE( packageURL, targetValue, patternMatch, isImports, conditions), continuing the loop on any Invalid Package Target error.
- If resolved is undefined, continue the loop.
- Return resolved.
- Return or throw the last fallback resolution null return or error.
- Otherwise, if target is null, return null.
- Otherwise throw an Invalid Package Target error.
ESM_FILE_FORMAT(url)
- Assert: url corresponds to an existing file.
- If url ends in ".mjs", then
- Return "module".
- If url ends in ".cjs", then
- Return "commonjs".
- If url ends in ".json", then
- Return "json".
- If url ends in ".wasm", then
- Return "wasm".
- If
--experimental-addon-modulesis enabled and url ends in ".node", then
- Return "addon".
- Let packageURL be the result of LOOKUP_PACKAGE_SCOPE(url).
- Let pjson be the result of READ_PACKAGE_JSON(packageURL).
- Let packageType be null.
- If pjson?.type is "module" or "commonjs", then
- Set packageType to pjson.type.
- If url ends in ".js", then
- If packageType is not null, then
- Return packageType.
- If the result of DETECT_MODULE_SYNTAX(source) is true, then
- Return "module".
- Return "commonjs".
- If url does not have any extension, then
- If packageType is "module" and the file at url contains the "application/wasm" content type header for a WebAssembly module, then
- Return "wasm".
- If packageType is not null, then
- Return packageType.
- If the result of DETECT_MODULE_SYNTAX(source) is true, then
- Return "module".
- Return "commonjs".
- Return undefined (will throw during load phase).
LOOKUP_PACKAGE_SCOPE(url)
- Let scopeURL be url.
- While scopeURL is not the file system root,
- Set scopeURL to the parent URL of scopeURL.
- If scopeURL ends in a "node_modules" path segment, return null.
- Let pjsonURL be the resolution of "package.json" within scopeURL.
- if the file at pjsonURL exists, then
- Return scopeURL.
- Return null.
READ_PACKAGE_JSON(packageURL)
- Let pjsonURL be the resolution of "package.json" within packageURL.
- If the file at pjsonURL does not exist, then
- Return null.
- If the file at packageURL does not parse as valid JSON, then
- Throw an Invalid Package Configuration error.
- Return the parsed JSON source of the file at pjsonURL.
DETECT_MODULE_SYNTAX(source)
- Parse source as an ECMAScript module.
- If the parse is successful, then
- If source contains top-level
await, staticimportorexportstatements, orimport.meta, return true.- If source contains a top-level lexical declaration (
const,let, orclass) of any of the CommonJS wrapper variables (require,exports,module,__filename, or__dirname) then return true.- Return false.
Customizing ESM specifier resolution algorithm#
Module customization hooks provide a mechanism for customizing the ESM specifier resolution algorithm. An example that provides CommonJS-style resolution for ESM specifiers is commonjs-extension-resolution-loader.
Modules: Packages#
Introduction#
A package is a folder tree described by a package.json file. The package consists of the folder containing the package.json file and all subfolders until the next folder containing another package.json file, or a folder named node_modules.
This page provides guidance for package authors writing package.json files along with a reference for the package.json fields defined by Node.js.
Determining module system#
Introduction#
Node.js will treat the following as ES modules when passed to node as the initial input, or when referenced by import statements or import() expressions:
Files with an
.mjsextension.Files with a
.jsextension when the nearest parentpackage.jsonfile contains a top-level"type"field with a value of"module".Strings passed in as an argument to
--eval, or piped tonodeviaSTDIN, with the flag--input-type=module.Code containing syntax only successfully parsed as ES modules, such as
importorexportstatements orimport.meta, with no explicit marker of how it should be interpreted. Explicit markers are.mjsor.cjsextensions,package.json"type"fields with either"module"or"commonjs"values, or the--input-typeflag. Dynamicimport()expressions are supported in either CommonJS or ES modules and would not force a file to be treated as an ES module. See Syntax detection.
Node.js will treat the following as CommonJS when passed to node as the initial input, or when referenced by import statements or import() expressions:
Files with a
.cjsextension.Files with a
.jsextension when the nearest parentpackage.jsonfile contains a top-level field"type"with a value of"commonjs".Strings passed in as an argument to
--evalor--print, or piped tonodeviaSTDIN, with the flag--input-type=commonjs.Files with a
.jsextension with no parentpackage.jsonfile or where the nearest parentpackage.jsonfile lacks atypefield, and where the code can evaluate successfully as CommonJS. In other words, Node.js tries to run such "ambiguous" files as CommonJS first, and will retry evaluating them as ES modules if the evaluation as CommonJS fails because the parser found ES module syntax.
Writing ES module syntax in "ambiguous" files incurs a performance cost, and therefore it is encouraged that authors be explicit wherever possible. In particular, package authors should always include the "type" field in their package.json files, even in packages where all sources are CommonJS. Being explicit about the type of the package will future-proof the package in case the default type of Node.js ever changes, and it will also make things easier for build tools and loaders to determine how the files in the package should be interpreted.
Syntax detection#
Stability: 1.2 - Release candidate
Node.js will inspect the source code of ambiguous input to determine whether it contains ES module syntax; if such syntax is detected, the input will be treated as an ES module.
Ambiguous input is defined as:
- Files with a
.jsextension or no extension; and either no controllingpackage.jsonfile or one that lacks atypefield. - String input (
--evalorSTDIN) when--input-typeis not specified.
ES module syntax is defined as syntax that would throw when evaluated as CommonJS. This includes the following:
importstatements (but notimport()expressions, which are valid in CommonJS).exportstatements.import.metareferences.awaitat the top level of a module.- Lexical redeclarations of the CommonJS wrapper variables (
require,module,exports,__dirname,__filename).
Module resolution and loading#
Node.js has two types of module resolution and loading, chosen based on how the module is requested.
When a module is requested via require() (available by default in CommonJS modules, and can be dynamically generated using createRequire() in both CommonJS and ES Modules):
- Resolution:
- The resolution initiated by
require()supports folders as modules. - When resolving a specifier, if no exact match is found,
require()will try to add extensions (.js,.json, and finally.node) and then attempt to resolve folders as modules. - It does not support URLs as specifiers by default.
- The resolution initiated by
- Loading:
.jsonfiles are treated as JSON text files..nodefiles are interpreted as compiled addon modules loaded withprocess.dlopen()..ts,.mtsand.ctsfiles are treated as TypeScript text files.- Files with any other extension, or without extensions, are treated as JavaScript text files.
require()can only be used to load ECMAScript modules from CommonJS modules if the ECMAScript module and its dependencies are synchronous (i.e. they do not contain top-levelawait).
When a module is requested via static import statements (only available in ES Modules) or import() expressions (available in both CommonJS and ES Modules):
- Resolution:
- The resolution of
import/import()does not support folders as modules, directory indexes (e.g.'./startup/index.js') must be fully specified. - It does not perform extension searching. A file extension must be provided when the specifier is a relative or absolute file URL.
- It supports
file://anddata:URLs as specifiers by default.
- The resolution of
- Loading:
.jsonfiles are treated as JSON text files. When importing JSON modules, an import type attribute is required (e.g.import json from './data.json' with { type: 'json' })..nodefiles are interpreted as compiled addon modules loaded withprocess.dlopen(), if--experimental-addon-modulesis enabled..ts,.mtsand.ctsfiles are treated as TypeScript text files.- It accepts only
.js,.mjs, and.cjsextensions for JavaScript text files. .wasmfiles are treated as WebAssembly modules.- Any other file extensions will result in a
ERR_UNKNOWN_FILE_EXTENSIONerror. Additional file extensions can be facilitated via customization hooks. import/import()can be used to load JavaScript CommonJS modules. Such modules are passed through merve to try to identify named exports, which are available if they can be determined through static analysis.
Regardless of how a module is requested, the resolution and loading process can be customized using customization hooks.
package.json and file extensions#
Within a package, the package.json "type" field defines how Node.js should interpret .js files. If a package.json file does not have a "type" field, .js files are treated as CommonJS.
A package.json "type" value of "module" tells Node.js to interpret .js files within that package as using ES module syntax.
The "type" field applies not only to initial entry points (node my-app.js) but also to files referenced by import statements and import() expressions.
// my-app.js, treated as an ES module because there is a package.json
// file in the same folder with "type": "module".
import './startup/init.js';
// Loaded as ES module since ./startup contains no package.json file,
// and therefore inherits the "type" value from one level up.
import 'commonjs-package';
// Loaded as CommonJS since ./node_modules/commonjs-package/package.json
// lacks a "type" field or contains "type": "commonjs".
import './node_modules/commonjs-package/index.js';
// Loaded as CommonJS since ./node_modules/commonjs-package/package.json
// lacks a "type" field or contains "type": "commonjs".
Files ending with .mjs are always loaded as ES modules regardless of the nearest parent package.json.
Files ending with .cjs are always loaded as CommonJS regardless of the nearest parent package.json.
import './legacy-file.cjs';
// Loaded as CommonJS since .cjs is always loaded as CommonJS.
import 'commonjs-package/src/index.mjs';
// Loaded as ES module since .mjs is always loaded as ES module.
The .mjs and .cjs extensions can be used to mix types within the same package:
Within a
"type": "module"package, Node.js can be instructed to interpret a particular file as CommonJS by naming it with a.cjsextension (since both.jsand.mjsfiles are treated as ES modules within a"module"package).Within a
"type": "commonjs"package, Node.js can be instructed to interpret a particular file as an ES module by naming it with an.mjsextension (since both.jsand.cjsfiles are treated as CommonJS within a"commonjs"package).
--input-type flag#
Strings passed in as an argument to --eval (or -e), or piped to node via STDIN, are treated as ES modules when the --input-type=module flag is set.
node --input-type=module --eval "import { sep } from 'node:path'; console.log(sep);"
echo "import { sep } from 'node:path'; console.log(sep);" | node --input-type=module
For completeness there is also --input-type=commonjs, for explicitly running string input as CommonJS. This is the default behavior if --input-type is unspecified.
Package entry points#
In a package's package.json file, two fields can define entry points for a package: "main" and "exports". Both fields apply to both ES module and CommonJS module entry points.
The "main" field is supported in all versions of Node.js, but its capabilities are limited: it only defines the main entry point of the package.
The "exports" provides a modern alternative to "main" allowing multiple entry points to be defined, conditional entry resolution support between environments, and preventing any other entry points besides those defined in "exports". This encapsulation allows module authors to clearly define the public interface for their package.
For new packages targeting the currently supported versions of Node.js, the "exports" field is recommended. For packages supporting Node.js 10 and below, the "main" field is required. If both "exports" and "main" are defined, the "exports" field takes precedence over "main" in supported versions of Node.js.
Conditional exports can be used within "exports" to define different package entry points per environment, including whether the package is referenced via require or via import. For more information about supporting both CommonJS and ES modules in a single package please consult the dual CommonJS/ES module packages section.
Existing packages introducing the "exports" field will prevent consumers of the package from using any entry points that are not defined, including the package.json (e.g. require('your-package/package.json')). This will likely be a breaking change.
To make the introduction of "exports" non-breaking, ensure that every previously supported entry point is exported. It is best to explicitly specify entry points so that the package's public API is well-defined. For example, a project that previously exported main, lib, feature, and the package.json could use the following package.exports:
{
"name": "my-package",
"exports": {
".": "./lib/index.js",
"./lib": "./lib/index.js",
"./lib/index": "./lib/index.js",
"./lib/index.js": "./lib/index.js",
"./feature": "./feature/index.js",
"./feature/index": "./feature/index.js",
"./feature/index.js": "./feature/index.js",
"./package.json": "./package.json"
}
}
Alternatively a project could choose to export entire folders both with and without extensioned subpaths using export patterns:
{
"name": "my-package",
"exports": {
".": "./lib/index.js",
"./lib": "./lib/index.js",
"./lib/*": "./lib/*.js",
"./lib/*.js": "./lib/*.js",
"./feature": "./feature/index.js",
"./feature/*": "./feature/*.js",
"./feature/*.js": "./feature/*.js",
"./package.json": "./package.json"
}
}
With the above providing backwards-compatibility for any minor package versions, a future major change for the package can then properly restrict the exports to only the specific feature exports exposed:
{
"name": "my-package",
"exports": {
".": "./lib/index.js",
"./feature/*.js": "./feature/*.js",
"./feature/internal/*": null
}
}
Main entry point export#
When writing a new package, it is recommended to use the "exports" field:
{
"exports": "./index.js"
}
When the "exports" field is defined, all subpaths of the package are encapsulated and no longer available to importers. For example, require('pkg/subpath.js') throws an ERR_PACKAGE_PATH_NOT_EXPORTED error.
This encapsulation of exports provides more reliable guarantees about package interfaces for tools and when handling semver upgrades for a package. It is not a strong encapsulation since a direct require of any absolute subpath of the package such as require('/path/to/node_modules/pkg/subpath.js') will still load subpath.js.
All currently supported versions of Node.js and modern build tools support the "exports" field. For projects using an older version of Node.js or a related build tool, compatibility can be achieved by including the "main" field alongside "exports" pointing to the same module:
{
"main": "./index.js",
"exports": "./index.js"
}
Subpath exports#
When using the "exports" field, custom subpaths can be defined along with the main entry point by treating the main entry point as the "." subpath:
{
"exports": {
".": "./index.js",
"./submodule.js": "./src/submodule.js"
}
}
Now only the defined subpath in "exports" can be imported by a consumer:
import submodule from 'es-module-package/submodule.js';
// Loads ./node_modules/es-module-package/src/submodule.js
While other subpaths will error:
import submodule from 'es-module-package/private-module.js';
// Throws ERR_PACKAGE_PATH_NOT_EXPORTED
Extensions in subpaths#
Package authors should provide either extensioned (import 'pkg/subpath.js') or extensionless (import 'pkg/subpath') subpaths in their exports. This ensures that there is only one subpath for each exported module so that all dependents import the same consistent specifier, keeping the package contract clear for consumers and simplifying package subpath completions.
Traditionally, packages tended to use the extensionless style, which has the benefits of readability and of masking the true path of the file within the package.
With import maps now providing a standard for package resolution in browsers and other JavaScript runtimes, using the extensionless style can result in bloated import map definitions. Explicit file extensions can avoid this issue by enabling the import map to utilize a packages folder mapping to map multiple subpaths where possible instead of a separate map entry per package subpath export. This also mirrors the requirement of using the full specifier path in relative and absolute import specifiers.
Path Rules and Validation for Export Targets#
When defining paths as targets in the "exports" field, Node.js enforces several rules to ensure security, predictability, and proper encapsulation. Understanding these rules is crucial for authors publishing packages.
Targets must be relative URLs#
All target paths in the "exports" map (the values associated with export keys) must be relative URL strings starting with ./.
// package.json
{
"name": "my-package",
"exports": {
".": "./dist/main.js", // Correct
"./feature": "./lib/feature.js", // Correct
// "./origin-relative": "/dist/main.js", // Incorrect: Must start with ./
// "./absolute": "file:///dev/null", // Incorrect: Must start with ./
// "./outside": "../common/util.js" // Incorrect: Must start with ./
}
}
Reasons for this behavior include:
- Security: Prevents exporting arbitrary files from outside the package's own directory.
- Encapsulation: Ensures all exported paths are resolved relative to the package root, making the package self-contained.
No path traversal or invalid segments#
Export targets must not resolve to a location outside the package's root directory. Additionally, path segments like . (single dot), .. (double dot), or node_modules (and their URL-encoded equivalents) are generally disallowed within the target string after the initial ./ and in any subpath part substituted into a target pattern.
// package.json
{
"name": "my-package",
"exports": {
// ".": "./dist/../../elsewhere/file.js", // Invalid: path traversal
// ".": "././dist/main.js", // Invalid: contains "." segment
// ".": "./dist/../dist/main.js", // Invalid: contains ".." segment
// "./utils/./helper.js": "./utils/helper.js" // Key has invalid segment
}
}
Exports sugar#
If the "." export is the only export, the "exports" field provides sugar for this case being the direct "exports" field value.
{
"exports": {
".": "./index.js"
}
}
can be written:
{
"exports": "./index.js"
}
Subpath imports#
In addition to the "exports" field, there is a package "imports" field to create private mappings that only apply to import specifiers from within the package itself.
Entries in the "imports" field must always start with # to ensure they are disambiguated from external package specifiers.
For example, the imports field can be used to gain the benefits of conditional exports for internal modules:
// package.json
{
"imports": {
"#dep": {
"node": "dep-node-native",
"default": "./dep-polyfill.js"
}
},
"dependencies": {
"dep-node-native": "^1.0.0"
}
}
where import '#dep' does not get the resolution of the external package dep-node-native (including its exports in turn), and instead gets the local file ./dep-polyfill.js relative to the package in other environments.
Unlike the "exports" field, the "imports" field permits mapping to external packages.
The resolution rules for the imports field are otherwise analogous to the exports field.
Subpath patterns#
For packages with a small number of exports or imports, we recommend explicitly listing each exports subpath entry. But for packages that have large numbers of subpaths, this might cause package.json bloat and maintenance issues.
For these use cases, subpath export patterns can be used instead:
// ./node_modules/es-module-package/package.json
{
"exports": {
"./features/*.js": "./src/features/*.js"
},
"imports": {
"#internal/*.js": "./src/internal/*.js"
}
}
* maps expose nested subpaths as it is a string replacement syntax only.
All instances of * on the right hand side will then be replaced with this value, including if it contains any / separators.
import featureX from 'es-module-package/features/x.js';
// Loads ./node_modules/es-module-package/src/features/x.js
import featureY from 'es-module-package/features/y/y.js';
// Loads ./node_modules/es-module-package/src/features/y/y.js
import internalZ from '#internal/z.js';
// Loads ./src/internal/z.js
This is a direct static matching and replacement without any special handling for file extensions. Including the "*.js" on both sides of the mapping restricts the exposed package exports to only JS files.
The property of exports being statically enumerable is maintained with exports patterns since the individual exports for a package can be determined by treating the right hand side target pattern as a ** glob against the list of files within the package. Because node_modules paths are forbidden in exports targets, this expansion is dependent on only the files of the package itself.
To exclude private subfolders from patterns, null targets can be used:
// ./node_modules/es-module-package/package.json
{
"exports": {
"./features/*.js": "./src/features/*.js",
"./features/private-internal/*": null
}
}
import featureInternal from 'es-module-package/features/private-internal/m.js';
// Throws: ERR_PACKAGE_PATH_NOT_EXPORTED
import featureX from 'es-module-package/features/x.js';
// Loads ./node_modules/es-module-package/src/features/x.js
Conditional exports#
Conditional exports provide a way to map to different paths depending on certain conditions. They are supported for both CommonJS and ES module imports.
For example, a package that wants to provide different ES module exports for require() and import can be written:
// package.json
{
"exports": {
"import": "./index-module.js",
"require": "./index-require.cjs"
},
"type": "module"
}
Node.js implements the following conditions, listed in order from most specific to least specific as conditions should be defined:
"node-addons"- similar to"node"and matches for any Node.js environment. This condition can be used to provide an entry point which uses native C++ addons as opposed to an entry point which is more universal and doesn't rely on native addons. This condition can be disabled via the--no-addonsflag."node"- matches for any Node.js environment. Can be a CommonJS or ES module file. In most cases explicitly calling out the Node.js platform is not necessary."import"- matches when the package is loaded viaimportorimport(), or via any top-level import or resolve operation by the ECMAScript module loader. Applies regardless of the module format of the target file. Always mutually exclusive with"require"."require"- matches when the package is loaded viarequire(). The referenced file should be loadable withrequire()although the condition matches regardless of the module format of the target file. Expected formats include CommonJS, JSON, native addons, and ES modules. Always mutually exclusive with"import"."module-sync"- matches no matter the package is loaded viaimport,import()orrequire(). The format is expected to be ES modules that does not contain top-level await in its module graph - if it does,ERR_REQUIRE_ASYNC_MODULEwill be thrown when the module isrequire()-ed."default"- the generic fallback that always matches. Can be a CommonJS or ES module file. This condition should always come last.
Within the "exports" object, key order is significant. During condition matching, earlier entries have higher priority and take precedence over later entries. The general rule is that conditions should be from most specific to least specific in object order.
Using the "import" and "require" conditions can lead to some hazards, which are further explained in the dual CommonJS/ES module packages section.
The "node-addons" condition can be used to provide an entry point which uses native C++ addons. However, this condition can be disabled via the --no-addons flag. When using "node-addons", it's recommended to treat "default" as an enhancement that provides a more universal entry point, e.g. using WebAssembly instead of a native addon.
Conditional exports can also be extended to exports subpaths, for example:
{
"exports": {
".": "./index.js",
"./feature.js": {
"node": "./feature-node.js",
"default": "./feature.js"
}
}
}
Defines a package where require('pkg/feature.js') and import 'pkg/feature.js' could provide different implementations between Node.js and other JS environments.
When using environment branches, always include a "default" condition where possible. Providing a "default" condition ensures that any unknown JS environments are able to use this universal implementation, which helps avoid these JS environments from having to pretend to be existing environments in order to support packages with conditional exports. For this reason, using "node" and "default" condition branches is usually preferable to using "node" and "browser" condition branches.
Nested conditions#
In addition to direct mappings, Node.js also supports nested condition objects.
For example, to define a package that only has dual mode entry points for use in Node.js but not the browser:
{
"exports": {
"node": {
"import": "./feature-node.mjs",
"require": "./feature-node.cjs"
},
"default": "./feature.mjs"
}
}
Conditions continue to be matched in order as with flat conditions. If a nested condition does not have any mapping it will continue checking the remaining conditions of the parent condition. In this way nested conditions behave analogously to nested JavaScript if statements.
Resolving user conditions#
When running Node.js, custom user conditions can be added with the --conditions flag:
node --conditions=development index.js
which would then resolve the "development" condition in package imports and exports, while resolving the existing "node", "node-addons", "default", "import", and "require" conditions as appropriate.
Any number of custom conditions can be set with repeat flags.
Typical conditions should only contain alphanumerical characters, using ":", "-", or "=" as separators if necessary. Anything else may run into compability issues outside of node.
In node, conditions have very few restrictions, but specifically these include:
- They must contain at least one character.
- They cannot start with "." since they may appear in places that also allow relative paths.
- They cannot contain "," since they may be parsed as a comma-separated list by some CLI tools.
- They cannot be integer property keys like "10" since that can have unexpected effects on property key ordering for JS objects.
Community Conditions Definitions#
Condition strings other than the "import", "require", "node", "module-sync", "node-addons" and "default" conditions implemented in Node.js core are ignored by default.
Other platforms may implement other conditions and user conditions can be enabled in Node.js via the --conditions / -C flag.
Since custom package conditions require clear definitions to ensure correct usage, a list of common known package conditions and their strict definitions is provided below to assist with ecosystem coordination.
"types"- can be used by typing systems to resolve the typing file for the given export. This condition should always be included first."browser"- any web browser environment."development"- can be used to define a development-only environment entry point, for example to provide additional debugging context such as better error messages when running in a development mode. Must always be mutually exclusive with"production"."production"- can be used to define a production environment entry point. Must always be mutually exclusive with"development".
For other runtimes, platform-specific condition key definitions are maintained by the WinterCG in the Runtime Keys proposal specification.
New conditions definitions may be added to this list by creating a pull request to the Node.js documentation for this section. The requirements for listing a new condition definition here are that:
- The definition should be clear and unambiguous for all implementers.
- The use case for why the condition is needed should be clearly justified.
- There should exist sufficient existing implementation usage.
- The condition name should not conflict with another condition definition or condition in wide usage.
- The listing of the condition definition should provide a coordination benefit to the ecosystem that wouldn't otherwise be possible. For example, this would not necessarily be the case for company-specific or application-specific conditions.
- The condition should be such that a Node.js user would expect it to be in Node.js core documentation. The
"types"condition is a good example: It doesn't really belong in the Runtime Keys proposal but is a good fit here in the Node.js docs.
The above definitions may be moved to a dedicated conditions registry in due course.
Self-referencing a package using its name#
Within a package, the values defined in the package's package.json "exports" field can be referenced via the package's name. For example, assuming the package.json is:
// package.json
{
"name": "a-package",
"exports": {
".": "./index.mjs",
"./foo.js": "./foo.js"
}
}
Then any module in that package can reference an export in the package itself:
// ./a-module.mjs
import { something } from 'a-package'; // Imports "something" from ./index.mjs.
Self-referencing is available only if package.json has "exports", and will allow importing only what that "exports" (in the package.json) allows. So the code below, given the previous package, will generate a runtime error:
// ./another-module.mjs
// Imports "another" from ./m.mjs. Fails because
// the "package.json" "exports" field
// does not provide an export named "./m.mjs".
import { another } from 'a-package/m.mjs';
Self-referencing is also available when using require, both in an ES module, and in a CommonJS one. For example, this code will also work:
// ./a-module.js
const { something } = require('a-package/foo.js'); // Loads from ./foo.js.
Finally, self-referencing also works with scoped packages. For example, this code will also work:
// ./index.js module.exports = 42;// ./other.js console.log(require('@my/package'));
$ node other.js
42
Dual CommonJS/ES module packages#
See the package examples repository for details.
Node.js package.json field definitions#
This section describes the fields used by the Node.js runtime. Other tools (such as npm) use additional fields which are ignored by Node.js and not documented here.
The following fields in package.json files are used in Node.js:
"name"- Relevant when using named imports within a package. Also used by package managers as the name of the package."main"- The default module when loading the package, if exports is not specified, and in versions of Node.js prior to the introduction of exports."type"- The package type determining whether to load.jsfiles as CommonJS or ES modules."exports"- Package exports and conditional exports. When present, limits which submodules can be loaded from within the package."imports"- Package imports, for use by modules within the package itself.
"name"#
- Type:
<string>
{
"name": "package-name"
}
The "name" field defines your package's name. Publishing to the npm registry requires a name that satisfies certain requirements.
The "name" field can be used in addition to the "exports" field to self-reference a package using its name.
"main"#
- Type:
<string>
{
"main": "./index.js"
}
The "main" field defines the entry point of a package when imported by name via a node_modules lookup. Its value is a path.
When a package has an "exports" field, this will take precedence over the "main" field when importing the package by name.
It also defines the script that is used when the package directory is loaded via require().
// This resolves to ./path/to/directory/index.js.
require('./path/to/directory');
"type"#
- Type:
<string>
The "type" field defines the module format that Node.js uses for all .js files that have that package.json file as their nearest parent.
Files ending with .js are loaded as ES modules when the nearest parent package.json file contains a top-level field "type" with a value of "module".
The nearest parent package.json is defined as the first package.json found when searching in the current folder, that folder's parent, and so on up until a node_modules folder or the volume root is reached.
// package.json
{
"type": "module"
}
# In same folder as preceding package.json
node my-app.js # Runs as ES module
If the nearest parent package.json lacks a "type" field, or contains "type": "commonjs", .js files are treated as CommonJS. If the volume root is reached and no package.json is found, .js files are treated as CommonJS.
import statements of .js files are treated as ES modules if the nearest parent package.json contains "type": "module".
// my-app.js, part of the same example as above
import './startup.js'; // Loaded as ES module because of package.json
Regardless of the value of the "type" field, .mjs files are always treated as ES modules and .cjs files are always treated as CommonJS.
"exports"#
- Type:
<Object>|<string>|<string[]>
{
"exports": "./index.js"
}
The "exports" field allows defining the entry points of a package when imported by name loaded either via a node_modules lookup or a self-reference to its own name. It is supported in Node.js 12+ as an alternative to the "main" that can support defining subpath exports and conditional exports while encapsulating internal unexported modules.
Conditional Exports can also be used within "exports" to define different package entry points per environment, including whether the package is referenced via require or via import.
All paths defined in the "exports" must be relative file URLs starting with ./.
"imports"#
- Type:
<Object>
// package.json
{
"imports": {
"#dep": {
"node": "dep-node-native",
"default": "./dep-polyfill.js"
}
},
"dependencies": {
"dep-node-native": "^1.0.0"
}
}
Entries in the imports field must be strings starting with #.
Package imports permit mapping to external packages.
This field defines subpath imports for the current package.
Modules: TypeScript#
Stability: 2 - Stable
Enabling#
There are two ways to enable runtime TypeScript support in Node.js:
For full support of all of TypeScript's syntax and features, including using any version of TypeScript, use a third-party package.
For lightweight support, you can use the built-in support for type stripping.
Full TypeScript support#
To use TypeScript with full support for all TypeScript features, including tsconfig.json, you can use a third-party package. These instructions use tsx as an example but there are many other similar libraries available.
Install the package as a development dependency using whatever package manager you're using for your project. For example, with
npm:npm install --save-dev tsxThen you can run your TypeScript code via:
npx tsx your-file.tsOr alternatively, you can run with
nodevia:node --import=tsx your-file.ts
Type stripping#
By default Node.js will execute TypeScript files that contains only erasable TypeScript syntax. Node.js will replace TypeScript syntax with whitespace, and no type checking is performed. To disable this feature, use the flag --no-strip-types.
Node.js ignores tsconfig.json files and therefore features that depend on settings within tsconfig.json, such as paths or converting newer JavaScript syntax to older standards, are intentionally unsupported. To get full TypeScript support, see Full TypeScript support.
The type stripping feature is designed to be lightweight. By intentionally not supporting syntaxes that require JavaScript code generation, and by replacing inline types with whitespace, Node.js can run TypeScript code without the need for source maps.
Type stripping is compatible with most versions of TypeScript but we recommend version 5.8 or newer with the following tsconfig.json settings:
{
"compilerOptions": {
"noEmit": true, // Optional - see note below
"target": "esnext",
"module": "nodenext",
"rewriteRelativeImportExtensions": true,
"erasableSyntaxOnly": true,
"verbatimModuleSyntax": true
}
}
Use the noEmit option if you intend to only execute *.ts files, for example a build script. You won't need this flag if you intend to distribute *.js files.
Determining module system#
Node.js supports both CommonJS and ES Modules syntax in TypeScript files. Node.js will not convert from one module system to another; if you want your code to run as an ES module, you must use import and export syntax, and if you want your code to run as CommonJS you must use require and module.exports.
.tsfiles will have their module system determined the same way as.jsfiles. To useimportandexportsyntax, add"type": "module"to the nearest parentpackage.json..mtsfiles will always be run as ES modules, similar to.mjsfiles..ctsfiles will always be run as CommonJS modules, similar to.cjsfiles..tsxfiles are unsupported.
As in JavaScript files, file extensions are mandatory in import statements and import() expressions: import './file.ts', not import './file'. Because of backward compatibility, file extensions are also mandatory in require() calls: require('./file.ts'), not require('./file'), similar to how the .cjs extension is mandatory in require calls in CommonJS files.
The tsconfig.json option allowImportingTsExtensions will allow the TypeScript compiler tsc to type-check files with import specifiers that include the .ts extension.
TypeScript features#
Since Node.js is only removing inline types, any TypeScript features that involve replacing TypeScript syntax with new JavaScript syntax will error.
The most prominent features that require transformation are:
Enumdeclarationsnamespacewith runtime code- parameter properties
- import aliases
namespaces that do not contain runtime code are supported. This example will work correctly:
// This namespace is exporting a type
namespace TypeOnly {
export type A = string;
}
This will result in ERR_UNSUPPORTED_TYPESCRIPT_SYNTAX error:
// This namespace is exporting a value
namespace A {
export let x = 1
}
Since Decorators are currently a TC39 Stage 3 proposal, they are not transformed and will result in a parser error. Node.js does not provide polyfills and thus will not support decorators until they are supported natively in JavaScript.
In addition, Node.js does not read tsconfig.json files and does not support features that depend on settings within tsconfig.json, such as paths or converting newer JavaScript syntax into older standards.
Importing types without type keyword#
Due to the nature of type stripping, the type keyword is necessary to correctly strip type imports. Without the type keyword, Node.js will treat the import as a value import, which will result in a runtime error. The tsconfig option verbatimModuleSyntax can be used to match this behavior.
This example will work correctly:
import type { Type1, Type2 } from './module.ts';
import { fn, type FnParams } from './fn.ts';
This will result in a runtime error:
import { Type1, Type2 } from './module.ts';
import { fn, FnParams } from './fn.ts';
Non-file forms of input#
Type stripping can be enabled for --eval and STDIN. The module system will be determined by --input-type, as it is for JavaScript.
TypeScript syntax is unsupported in the REPL, --check, and inspect.
Source maps#
Since inline types are replaced by whitespace, source maps are unnecessary for correct line numbers in stack traces; and Node.js does not generate them.
Type stripping in dependencies#
To discourage package authors from publishing packages written in TypeScript, Node.js refuses to handle TypeScript files inside folders under a node_modules path.
Paths aliases#
tsconfig "paths" won't be transformed and therefore produce an error. The closest feature available is subpath imports with the limitation that they need to start with #.
Net#
Stability: 2 - Stable
The node:net module provides an asynchronous network API for creating stream-based TCP or IPC servers (net.createServer()) and clients (net.createConnection()).
It can be accessed using:
import net from 'node:net';const net = require('node:net');
IPC support#
The node:net module supports IPC with named pipes on Windows, and Unix domain sockets on other operating systems.
Identifying paths for IPC connections#
net.connect(), net.createConnection(), server.listen(), and socket.connect() take a path parameter to identify IPC endpoints.
On Unix, the local domain is also known as the Unix domain. The path is a file system pathname. It will throw an error when the length of pathname is greater than the length of sizeof(sockaddr_un.sun_path). Typical values are 107 bytes on Linux and 103 bytes on macOS. If a Node.js API abstraction creates the Unix domain socket, it will unlink the Unix domain socket as well. For example, net.createServer() may create a Unix domain socket and server.close() will unlink it. But if a user creates the Unix domain socket outside of these abstractions, the user will need to remove it. The same applies when a Node.js API creates a Unix domain socket but the program then crashes. In short, a Unix domain socket will be visible in the file system and will persist until unlinked. On Linux, You can use Unix abstract socket by adding \0 to the beginning of the path, such as \0abstract. The path to the Unix abstract socket is not visible in the file system and it will disappear automatically when all open references to the socket are closed.
On Windows, the local domain is implemented using a named pipe. The path must refer to an entry in \\?\pipe\ or \\.\pipe\. Any characters are permitted, but the latter may do some processing of pipe names, such as resolving .. sequences. Despite how it might look, the pipe namespace is flat. Pipes will not persist. They are removed when the last reference to them is closed. Unlike Unix domain sockets, Windows will close and remove the pipe when the owning process exits.
JavaScript string escaping requires paths to be specified with extra backslash escaping such as:
net.createServer().listen(
path.join('\\\\?\\pipe', process.cwd(), 'myctl'));
Class: net.BlockList#
The BlockList object can be used with some network APIs to specify rules for disabling inbound or outbound access to specific IP addresses, IP ranges, or IP subnets.
blockList.addAddress(address[, type])#
address<string>|<net.SocketAddress>An IPv4 or IPv6 address.type<string>Either'ipv4'or'ipv6'. Default:'ipv4'.
Adds a rule to block the given IP address.
blockList.addRange(start, end[, type])#
start<string>|<net.SocketAddress>The starting IPv4 or IPv6 address in the range.end<string>|<net.SocketAddress>The ending IPv4 or IPv6 address in the range.type<string>Either'ipv4'or'ipv6'. Default:'ipv4'.
Adds a rule to block a range of IP addresses from start (inclusive) to end (inclusive).
blockList.addSubnet(net, prefix[, type])#
net<string>|<net.SocketAddress>The network IPv4 or IPv6 address.prefix<number>The number of CIDR prefix bits. For IPv4, this must be a value between0and32. For IPv6, this must be between0and128.type<string>Either'ipv4'or'ipv6'. Default:'ipv4'.
Adds a rule to block a range of IP addresses specified as a subnet mask.
blockList.check(address[, type])#
address<string>|<net.SocketAddress>The IP address to checktype<string>Either'ipv4'or'ipv6'. Default:'ipv4'.- Returns:
<boolean>
Returns true if the given IP address matches any of the rules added to the BlockList.
const blockList = new net.BlockList();
blockList.addAddress('123.123.123.123');
blockList.addRange('10.0.0.1', '10.0.0.10');
blockList.addSubnet('8592:757c:efae:4e45::', 64, 'ipv6');
console.log(blockList.check('123.123.123.123')); // Prints: true
console.log(blockList.check('10.0.0.3')); // Prints: true
console.log(blockList.check('222.111.111.222')); // Prints: false
// IPv6 notation for IPv4 addresses works:
console.log(blockList.check('::ffff:7b7b:7b7b', 'ipv6')); // Prints: true
console.log(blockList.check('::ffff:123.123.123.123', 'ipv6')); // Prints: true
blockList.rules#
- Type:
<string[]>
The list of rules added to the blocklist.
BlockList.isBlockList(value)#
value<any>Any JS value- Returns
trueif thevalueis anet.BlockList.
blockList.fromJSON(value)#
Stability: 1 - Experimental
const blockList = new net.BlockList();
const data = [
'Subnet: IPv4 192.168.1.0/24',
'Address: IPv4 10.0.0.5',
'Range: IPv4 192.168.2.1-192.168.2.10',
'Range: IPv4 10.0.0.1-10.0.0.10',
];
blockList.fromJSON(data);
blockList.fromJSON(JSON.stringify(data));
valueBlocklist.rules
blockList.toJSON()#
Stability: 1 - Experimental
- Returns Blocklist.rules
Class: net.SocketAddress#
new net.SocketAddress([options])#
options<Object>
socketaddress.address#
- Type:
<string>
socketaddress.family#
- Type:
<string>Either'ipv4'or'ipv6'.
socketaddress.flowlabel#
- Type:
<number>
socketaddress.port#
- Type:
<number>
SocketAddress.parse(input)#
input<string>An input string containing an IP address and optional port, e.g.123.1.2.3:1234or[1::1]:1234.- Returns:
<net.SocketAddress>Returns aSocketAddressif parsing was successful. Otherwise returnsundefined.
Class: net.Server#
- Extends:
<EventEmitter>
This class is used to create a TCP or IPC server.
new net.Server([options][, connectionListener])#
options<Object>Seenet.createServer([options][, connectionListener]).connectionListener<Function>Automatically set as a listener for the'connection'event.- Returns:
<net.Server>
net.Server is an EventEmitter with the following events:
Event: 'close'#
Emitted when the server closes. If connections exist, this event is not emitted until all connections are ended.
Event: 'connection'#
- Type:
<net.Socket>The connection object
Emitted when a new connection is made. socket is an instance of net.Socket.
Event: 'error'#
- Type:
<Error>
Emitted when an error occurs. Unlike net.Socket, the 'close' event will not be emitted directly following this event unless server.close() is manually called. See the example in discussion of server.listen().
Event: 'listening'#
Emitted when the server has been bound after calling server.listen().
Event: 'drop'#
When the number of connections reaches the threshold of server.maxConnections, the server will drop new connections and emit 'drop' event instead. If it is a TCP server, the argument is as follows, otherwise the argument is undefined.
server.address()#
Returns the bound address, the address family name, and port of the server as reported by the operating system if listening on an IP socket (useful to find which port was assigned when getting an OS-assigned address): { port: 12346, family: 'IPv4', address: '127.0.0.1' }.
For a server listening on a pipe or Unix domain socket, the name is returned as a string.
const server = net.createServer((socket) => {
socket.end('goodbye\n');
}).on('error', (err) => {
// Handle errors here.
throw err;
});
// Grab an arbitrary unused port.
server.listen(() => {
console.log('opened server on', server.address());
});
server.address() returns null before the 'listening' event has been emitted or after calling server.close().
server.close([callback])#
callback<Function>Called when the server is closed.- Returns:
<net.Server>
Stops the server from accepting new connections and keeps existing connections. This function is asynchronous, the server is finally closed when all connections are ended and the server emits a 'close' event. The optional callback will be called once the 'close' event occurs. Unlike that event, it will be called with an Error as its only argument if the server was not open when it was closed.
server[Symbol.asyncDispose]()#
Calls server.close() and returns a promise that fulfills when the server has closed.
server.getConnections(callback)#
callback<Function>- Returns:
<net.Server>
Asynchronously get the number of concurrent connections on the server. Works when sockets were sent to forks.
Callback should take two arguments err and count.
server.listen()#
Start a server listening for connections. A net.Server can be a TCP or an IPC server depending on what it listens to.
Possible signatures:
server.listen(handle[, backlog][, callback])server.listen(options[, callback])server.listen(path[, backlog][, callback])for IPC serversserver.listen([port[, host[, backlog]]][, callback])for TCP servers
This function is asynchronous. When the server starts listening, the 'listening' event will be emitted. The last parameter callback will be added as a listener for the 'listening' event.
All listen() methods can take a backlog parameter to specify the maximum length of the queue of pending connections. The actual length will be determined by the OS through sysctl settings such as tcp_max_syn_backlog and somaxconn on Linux. The default value of this parameter is 511 (not 512).
All net.Socket are set to SO_REUSEADDR (see socket(7) for details).
The server.listen() method can be called again if and only if there was an error during the first server.listen() call or server.close() has been called. Otherwise, an ERR_SERVER_ALREADY_LISTEN error will be thrown.
One of the most common errors raised when listening is EADDRINUSE. This happens when another server is already listening on the requested port/path/handle. One way to handle this would be to retry after a certain amount of time:
server.on('error', (e) => {
if (e.code === 'EADDRINUSE') {
console.error('Address in use, retrying...');
setTimeout(() => {
server.close();
server.listen(PORT, HOST);
}, 1000);
}
});
server.listen(handle[, backlog][, callback])#
handle<Object>backlog<number>Common parameter ofserver.listen()functionscallback<Function>- Returns:
<net.Server>
Start a server listening for connections on a given handle that has already been bound to a port, a Unix domain socket, or a Windows named pipe.
The handle object can be either a server, a socket (anything with an underlying _handle member), or an object with an fd member that is a valid file descriptor.
Listening on a file descriptor is not supported on Windows.
server.listen(options[, callback])#
options<Object>Required. Supports the following properties:backlog<number>Common parameter ofserver.listen()functions.exclusive<boolean>Default:falsehost<string>ipv6Only<boolean>For TCP servers, settingipv6Onlytotruewill disable dual-stack support, i.e., binding to host::won't make0.0.0.0be bound. Default:false.reusePort<boolean>For TCP servers, settingreusePorttotrueallows multiple sockets on the same host to bind to the same port. Incoming connections are distributed by the operating system to listening sockets. This option is available only on some platforms, such as Linux 3.9+, DragonFlyBSD 3.6+, FreeBSD 12.0+, Solaris 11.4, and AIX 7.2.5+. On unsupported platforms, this option raises an error. Default:false.path<string>Will be ignored ifportis specified. See Identifying paths for IPC connections.port<number>readableAll<boolean>For IPC servers makes the pipe readable for all users. Default:false.signal<AbortSignal>An AbortSignal that may be used to close a listening server.writableAll<boolean>For IPC servers makes the pipe writable for all users. Default:false.
callback<Function>functions.- Returns:
<net.Server>
If port is specified, it behaves the same as server.listen([port[, host[, backlog]]][, callback]). Otherwise, if path is specified, it behaves the same as server.listen(path[, backlog][, callback]). If none of them is specified, an error will be thrown.
If exclusive is false (default), then cluster workers will use the same underlying handle, allowing connection handling duties to be shared. When exclusive is true, the handle is not shared, and attempted port sharing results in an error. An example which listens on an exclusive port is shown below.
server.listen({
host: 'localhost',
port: 80,
exclusive: true,
});
When exclusive is true and the underlying handle is shared, it is possible that several workers query a handle with different backlogs. In this case, the first backlog passed to the master process will be used.
Starting an IPC server as root may cause the server path to be inaccessible for unprivileged users. Using readableAll and writableAll will make the server accessible for all users.
If the signal option is enabled, calling .abort() on the corresponding AbortController is similar to calling .close() on the server:
const controller = new AbortController();
server.listen({
host: 'localhost',
port: 80,
signal: controller.signal,
});
// Later, when you want to close the server.
controller.abort();
server.listen(path[, backlog][, callback])#
path<string>Path the server should listen to. See Identifying paths for IPC connections.backlog<number>Common parameter ofserver.listen()functions.callback<Function>.- Returns:
<net.Server>
Start an IPC server listening for connections on the given path.
server.listen([port[, host[, backlog]]][, callback])#
port<number>host<string>backlog<number>Common parameter ofserver.listen()functions.callback<Function>.- Returns:
<net.Server>
Start a TCP server listening for connections on the given port and host.
If port is omitted or is 0, the operating system will assign an arbitrary unused port, which can be retrieved by using server.address().port after the 'listening' event has been emitted.
If host is omitted, the server will accept connections on the unspecified IPv6 address (::) when IPv6 is available, or the unspecified IPv4 address (0.0.0.0) otherwise.
In most operating systems, listening to the unspecified IPv6 address (::) may cause the net.Server to also listen on the unspecified IPv4 address (0.0.0.0).
server.listening#
- Type:
<boolean>Indicates whether or not the server is listening for connections.
server.maxConnections#
- Type:
<integer>
When the number of connections reaches the server.maxConnections threshold:
If the process is not running in cluster mode, Node.js will close the connection.
If the process is running in cluster mode, Node.js will, by default, route the connection to another worker process. To close the connection instead, set
server.dropMaxConnectiontotrue.
It is not recommended to use this option once a socket has been sent to a child with child_process.fork().
server.dropMaxConnection#
- Type:
<boolean>
Set this property to true to begin closing connections once the number of connections reaches the server.maxConnections threshold. This setting is only effective in cluster mode.
server.ref()#
- Returns:
<net.Server>
Opposite of unref(), calling ref() on a previously unrefed server will not let the program exit if it's the only server left (the default behavior). If the server is refed calling ref() again will have no effect.
server.unref()#
- Returns:
<net.Server>
Calling unref() on a server will allow the program to exit if this is the only active server in the event system. If the server is already unrefed calling unref() again will have no effect.
Class: net.Socket#
- Extends:
<stream.Duplex>
This class is an abstraction of a TCP socket or a streaming IPC endpoint (uses named pipes on Windows, and Unix domain sockets otherwise). It is also an EventEmitter.
A net.Socket can be created by the user and used directly to interact with a server. For example, it is returned by net.createConnection(), so the user can use it to talk to the server.
It can also be created by Node.js and passed to the user when a connection is received. For example, it is passed to the listeners of a 'connection' event emitted on a net.Server, so the user can use it to interact with the client.
new net.Socket([options])#
options<Object>Available options are:allowHalfOpen<boolean>If set tofalse, then the socket will automatically end the writable side when the readable side ends. Seenet.createServer()and the'end'event for details. Default:false.blockList<net.BlockList>blockListcan be used for disabling outbound access to specific IP addresses, IP ranges, or IP subnets.fd<number>If specified, wrap around an existing socket with the given file descriptor, otherwise a new socket will be created.keepAlive<boolean>If set totrue, it enables keep-alive functionality on the socket immediately after the connection is established, similarly on what is done insocket.setKeepAlive(). Default:false.keepAliveInitialDelay<number>If set to a positive number, it sets the initial delay before the first keepalive probe is sent on an idle socket. Default:0.noDelay<boolean>If set totrue, it disables the use of Nagle's algorithm immediately after the socket is established. Default:false.onread<Object>If specified, incoming data is stored in a singlebufferand passed to the suppliedcallbackwhen data arrives on the socket. This will cause the streaming functionality to not provide any data. The socket will emit events like'error','end', and'close'as usual. Methods likepause()andresume()will also behave as expected.buffer<Buffer>|<Uint8Array>|<Function>Either a reusable chunk of memory to use for storing incoming data or a function that returns such.callback<Function>This function is called for every chunk of incoming data. Two arguments are passed to it: the number of bytes written tobufferand a reference tobuffer. Returnfalsefrom this function to implicitlypause()the socket. This function will be executed in the global context.
readable<boolean>Allow reads on the socket when anfdis passed, otherwise ignored. Default:false.signal<AbortSignal>An Abort signal that may be used to destroy the socket.typeOfService<number>The initial Type of Service (TOS) value.writable<boolean>Allow writes on the socket when anfdis passed, otherwise ignored. Default:false.
- Returns:
<net.Socket>
Creates a new socket object.
The newly created socket can be either a TCP socket or a streaming IPC endpoint, depending on what it connect() to.
Event: 'close'#
hadError<boolean>trueif the socket had a transmission error.
Emitted once the socket is fully closed. The argument hadError is a boolean which says if the socket was closed due to a transmission error.
Event: 'connect'#
Emitted when a socket connection is successfully established. See net.createConnection().
Event: 'connectionAttempt'#
ip<string>The IP which the socket is attempting to connect to.port<number>The port which the socket is attempting to connect to.family<number>The family of the IP. It can be6for IPv6 or4for IPv4.
Emitted when a new connection attempt is started. This may be emitted multiple times if the family autoselection algorithm is enabled in socket.connect(options).
Event: 'connectionAttemptFailed'#
ip<string>The IP which the socket attempted to connect to.port<number>The port which the socket attempted to connect to.family<number>The family of the IP. It can be6for IPv6 or4for IPv4.error<Error>The error associated with the failure.
Emitted when a connection attempt failed. This may be emitted multiple times if the family autoselection algorithm is enabled in socket.connect(options).
Event: 'connectionAttemptTimeout'#
ip<string>The IP which the socket attempted to connect to.port<number>The port which the socket attempted to connect to.family<number>The family of the IP. It can be6for IPv6 or4for IPv4.
Emitted when a connection attempt timed out. This is only emitted (and may be emitted multiple times) if the family autoselection algorithm is enabled in socket.connect(options).
Event: 'data'#
Emitted when data is received. The argument data will be a Buffer or String. Encoding of data is set by socket.setEncoding().
The data will be lost if there is no listener when a Socket emits a 'data' event.
Event: 'drain'#
Emitted when the write buffer becomes empty. Can be used to throttle uploads.
See also: the return values of socket.write().
Event: 'end'#
Emitted when the other end of the socket signals the end of transmission, thus ending the readable side of the socket.
By default (allowHalfOpen is false) the socket will send an end of transmission packet back and destroy its file descriptor once it has written out its pending write queue. However, if allowHalfOpen is set to true, the socket will not automatically end() its writable side, allowing the user to write arbitrary amounts of data. The user must call end() explicitly to close the connection (i.e. sending a FIN packet back).
Event: 'error'#
- Type:
<Error>
Emitted when an error occurs. The 'close' event will be called directly following this event.
Event: 'lookup'#
Emitted after resolving the host name but before connecting. Not applicable to Unix sockets.
err<Error>|<null>The error object. Seedns.lookup().address<string>The IP address.family<number>|<null>The address type. Seedns.lookup().host<string>The host name.
Event: 'ready'#
Emitted when a socket is ready to be used.
Triggered immediately after 'connect'.
Event: 'timeout'#
Emitted if the socket times out from inactivity. This is only to notify that the socket has been idle. The user must manually close the connection.
See also: socket.setTimeout().
socket.address()#
- Returns:
<Object>
Returns the bound address, the address family name and port of the socket as reported by the operating system: { port: 12346, family: 'IPv4', address: '127.0.0.1' }
socket.autoSelectFamilyAttemptedAddresses#
- Type:
<string[]>
This property is only present if the family autoselection algorithm is enabled in socket.connect(options) and it is an array of the addresses that have been attempted.
Each address is a string in the form of $IP:$PORT. If the connection was successful, then the last address is the one that the socket is currently connected to.
socket.bufferSize#
Stability: 0 - Deprecated: Use writable.writableLength instead.
- Type:
<integer>
This property shows the number of characters buffered for writing. The buffer may contain strings whose length after encoding is not yet known. So this number is only an approximation of the number of bytes in the buffer.
net.Socket has the property that socket.write() always works. This is to help users get up and running quickly. The computer cannot always keep up with the amount of data that is written to a socket. The network connection simply might be too slow. Node.js will internally queue up the data written to a socket and send it out over the wire when it is possible.
The consequence of this internal buffering is that memory may grow. Users who experience large or growing bufferSize should attempt to "throttle" the data flows in their program with socket.pause() and socket.resume().
socket.bytesRead#
- Type:
<integer>
The amount of received bytes.
socket.bytesWritten#
- Type:
<integer>
The amount of bytes sent.
socket.connect()#
Initiate a connection on a given socket.
Possible signatures:
socket.connect(options[, connectListener])socket.connect(path[, connectListener])for IPC connections.socket.connect(port[, host][, connectListener])for TCP connections.- Returns:
<net.Socket>The socket itself.
This function is asynchronous. When the connection is established, the 'connect' event will be emitted. If there is a problem connecting, instead of a 'connect' event, an 'error' event will be emitted with the error passed to the 'error' listener. The last parameter connectListener, if supplied, will be added as a listener for the 'connect' event once.
This function should only be used for reconnecting a socket after 'close' has been emitted or otherwise it may lead to undefined behavior.
socket.connect(options[, connectListener])#
options<Object>connectListener<Function>Common parameter ofsocket.connect()methods. Will be added as a listener for the'connect'event once.- Returns:
<net.Socket>The socket itself.
Initiate a connection on a given socket. Normally this method is not needed, the socket should be created and opened with net.createConnection(). Use this only when implementing a custom Socket.
For TCP connections, available options are:
autoSelectFamily<boolean>: If set totrue, it enables a family autodetection algorithm that loosely implements section 5 of RFC 8305. Thealloption passed to lookup is set totrueand the sockets attempts to connect to all obtained IPv6 and IPv4 addresses, in sequence, until a connection is established. The first returned AAAA address is tried first, then the first returned A address, then the second returned AAAA address and so on. Each connection attempt (but the last one) is given the amount of time specified by theautoSelectFamilyAttemptTimeoutoption before timing out and trying the next address. Ignored if thefamilyoption is not0or iflocalAddressis set. Connection errors are not emitted if at least one connection succeeds. If all connections attempts fails, a singleAggregateErrorwith all failed attempts is emitted. Default:net.getDefaultAutoSelectFamily().autoSelectFamilyAttemptTimeout<number>: The amount of time in milliseconds to wait for a connection attempt to finish before trying the next address when using theautoSelectFamilyoption. If set to a positive integer less than10, then the value10will be used instead. Default:net.getDefaultAutoSelectFamilyAttemptTimeout().family<number>: Version of IP stack. Must be4,6, or0. The value0indicates that both IPv4 and IPv6 addresses are allowed. Default:0.hints<number>Optionaldns.lookup()hints.host<string>Host the socket should connect to. Default:'localhost'.localAddress<string>Local address the socket should connect from.localPort<number>Local port the socket should connect from.lookup<Function>Custom lookup function. Default:dns.lookup().port<number>Required. Port the socket should connect to.
For IPC connections, available options are:
path<string>Required. Path the client should connect to. See Identifying paths for IPC connections. If provided, the TCP-specific options above are ignored.
socket.connect(path[, connectListener])#
path<string>Path the client should connect to. See Identifying paths for IPC connections.connectListener<Function>Common parameter ofsocket.connect()methods. Will be added as a listener for the'connect'event once.- Returns:
<net.Socket>The socket itself.
Initiate an IPC connection on the given socket.
Alias to socket.connect(options[, connectListener]) called with { path: path } as options.
socket.connect(port[, host][, connectListener])#
port<number>Port the client should connect to.host<string>Host the client should connect to.connectListener<Function>Common parameter ofsocket.connect()methods. Will be added as a listener for the'connect'event once.- Returns:
<net.Socket>The socket itself.
Initiate a TCP connection on the given socket.
Alias to socket.connect(options[, connectListener]) called with {port: port, host: host} as options.
socket.connecting#
- Type:
<boolean>
If true, socket.connect(options[, connectListener]) was called and has not yet finished. It will stay true until the socket becomes connected, then it is set to false and the 'connect' event is emitted. Note that the socket.connect(options[, connectListener]) callback is a listener for the 'connect' event.
socket.destroy([error])#
error<Object>- Returns:
<net.Socket>
Ensures that no more I/O activity happens on this socket. Destroys the stream and closes the connection.
See writable.destroy() for further details.
socket.destroyed#
- Type:
<boolean>Indicates if the connection is destroyed or not. Once a connection is destroyed no further data can be transferred using it.
See writable.destroyed for further details.
socket.destroySoon()#
Destroys the socket after all data is written. If the 'finish' event was already emitted the socket is destroyed immediately. If the socket is still writable it implicitly calls socket.end().
socket.end([data[, encoding]][, callback])#
data<string>|<Buffer>|<Uint8Array>encoding<string>Only used when data isstring. Default:'utf8'.callback<Function>Optional callback for when the socket is finished.- Returns:
<net.Socket>The socket itself.
Half-closes the socket. i.e., it sends a FIN packet. It is possible the server will still send some data.
See writable.end() for further details.
socket.localAddress#
- Type:
<string>
The string representation of the local IP address the remote client is connecting on. For example, in a server listening on '0.0.0.0', if a client connects on '192.168.1.1', the value of socket.localAddress would be '192.168.1.1'.
socket.localPort#
- Type:
<integer>
The numeric representation of the local port. For example, 80 or 21.
socket.localFamily#
- Type:
<string>
The string representation of the local IP family. 'IPv4' or 'IPv6'.
socket.pause()#
- Returns:
<net.Socket>The socket itself.
Pauses the reading of data. That is, 'data' events will not be emitted. Useful to throttle back an upload.
socket.pending#
- Type:
<boolean>
This is true if the socket is not connected yet, either because .connect() has not yet been called or because it is still in the process of connecting (see socket.connecting).
socket.ref()#
- Returns:
<net.Socket>The socket itself.
Opposite of unref(), calling ref() on a previously unrefed socket will not let the program exit if it's the only socket left (the default behavior). If the socket is refed calling ref again will have no effect.
socket.remoteAddress#
- Type:
<string>
The string representation of the remote IP address. For example, '74.125.127.100' or '2001:4860:a005::68'. Value may be undefined if the socket is destroyed (for example, if the client disconnected).
socket.remoteFamily#
- Type:
<string>
The string representation of the remote IP family. 'IPv4' or 'IPv6'. Value may be undefined if the socket is destroyed (for example, if the client disconnected).
socket.remotePort#
- Type:
<integer>
The numeric representation of the remote port. For example, 80 or 21. Value may be undefined if the socket is destroyed (for example, if the client disconnected).
socket.resetAndDestroy()#
- Returns:
<net.Socket>
Close the TCP connection by sending an RST packet and destroy the stream. If this TCP socket is in connecting status, it will send an RST packet and destroy this TCP socket once it is connected. Otherwise, it will call socket.destroy with an ERR_SOCKET_CLOSED Error. If this is not a TCP socket (for example, a pipe), calling this method will immediately throw an ERR_INVALID_HANDLE_TYPE Error.
socket.resume()#
- Returns:
<net.Socket>The socket itself.
Resumes reading after a call to socket.pause().
socket.setEncoding([encoding])#
encoding<string>- Returns:
<net.Socket>The socket itself.
Set the encoding for the socket as a Readable Stream. See readable.setEncoding() for more information.
socket.setKeepAlive([enable][, initialDelay])#
enable<boolean>Default:falseinitialDelay<number>Default:0- Returns:
<net.Socket>The socket itself.
Enable/disable keep-alive functionality, and optionally set the initial delay before the first keepalive probe is sent on an idle socket.
Set initialDelay (in milliseconds) to set the delay between the last data packet received and the first keepalive probe. Setting 0 for initialDelay will leave the value unchanged from the default (or previous) setting.
Enabling the keep-alive functionality will set the following socket options:
SO_KEEPALIVE=1TCP_KEEPIDLE=initialDelayTCP_KEEPCNT=10TCP_KEEPINTVL=1
socket.setNoDelay([noDelay])#
noDelay<boolean>Default:true- Returns:
<net.Socket>The socket itself.
Enable/disable the use of Nagle's algorithm.
When a TCP connection is created, it will have Nagle's algorithm enabled.
Nagle's algorithm delays data before it is sent via the network. It attempts to optimize throughput at the expense of latency.
Passing true for noDelay or not passing an argument will disable Nagle's algorithm for the socket. Passing false for noDelay will enable Nagle's algorithm.
socket.setTimeout(timeout[, callback])#
timeout<number>callback<Function>- Returns:
<net.Socket>The socket itself.
Sets the socket to timeout after timeout milliseconds of inactivity on the socket. By default net.Socket do not have a timeout.
When an idle timeout is triggered the socket will receive a 'timeout' event but the connection will not be severed. The user must manually call socket.end() or socket.destroy() to end the connection.
socket.setTimeout(3000);
socket.on('timeout', () => {
console.log('socket timeout');
socket.end();
});
If timeout is 0, then the existing idle timeout is disabled.
The optional callback parameter will be added as a one-time listener for the 'timeout' event.
socket.getTypeOfService()#
- Returns:
<integer>The current TOS value.
Returns the current Type of Service (TOS) field for IPv4 packets or Traffic Class for IPv6 packets for this socket.
setTypeOfService() may be called before the socket is connected; the value will be cached and applied when the socket establishes a connection. getTypeOfService() will return the currently set value even before connection.
On some platforms (e.g., Linux), certain TOS/ECN bits may be masked or ignored, and behavior can differ between IPv4 and IPv6 or dual-stack sockets. Callers should verify platform-specific semantics.
socket.setTypeOfService(tos)#
tos<integer>The TOS value to set (0-255).- Returns:
<net.Socket>The socket itself.
Sets the Type of Service (TOS) field for IPv4 packets or Traffic Class for IPv6 Packets sent from this socket. This can be used to prioritize network traffic.
setTypeOfService() may be called before the socket is connected; the value will be cached and applied when the socket establishes a connection. getTypeOfService() will return the currently set value even before connection.
On some platforms (e.g., Linux), certain TOS/ECN bits may be masked or ignored, and behavior can differ between IPv4 and IPv6 or dual-stack sockets. Callers should verify platform-specific semantics.
socket.timeout#
- Type:
<number>|<undefined>
The socket timeout in milliseconds as set by socket.setTimeout(). It is undefined if a timeout has not been set.
socket.unref()#
- Returns:
<net.Socket>The socket itself.
Calling unref() on a socket will allow the program to exit if this is the only active socket in the event system. If the socket is already unrefed calling unref() again will have no effect.
socket.write(data[, encoding][, callback])#
data<string>|<Buffer>|<Uint8Array>encoding<string>Only used when data isstring. Default:utf8.callback<Function>- Returns:
<boolean>
Sends data on the socket. The second parameter specifies the encoding in the case of a string. It defaults to UTF8 encoding.
Returns true if the entire data was flushed successfully to the kernel buffer. Returns false if all or part of the data was queued in user memory. 'drain' will be emitted when the buffer is again free.
The optional callback parameter will be executed when the data is finally written out, which may not be immediately.
See Writable stream write() method for more information.
socket.readyState#
- Type:
<string>
This property represents the state of the connection as a string.
- If the stream is connecting
socket.readyStateisopening. - If the stream is readable and writable, it is
open. - If the stream is readable and not writable, it is
readOnly. - If the stream is not readable and writable, it is
writeOnly.
net.connect()#
Aliases to net.createConnection().
Possible signatures:
net.connect(options[, connectListener])net.connect(path[, connectListener])for IPC connections.net.connect(port[, host][, connectListener])for TCP connections.
net.connect(options[, connectListener])#
options<Object>connectListener<Function>- Returns:
<net.Socket>
net.connect(path[, connectListener])#
path<string>connectListener<Function>- Returns:
<net.Socket>
net.connect(port[, host][, connectListener])#
port<number>host<string>connectListener<Function>- Returns:
<net.Socket>
Alias to net.createConnection(port[, host][, connectListener]).
net.createConnection()#
A factory function, which creates a new net.Socket, immediately initiates connection with socket.connect(), then returns the net.Socket that starts the connection.
When the connection is established, a 'connect' event will be emitted on the returned socket. The last parameter connectListener, if supplied, will be added as a listener for the 'connect' event once.
Possible signatures:
net.createConnection(options[, connectListener])net.createConnection(path[, connectListener])for IPC connections.net.createConnection(port[, host][, connectListener])for TCP connections.
The net.connect() function is an alias to this function.
net.createConnection(options[, connectListener])#
options<Object>Required. Will be passed to both thenew net.Socket([options])call and thesocket.connect(options[, connectListener])method.connectListener<Function>Common parameter of thenet.createConnection()functions. If supplied, will be added as a listener for the'connect'event on the returned socket once.- Returns:
<net.Socket>The newly created socket used to start the connection.
For available options, see new net.Socket([options]) and socket.connect(options[, connectListener]).
Additional options:
timeout<number>If set, will be used to callsocket.setTimeout(timeout)after the socket is created, but before it starts the connection.
Following is an example of a client of the echo server described in the net.createServer() section:
import net from 'node:net'; const client = net.createConnection({ port: 8124 }, () => { // 'connect' listener. console.log('connected to server!'); client.write('world!\r\n'); }); client.on('data', (data) => { console.log(data.toString()); client.end(); }); client.on('end', () => { console.log('disconnected from server'); });const net = require('node:net'); const client = net.createConnection({ port: 8124 }, () => { // 'connect' listener. console.log('connected to server!'); client.write('world!\r\n'); }); client.on('data', (data) => { console.log(data.toString()); client.end(); }); client.on('end', () => { console.log('disconnected from server'); });
To connect on the socket /tmp/echo.sock:
const client = net.createConnection({ path: '/tmp/echo.sock' });
Following is an example of a client using the port and onread option. In this case, the onread option will be only used to call new net.Socket([options]) and the port option will be used to call socket.connect(options[, connectListener]).
import net from 'node:net'; import { Buffer } from 'node:buffer'; net.createConnection({ port: 8124, onread: { // Reuses a 4KiB Buffer for every read from the socket. buffer: Buffer.alloc(4 * 1024), callback: function(nread, buf) { // Received data is available in `buf` from 0 to `nread`. console.log(buf.toString('utf8', 0, nread)); }, }, });const net = require('node:net'); net.createConnection({ port: 8124, onread: { // Reuses a 4KiB Buffer for every read from the socket. buffer: Buffer.alloc(4 * 1024), callback: function(nread, buf) { // Received data is available in `buf` from 0 to `nread`. console.log(buf.toString('utf8', 0, nread)); }, }, });
net.createConnection(path[, connectListener])#
path<string>Path the socket should connect to. Will be passed tosocket.connect(path[, connectListener]). See Identifying paths for IPC connections.connectListener<Function>Common parameter of thenet.createConnection()functions, an "once" listener for the'connect'event on the initiating socket. Will be passed tosocket.connect(path[, connectListener]).- Returns:
<net.Socket>The newly created socket used to start the connection.
Initiates an IPC connection.
This function creates a new net.Socket with all options set to default, immediately initiates connection with socket.connect(path[, connectListener]), then returns the net.Socket that starts the connection.
net.createConnection(port[, host][, connectListener])#
port<number>Port the socket should connect to. Will be passed tosocket.connect(port[, host][, connectListener]).host<string>Host the socket should connect to. Will be passed tosocket.connect(port[, host][, connectListener]). Default:'localhost'.connectListener<Function>Common parameter of thenet.createConnection()functions, an "once" listener for the'connect'event on the initiating socket. Will be passed tosocket.connect(port[, host][, connectListener]).- Returns:
<net.Socket>The newly created socket used to start the connection.
Initiates a TCP connection.
This function creates a new net.Socket with all options set to default, immediately initiates connection with socket.connect(port[, host][, connectListener]), then returns the net.Socket that starts the connection.
net.createServer([options][, connectionListener])#
options<Object>allowHalfOpen<boolean>If set tofalse, then the socket will automatically end the writable side when the readable side ends. Default:false.highWaterMark<number>Optionally overrides allnet.Sockets'readableHighWaterMarkandwritableHighWaterMark. Default: Seestream.getDefaultHighWaterMark().keepAlive<boolean>If set totrue, it enables keep-alive functionality on the socket immediately after a new incoming connection is received, similarly on what is done insocket.setKeepAlive(). Default:false.keepAliveInitialDelay<number>If set to a positive number, it sets the initial delay before the first keepalive probe is sent on an idle socket. Default:0.noDelay<boolean>If set totrue, it disables the use of Nagle's algorithm immediately after a new incoming connection is received. Default:false.pauseOnConnect<boolean>Indicates whether the socket should be paused on incoming connections. Default:false.blockList<net.BlockList>blockListcan be used for disabling inbound access to specific IP addresses, IP ranges, or IP subnets. This does not work if the server is behind a reverse proxy, NAT, etc. because the address checked against the block list is the address of the proxy, or the one specified by the NAT.
connectionListener<Function>Automatically set as a listener for the'connection'event.Returns:
<net.Server>
Creates a new TCP or IPC server.
If allowHalfOpen is set to true, when the other end of the socket signals the end of transmission, the server will only send back the end of transmission when socket.end() is explicitly called. For example, in the context of TCP, when a FIN packed is received, a FIN packed is sent back only when socket.end() is explicitly called. Until then the connection is half-closed (non-readable but still writable). See 'end' event and RFC 1122 (section 4.2.2.13) for more information.
If pauseOnConnect is set to true, then the socket associated with each incoming connection will be paused, and no data will be read from its handle. This allows connections to be passed between processes without any data being read by the original process. To begin reading data from a paused socket, call socket.resume().
The server can be a TCP server or an IPC server, depending on what it listen() to.
Here is an example of a TCP echo server which listens for connections on port 8124:
import net from 'node:net'; const server = net.createServer((c) => { // 'connection' listener. console.log('client connected'); c.on('end', () => { console.log('client disconnected'); }); c.write('hello\r\n'); c.pipe(c); }); server.on('error', (err) => { throw err; }); server.listen(8124, () => { console.log('server bound'); });const net = require('node:net'); const server = net.createServer((c) => { // 'connection' listener. console.log('client connected'); c.on('end', () => { console.log('client disconnected'); }); c.write('hello\r\n'); c.pipe(c); }); server.on('error', (err) => { throw err; }); server.listen(8124, () => { console.log('server bound'); });
Test this by using telnet:
telnet localhost 8124
To listen on the socket /tmp/echo.sock:
server.listen('/tmp/echo.sock', () => {
console.log('server bound');
});
Use nc to connect to a Unix domain socket server:
nc -U /tmp/echo.sock
net.getDefaultAutoSelectFamily()#
Gets the current default value of the autoSelectFamily option of socket.connect(options). The initial default value is true, unless the command line option --no-network-family-autoselection is provided.
- Returns:
<boolean>The current default value of theautoSelectFamilyoption.
net.setDefaultAutoSelectFamily(value)#
Sets the default value of the autoSelectFamily option of socket.connect(options).
value<boolean>The new default value. The initial default value istrue, unless the command line option--no-network-family-autoselectionis provided.
net.getDefaultAutoSelectFamilyAttemptTimeout()#
Gets the current default value of the autoSelectFamilyAttemptTimeout option of socket.connect(options). The initial default value is 500 or the value specified via the command line option --network-family-autoselection-attempt-timeout.
- Returns:
<number>The current default value of theautoSelectFamilyAttemptTimeoutoption.
net.setDefaultAutoSelectFamilyAttemptTimeout(value)#
Sets the default value of the autoSelectFamilyAttemptTimeout option of socket.connect(options).
value<number>The new default value, which must be a positive number. If the number is less than10, the value10is used instead. The initial default value is250or the value specified via the command line option--network-family-autoselection-attempt-timeout.
net.isIP(input)#
Returns 6 if input is an IPv6 address. Returns 4 if input is an IPv4 address in dot-decimal notation with no leading zeroes. Otherwise, returns 0.
net.isIP('::1'); // returns 6
net.isIP('127.0.0.1'); // returns 4
net.isIP('127.000.000.001'); // returns 0
net.isIP('127.0.0.1/24'); // returns 0
net.isIP('fhqwhgads'); // returns 0
net.isIPv4(input)#
Returns true if input is an IPv4 address in dot-decimal notation with no leading zeroes. Otherwise, returns false.
net.isIPv4('127.0.0.1'); // returns true
net.isIPv4('127.000.000.001'); // returns false
net.isIPv4('127.0.0.1/24'); // returns false
net.isIPv4('fhqwhgads'); // returns false
net.isIPv6(input)#
Returns true if input is an IPv6 address. Otherwise, returns false.
net.isIPv6('::1'); // returns true
net.isIPv6('fhqwhgads'); // returns false
Node-API#
Stability: 2 - Stable
Node-API (formerly N-API) is an API for building native Addons. It is independent from the underlying JavaScript runtime (for example, V8) and is maintained as part of Node.js itself. This API will be Application Binary Interface (ABI) stable across versions of Node.js. It is intended to insulate addons from changes in the underlying JavaScript engine and allow modules compiled for one major version to run on later major versions of Node.js without recompilation. The ABI Stability guide provides a more in-depth explanation.
Addons are built/packaged with the same approach/tools outlined in the section titled C++ Addons. The only difference is the set of APIs that are used by the native code. Instead of using the V8 or Native Abstractions for Node.js APIs, the functions available in Node-API are used.
APIs exposed by Node-API are generally used to create and manipulate JavaScript values. Concepts and operations generally map to ideas specified in the ECMA-262 Language Specification. The APIs have the following properties:
- All Node-API calls return a status code of type
napi_status. This status indicates whether the API call succeeded or failed. - The API's return value is passed via an out parameter.
- All JavaScript values are abstracted behind an opaque type named
napi_value. - In case of an error status code, additional information can be obtained using
napi_get_last_error_info. More information can be found in the error handling section Error handling.
Writing addons in various programming languages#
Node-API is a C API that ensures ABI stability across Node.js versions and different compiler levels. With this stability guarantee, it is possible to write addons in other programming languages on top of Node-API. Refer to language and engine bindings for more programming languages and engines support details.
node-addon-api is the official C++ binding that provides a more efficient way to write C++ code that calls Node-API. This wrapper is a header-only library that offers an inlinable C++ API. Binaries built with node-addon-api will depend on the symbols of the Node-API C-based functions exported by Node.js. The following code snippet is an example of node-addon-api:
Object obj = Object::New(env);
obj["foo"] = String::New(env, "bar");
The above node-addon-api C++ code is equivalent to the following C-based Node-API code:
napi_status status;
napi_value object, string;
status = napi_create_object(env, &object);
if (status != napi_ok) {
napi_throw_error(env, ...);
return;
}
status = napi_create_string_utf8(env, "bar", NAPI_AUTO_LENGTH, &string);
if (status != napi_ok) {
napi_throw_error(env, ...);
return;
}
status = napi_set_named_property(env, object, "foo", string);
if (status != napi_ok) {
napi_throw_error(env, ...);
return;
}
The end result is that the addon only uses the exported C APIs. Even though the addon is written in C++, it still gets the benefits of the ABI stability provided by the C Node-API.
When using node-addon-api instead of the C APIs, start with the API docs for node-addon-api.
The Node-API Resource offers an excellent orientation and tips for developers just getting started with Node-API and node-addon-api. Additional media resources can be found on the Node-API Media page.
Implications of ABI stability#
Although Node-API provides an ABI stability guarantee, other parts of Node.js do not, and any external libraries used from the addon may not. In particular, none of the following APIs provide an ABI stability guarantee across major versions:
the Node.js C++ APIs available via any of
#include <node.h> #include <node_buffer.h> #include <node_version.h> #include <node_object_wrap.h>the libuv APIs which are also included with Node.js and available via
#include <uv.h>the V8 API available via
#include <v8.h>
Thus, for an addon to remain ABI-compatible across Node.js major versions, it must use Node-API exclusively by restricting itself to using
#include <node_api.h>
and by checking, for all external libraries that it uses, that the external library makes ABI stability guarantees similar to Node-API.
Enum values in ABI stability#
All enum data types defined in Node-API should be considered as a fixed size int32_t value. Bit flag enum types should be explicitly documented, and they work with bit operators like bit-OR (|) as a bit value. Unless otherwise documented, an enum type should be considered to be extensible.
A new enum value will be added at the end of the enum definition. An enum value will not be removed or renamed.
For an enum type returned from a Node-API function, or provided as an out parameter of a Node-API function, the value is an integer value and an addon should handle unknown values. New values are allowed to be introduced without a version guard. For example, when checking napi_status in switch statements, an addon should include a default branch, as new status codes may be introduced in newer Node.js versions.
For an enum type used in an in-parameter, the result of passing an unknown integer value to Node-API functions is undefined unless otherwise documented. A new value is added with a version guard to indicate the Node-API version in which it was introduced. For example, napi_get_all_property_names can be extended with new enum value of napi_key_filter.
For an enum type used in both in-parameters and out-parameters, new values are allowed to be introduced without a version guard.
Building#
Unlike modules written in JavaScript, developing and deploying Node.js native addons using Node-API requires an additional set of tools. Besides the basic tools required to develop for Node.js, the native addon developer requires a toolchain that can compile C and C++ code into a binary. In addition, depending upon how the native addon is deployed, the user of the native addon will also need to have a C/C++ toolchain installed.
For Linux developers, the necessary C/C++ toolchain packages are readily available. GCC is widely used in the Node.js community to build and test across a variety of platforms. For many developers, the LLVM compiler infrastructure is also a good choice.
For Mac developers, Xcode offers all the required compiler tools. However, it is not necessary to install the entire Xcode IDE. The following command installs the necessary toolchain:
xcode-select --install
For Windows developers, Visual Studio offers all the required compiler tools. However, it is not necessary to install the entire Visual Studio IDE. The following command installs the necessary toolchain:
npm install --global windows-build-tools
The sections below describe the additional tools available for developing and deploying Node.js native addons.
Build tools#
Both the tools listed here require that users of the native addon have a C/C++ toolchain installed in order to successfully install the native addon.
node-gyp#
node-gyp is a build system based on the gyp-next fork of Google's GYP tool and comes bundled with npm. GYP, and therefore node-gyp, requires that Python be installed.
Historically, node-gyp has been the tool of choice for building native addons. It has widespread adoption and documentation. However, some developers have run into limitations in node-gyp.
CMake.js#
CMake.js is an alternative build system based on CMake.
CMake.js is a good choice for projects that already use CMake or for developers affected by limitations in node-gyp. build_with_cmake is an example of a CMake-based native addon project.
Uploading precompiled binaries#
The three tools listed here permit native addon developers and maintainers to create and upload binaries to public or private servers. These tools are typically integrated with CI/CD build systems like Travis CI and AppVeyor to build and upload binaries for a variety of platforms and architectures. These binaries are then available for download by users who do not need to have a C/C++ toolchain installed.
node-pre-gyp#
node-pre-gyp is a tool based on node-gyp that adds the ability to upload binaries to a server of the developer's choice. node-pre-gyp has particularly good support for uploading binaries to Amazon S3.
prebuild#
prebuild is a tool that supports builds using either node-gyp or CMake.js. Unlike node-pre-gyp which supports a variety of servers, prebuild uploads binaries only to GitHub releases. prebuild is a good choice for GitHub projects using CMake.js.
prebuildify#
prebuildify is a tool based on node-gyp. The advantage of prebuildify is that the built binaries are bundled with the native addon when it's uploaded to npm. The binaries are downloaded from npm and are immediately available to the module user when the native addon is installed.
Usage#
In order to use the Node-API functions, include the file node_api.h which is located in the src directory in the node development tree:
#include <node_api.h>
This will opt into the default NAPI_VERSION for the given release of Node.js. In order to ensure compatibility with specific versions of Node-API, the version can be specified explicitly when including the header:
#define NAPI_VERSION 3
#include <node_api.h>
This restricts the Node-API surface to just the functionality that was available in the specified (and earlier) versions.
Some of the Node-API surface is experimental and requires explicit opt-in:
#define NAPI_EXPERIMENTAL
#include <node_api.h>
In this case the entire API surface, including any experimental APIs, will be available to the module code.
Occasionally, experimental features are introduced that affect already-released and stable APIs. These features can be disabled by an opt-out:
#define NAPI_EXPERIMENTAL
#define NODE_API_EXPERIMENTAL_<FEATURE_NAME>_OPT_OUT
#include <node_api.h>
where <FEATURE_NAME> is the name of an experimental feature that affects both experimental and stable APIs.
Node-API version matrix#
Up until version 9, Node-API versions were additive and versioned independently from Node.js. This meant that any version was an extension to the previous version in that it had all of the APIs from the previous version with some additions. Each Node.js version only supported a single Node-API version. For example v18.15.0 supports only Node-API version 8. ABI stability was achieved because 8 was a strict superset of all previous versions.
As of version 9, while Node-API versions continue to be versioned independently, an add-on that ran with Node-API version 9 may need code updates to run with Node-API version 10. ABI stability is maintained, however, because Node.js versions that support Node-API versions higher than 8 will support all versions between 8 and the highest version they support and will default to providing the version 8 APIs unless an add-on opts into a higher Node-API version. This approach provides the flexibility of better optimizing existing Node-API functions while maintaining ABI stability. Existing add-ons can continue to run without recompilation using an earlier version of Node-API. If an add-on needs functionality from a newer Node-API version, changes to existing code and recompilation will be needed to use those new functions anyway.
In versions of Node.js that support Node-API version 9 and later, defining NAPI_VERSION=X and using the existing add-on initialization macros will bake in the requested Node-API version that will be used at runtime into the add-on. If NAPI_VERSION is not set it will default to 8.
This table may not be up to date in older streams, the most up to date information is in the latest API documentation in: Node-API version matrix
| Node-API version | Supported In |
|---|---|
| 10 | v22.14.0+, 23.6.0+ and all later versions |
| 9 | v18.17.0+, 20.3.0+, 21.0.0 and all later versions |
| 8 | v12.22.0+, v14.17.0+, v15.12.0+, 16.0.0 and all later versions |
| 7 | v10.23.0+, v12.19.0+, v14.12.0+, 15.0.0 and all later versions |
| 6 | v10.20.0+, v12.17.0+, 14.0.0 and all later versions |
| 5 | v10.17.0+, v12.11.0+, 13.0.0 and all later versions |
| 4 | v10.16.0+, v11.8.0+, 12.0.0 and all later versions |
| 3 | v6.14.2*, 8.11.2+, v9.11.0+*, 10.0.0 and all later versions |
| 2 | v8.10.0+*, v9.3.0+*, 10.0.0 and all later versions |
| 1 | v8.6.0+**, v9.0.0+*, 10.0.0 and all later versions |
* Node-API was experimental.
** Node.js 8.0.0 included Node-API as experimental. It was released as Node-API version 1 but continued to evolve until Node.js 8.6.0. The API is different in versions prior to Node.js 8.6.0. We recommend Node-API version 3 or later.
Each API documented for Node-API will have a header named added in:, and APIs which are stable will have the additional header Node-API version:. APIs are directly usable when using a Node.js version which supports the Node-API version shown in Node-API version: or higher. When using a Node.js version that does not support the Node-API version: listed or if there is no Node-API version: listed, then the API will only be available if #define NAPI_EXPERIMENTAL precedes the inclusion of node_api.h or js_native_api.h. If an API appears not to be available on a version of Node.js which is later than the one shown in added in: then this is most likely the reason for the apparent absence.
The Node-APIs associated strictly with accessing ECMAScript features from native code can be found separately in js_native_api.h and js_native_api_types.h. The APIs defined in these headers are included in node_api.h and node_api_types.h. The headers are structured in this way in order to allow implementations of Node-API outside of Node.js. For those implementations the Node.js specific APIs may not be applicable.
The Node.js-specific parts of an addon can be separated from the code that exposes the actual functionality to the JavaScript environment so that the latter may be used with multiple implementations of Node-API. In the example below, addon.c and addon.h refer only to js_native_api.h. This ensures that addon.c can be reused to compile against either the Node.js implementation of Node-API or any implementation of Node-API outside of Node.js.
addon_node.c is a separate file that contains the Node.js specific entry point to the addon and which instantiates the addon by calling into addon.c when the addon is loaded into a Node.js environment.
// addon.h
#ifndef _ADDON_H_
#define _ADDON_H_
#include <js_native_api.h>
napi_value create_addon(napi_env env);
#endif // _ADDON_H_
// addon.c
#include "addon.h"
#define NODE_API_CALL(env, call) \
do { \
napi_status status = (call); \
if (status != napi_ok) { \
const napi_extended_error_info* error_info = NULL; \
napi_get_last_error_info((env), &error_info); \
const char* err_message = error_info->error_message; \
bool is_pending; \
napi_is_exception_pending((env), &is_pending); \
/* If an exception is already pending, don't rethrow it */ \
if (!is_pending) { \
const char* message = (err_message == NULL) \
? "empty error message" \
: err_message; \
napi_throw_error((env), NULL, message); \
} \
return NULL; \
} \
} while(0)
static napi_value
DoSomethingUseful(napi_env env, napi_callback_info info) {
// Do something useful.
return NULL;
}
napi_value create_addon(napi_env env) {
napi_value result;
NODE_API_CALL(env, napi_create_object(env, &result));
napi_value exported_function;
NODE_API_CALL(env, napi_create_function(env,
"doSomethingUseful",
NAPI_AUTO_LENGTH,
DoSomethingUseful,
NULL,
&exported_function));
NODE_API_CALL(env, napi_set_named_property(env,
result,
"doSomethingUseful",
exported_function));
return result;
}
// addon_node.c
#include <node_api.h>
#include "addon.h"
NAPI_MODULE_INIT(/* napi_env env, napi_value exports */) {
// This function body is expected to return a `napi_value`.
// The variables `napi_env env` and `napi_value exports` may be used within
// the body, as they are provided by the definition of `NAPI_MODULE_INIT()`.
return create_addon(env);
}
Environment life cycle APIs#
Section Agents of the ECMAScript Language Specification defines the concept of an "Agent" as a self-contained environment in which JavaScript code runs. Multiple such Agents may be started and terminated either concurrently or in sequence by the process.
A Node.js environment corresponds to an ECMAScript Agent. In the main process, an environment is created at startup, and additional environments can be created on separate threads to serve as worker threads. When Node.js is embedded in another application, the main thread of the application may also construct and destroy a Node.js environment multiple times during the life cycle of the application process such that each Node.js environment created by the application may, in turn, during its life cycle create and destroy additional environments as worker threads.
From the perspective of a native addon this means that the bindings it provides may be called multiple times, from multiple contexts, and even concurrently from multiple threads.
Native addons may need to allocate global state which they use during their life cycle of an Node.js environment such that the state can be unique to each instance of the addon.
To this end, Node-API provides a way to associate data such that its life cycle is tied to the life cycle of a Node.js environment.
napi_set_instance_data#
napi_status napi_set_instance_data(node_api_basic_env env,
void* data,
napi_finalize finalize_cb,
void* finalize_hint);
[in] env: The environment that the Node-API call is invoked under.[in] data: The data item to make available to bindings of this instance.[in] finalize_cb: The function to call when the environment is being torn down. The function receivesdataso that it might free it.napi_finalizeprovides more details.[in] finalize_hint: Optional hint to pass to the finalize callback during collection.
Returns napi_ok if the API succeeded.
This API associates data with the currently running Node.js environment. data can later be retrieved using napi_get_instance_data(). Any existing data associated with the currently running Node.js environment which was set by means of a previous call to napi_set_instance_data() will be overwritten. If a finalize_cb was provided by the previous call, it will not be called.
napi_get_instance_data#
napi_status napi_get_instance_data(node_api_basic_env env,
void** data);
[in] env: The environment that the Node-API call is invoked under.[out] data: The data item that was previously associated with the currently running Node.js environment by a call tonapi_set_instance_data().
Returns napi_ok if the API succeeded.
This API retrieves data that was previously associated with the currently running Node.js environment via napi_set_instance_data(). If no data is set, the call will succeed and data will be set to NULL.
Basic Node-API data types#
Node-API exposes the following fundamental data types as abstractions that are consumed by the various APIs. These APIs should be treated as opaque, introspectable only with other Node-API calls.
napi_status#
Integral status code indicating the success or failure of a Node-API call. Currently, the following status codes are supported.
typedef enum {
napi_ok,
napi_invalid_arg,
napi_object_expected,
napi_string_expected,
napi_name_expected,
napi_function_expected,
napi_number_expected,
napi_boolean_expected,
napi_array_expected,
napi_generic_failure,
napi_pending_exception,
napi_cancelled,
napi_escape_called_twice,
napi_handle_scope_mismatch,
napi_callback_scope_mismatch,
napi_queue_full,
napi_closing,
napi_bigint_expected,
napi_date_expected,
napi_arraybuffer_expected,
napi_detachable_arraybuffer_expected,
napi_would_deadlock, /* unused */
napi_no_external_buffers_allowed,
napi_cannot_run_js
} napi_status;
If additional information is required upon an API returning a failed status, it can be obtained by calling napi_get_last_error_info.
napi_extended_error_info#
typedef struct {
const char* error_message;
void* engine_reserved;
uint32_t engine_error_code;
napi_status error_code;
} napi_extended_error_info;
error_message: UTF8-encoded string containing a VM-neutral description of the error.engine_reserved: Reserved for VM-specific error details. This is currently not implemented for any VM.engine_error_code: VM-specific error code. This is currently not implemented for any VM.error_code: The Node-API status code that originated with the last error.
See the Error handling section for additional information.
napi_env#
napi_env is used to represent a context that the underlying Node-API implementation can use to persist VM-specific state. This structure is passed to native functions when they're invoked, and it must be passed back when making Node-API calls. Specifically, the same napi_env that was passed in when the initial native function was called must be passed to any subsequent nested Node-API calls. Caching the napi_env for the purpose of general reuse, and passing the napi_env between instances of the same addon running on different Worker threads is not allowed. The napi_env becomes invalid when an instance of a native addon is unloaded. Notification of this event is delivered through the callbacks given to napi_add_env_cleanup_hook and napi_set_instance_data.
node_api_basic_env#
Stability: 1 - Experimental
This variant of napi_env is passed to synchronous finalizers (node_api_basic_finalize). There is a subset of Node-APIs which accept a parameter of type node_api_basic_env as their first argument. These APIs do not access the state of the JavaScript engine and are thus safe to call from synchronous finalizers. Passing a parameter of type napi_env to these APIs is allowed, however, passing a parameter of type node_api_basic_env to APIs that access the JavaScript engine state is not allowed. Attempting to do so without a cast will produce a compiler warning or an error when add-ons are compiled with flags which cause them to emit warnings and/or errors when incorrect pointer types are passed into a function. Calling such APIs from a synchronous finalizer will ultimately result in the termination of the application.
napi_value#
This is an opaque pointer that is used to represent a JavaScript value.
napi_threadsafe_function#
This is an opaque pointer that represents a JavaScript function which can be called asynchronously from multiple threads via napi_call_threadsafe_function().
napi_threadsafe_function_release_mode#
A value to be given to napi_release_threadsafe_function() to indicate whether the thread-safe function is to be closed immediately (napi_tsfn_abort) or merely released (napi_tsfn_release) and thus available for subsequent use via napi_acquire_threadsafe_function() and napi_call_threadsafe_function().
typedef enum {
napi_tsfn_release,
napi_tsfn_abort
} napi_threadsafe_function_release_mode;
napi_threadsafe_function_call_mode#
A value to be given to napi_call_threadsafe_function() to indicate whether the call should block whenever the queue associated with the thread-safe function is full.
typedef enum {
napi_tsfn_nonblocking,
napi_tsfn_blocking
} napi_threadsafe_function_call_mode;
Node-API memory management types#
napi_handle_scope#
This is an abstraction used to control and modify the lifetime of objects created within a particular scope. In general, Node-API values are created within the context of a handle scope. When a native method is called from JavaScript, a default handle scope will exist. If the user does not explicitly create a new handle scope, Node-API values will be created in the default handle scope. For any invocations of code outside the execution of a native method (for instance, during a libuv callback invocation), the module is required to create a scope before invoking any functions that can result in the creation of JavaScript values.
Handle scopes are created using napi_open_handle_scope and are destroyed using napi_close_handle_scope. Closing the scope can indicate to the GC that all napi_values created during the lifetime of the handle scope are no longer referenced from the current stack frame.
For more details, review the Object lifetime management.
napi_escapable_handle_scope#
Escapable handle scopes are a special type of handle scope to return values created within a particular handle scope to a parent scope.
napi_ref#
This is the abstraction to use to reference a napi_value. This allows for users to manage the lifetimes of JavaScript values, including defining their minimum lifetimes explicitly.
For more details, review the Object lifetime management.
napi_type_tag#
A 128-bit value stored as two unsigned 64-bit integers. It serves as a UUID with which JavaScript objects or externals can be "tagged" in order to ensure that they are of a certain type. This is a stronger check than napi_instanceof, because the latter can report a false positive if the object's prototype has been manipulated. Type-tagging is most useful in conjunction with napi_wrap because it ensures that the pointer retrieved from a wrapped object can be safely cast to the native type corresponding to the type tag that had been previously applied to the JavaScript object.
typedef struct {
uint64_t lower;
uint64_t upper;
} napi_type_tag;
napi_async_cleanup_hook_handle#
An opaque value returned by napi_add_async_cleanup_hook. It must be passed to napi_remove_async_cleanup_hook when the chain of asynchronous cleanup events completes.
Node-API callback types#
napi_callback_info#
Opaque datatype that is passed to a callback function. It can be used for getting additional information about the context in which the callback was invoked.
napi_callback#
Function pointer type for user-provided native functions which are to be exposed to JavaScript via Node-API. Callback functions should satisfy the following signature:
typedef napi_value (*napi_callback)(napi_env, napi_callback_info);
Unless for reasons discussed in Object Lifetime Management, creating a handle and/or callback scope inside a napi_callback is not necessary.
node_api_basic_finalize#
Stability: 1 - Experimental
Function pointer type for add-on provided functions that allow the user to be notified when externally-owned data is ready to be cleaned up because the object it was associated with has been garbage-collected. The user must provide a function satisfying the following signature which would get called upon the object's collection. Currently, node_api_basic_finalize can be used for finding out when objects that have external data are collected.
typedef void (*node_api_basic_finalize)(node_api_basic_env env,
void* finalize_data,
void* finalize_hint);
Unless for reasons discussed in Object Lifetime Management, creating a handle and/or callback scope inside the function body is not necessary.
Since these functions may be called while the JavaScript engine is in a state where it cannot execute JavaScript code, only Node-APIs which accept a node_api_basic_env as their first parameter may be called. node_api_post_finalizer can be used to schedule Node-API calls that require access to the JavaScript engine's state to run after the current garbage collection cycle has completed.
In the case of node_api_create_external_string_latin1 and node_api_create_external_string_utf16 the env parameter may be null, because external strings can be collected during the latter part of environment shutdown.
Change History:
experimental (
NAPI_EXPERIMENTAL):Only Node-API calls that accept a
node_api_basic_envas their first parameter may be called, otherwise the application will be terminated with an appropriate error message. This feature can be turned off by definingNODE_API_EXPERIMENTAL_BASIC_ENV_OPT_OUT.
napi_finalize#
Function pointer type for add-on provided function that allow the user to schedule a group of calls to Node-APIs in response to a garbage collection event, after the garbage collection cycle has completed. These function pointers can be used with node_api_post_finalizer.
typedef void (*napi_finalize)(napi_env env,
void* finalize_data,
void* finalize_hint);
Change History:
experimental (
NAPI_EXPERIMENTALis defined):A function of this type may no longer be used as a finalizer, except with
node_api_post_finalizer.node_api_basic_finalizemust be used instead. This feature can be turned off by definingNODE_API_EXPERIMENTAL_BASIC_ENV_OPT_OUT.
napi_async_execute_callback#
Function pointer used with functions that support asynchronous operations. Callback functions must satisfy the following signature:
typedef void (*napi_async_execute_callback)(napi_env env, void* data);
Implementations of this function must avoid making Node-API calls that execute JavaScript or interact with JavaScript objects. Node-API calls should be in the napi_async_complete_callback instead. Do not use the napi_env parameter as it will likely result in execution of JavaScript.
napi_async_complete_callback#
Function pointer used with functions that support asynchronous operations. Callback functions must satisfy the following signature:
typedef void (*napi_async_complete_callback)(napi_env env,
napi_status status,
void* data);
Unless for reasons discussed in Object Lifetime Management, creating a handle and/or callback scope inside the function body is not necessary.
napi_threadsafe_function_call_js#
Function pointer used with asynchronous thread-safe function calls. The callback will be called on the main thread. Its purpose is to use a data item arriving via the queue from one of the secondary threads to construct the parameters necessary for a call into JavaScript, usually via napi_call_function, and then make the call into JavaScript.
The data arriving from the secondary thread via the queue is given in the data parameter and the JavaScript function to call is given in the js_callback parameter.
Node-API sets up the environment prior to calling this callback, so it is sufficient to call the JavaScript function via napi_call_function rather than via napi_make_callback.
Callback functions must satisfy the following signature:
typedef void (*napi_threadsafe_function_call_js)(napi_env env,
napi_value js_callback,
void* context,
void* data);
[in] env: The environment to use for API calls, orNULLif the thread-safe function is being torn down anddatamay need to be freed.[in] js_callback: The JavaScript function to call, orNULLif the thread-safe function is being torn down anddatamay need to be freed. It may also beNULLif the thread-safe function was created withoutjs_callback.[in] context: The optional data with which the thread-safe function was created.[in] data: Data created by the secondary thread. It is the responsibility of the callback to convert this native data to JavaScript values (with Node-API functions) that can be passed as parameters whenjs_callbackis invoked. This pointer is managed entirely by the threads and this callback. Thus this callback should free the data.
Unless for reasons discussed in Object Lifetime Management, creating a handle and/or callback scope inside the function body is not necessary.
napi_cleanup_hook#
Function pointer used with napi_add_env_cleanup_hook. It will be called when the environment is being torn down.
Callback functions must satisfy the following signature:
typedef void (*napi_cleanup_hook)(void* data);
[in] data: The data that was passed tonapi_add_env_cleanup_hook.
napi_async_cleanup_hook#
Function pointer used with napi_add_async_cleanup_hook. It will be called when the environment is being torn down.
Callback functions must satisfy the following signature:
typedef void (*napi_async_cleanup_hook)(napi_async_cleanup_hook_handle handle,
void* data);
[in] handle: The handle that must be passed tonapi_remove_async_cleanup_hookafter completion of the asynchronous cleanup.[in] data: The data that was passed tonapi_add_async_cleanup_hook.
The body of the function should initiate the asynchronous cleanup actions at the end of which handle must be passed in a call to napi_remove_async_cleanup_hook.
Error handling#
Node-API uses both return values and JavaScript exceptions for error handling. The following sections explain the approach for each case.
Return values#
All of the Node-API functions share the same error handling pattern. The return type of all API functions is napi_status.
The return value will be napi_ok if the request was successful and no uncaught JavaScript exception was thrown. If an error occurred AND an exception was thrown, the napi_status value for the error will be returned. If an exception was thrown, and no error occurred, napi_pending_exception will be returned.
In cases where a return value other than napi_ok or napi_pending_exception is returned, napi_is_exception_pending must be called to check if an exception is pending. See the section on exceptions for more details.
The full set of possible napi_status values is defined in napi_api_types.h.
The napi_status return value provides a VM-independent representation of the error which occurred. In some cases it is useful to be able to get more detailed information, including a string representing the error as well as VM (engine)-specific information.
In order to retrieve this information napi_get_last_error_info is provided which returns a napi_extended_error_info structure. The format of the napi_extended_error_info structure is as follows:
typedef struct napi_extended_error_info {
const char* error_message;
void* engine_reserved;
uint32_t engine_error_code;
napi_status error_code;
};
error_message: Textual representation of the error that occurred.engine_reserved: Opaque handle reserved for engine use only.engine_error_code: VM specific error code.error_code: Node-API status code for the last error.
napi_get_last_error_info returns the information for the last Node-API call that was made.
Do not rely on the content or format of any of the extended information as it is not subject to SemVer and may change at any time. It is intended only for logging purposes.
napi_get_last_error_info#
napi_status
napi_get_last_error_info(node_api_basic_env env,
const napi_extended_error_info** result);
[in] env: The environment that the API is invoked under.[out] result: Thenapi_extended_error_infostructure with more information about the error.
Returns napi_ok if the API succeeded.
This API retrieves a napi_extended_error_info structure with information about the last error that occurred.
The content of the napi_extended_error_info returned is only valid up until a Node-API function is called on the same env. This includes a call to napi_is_exception_pending so it may often be necessary to make a copy of the information so that it can be used later. The pointer returned in error_message points to a statically-defined string so it is safe to use that pointer if you have copied it out of the error_message field (which will be overwritten) before another Node-API function was called.
Do not rely on the content or format of any of the extended information as it is not subject to SemVer and may change at any time. It is intended only for logging purposes.
This API can be called even if there is a pending JavaScript exception.
Exceptions#
Any Node-API function call may result in a pending JavaScript exception. This is the case for any of the API functions, even those that may not cause the execution of JavaScript.
If the napi_status returned by a function is napi_ok then no exception is pending and no additional action is required. If the napi_status returned is anything other than napi_ok or napi_pending_exception, in order to try to recover and continue instead of simply returning immediately, napi_is_exception_pending must be called in order to determine if an exception is pending or not.
In many cases when a Node-API function is called and an exception is already pending, the function will return immediately with a napi_status of napi_pending_exception. However, this is not the case for all functions. Node-API allows a subset of the functions to be called to allow for some minimal cleanup before returning to JavaScript. In that case, napi_status will reflect the status for the function. It will not reflect previous pending exceptions. To avoid confusion, check the error status after every function call.
When an exception is pending one of two approaches can be employed.
The first approach is to do any appropriate cleanup and then return so that execution will return to JavaScript. As part of the transition back to JavaScript, the exception will be thrown at the point in the JavaScript code where the native method was invoked. The behavior of most Node-API calls is unspecified while an exception is pending, and many will simply return napi_pending_exception, so do as little as possible and then return to JavaScript where the exception can be handled.
The second approach is to try to handle the exception. There will be cases where the native code can catch the exception, take the appropriate action, and then continue. This is only recommended in specific cases where it is known that the exception can be safely handled. In these cases napi_get_and_clear_last_exception can be used to get and clear the exception. On success, result will contain the handle to the last JavaScript Object thrown. If it is determined, after retrieving the exception, the exception cannot be handled after all it can be re-thrown it with napi_throw where error is the JavaScript value to be thrown.
The following utility functions are also available in case native code needs to throw an exception or determine if a napi_value is an instance of a JavaScript Error object: napi_throw_error, napi_throw_type_error, napi_throw_range_error, node_api_throw_syntax_error and napi_is_error.
The following utility functions are also available in case native code needs to create an Error object: napi_create_error, napi_create_type_error, napi_create_range_error and node_api_create_syntax_error, where result is the napi_value that refers to the newly created JavaScript Error object.
The Node.js project is adding error codes to all of the errors generated internally. The goal is for applications to use these error codes for all error checking. The associated error messages will remain, but will only be meant to be used for logging and display with the expectation that the message can change without SemVer applying. In order to support this model with Node-API, both in internal functionality and for module specific functionality (as its good practice), the throw_ and create_ functions take an optional code parameter which is the string for the code to be added to the error object. If the optional parameter is NULL then no code will be associated with the error. If a code is provided, the name associated with the error is also updated to be:
originalName [code]
where originalName is the original name associated with the error and code is the code that was provided. For example, if the code is 'ERR_ERROR_1' and a TypeError is being created the name will be:
TypeError [ERR_ERROR_1]
napi_throw#
NAPI_EXTERN napi_status napi_throw(napi_env env, napi_value error);
[in] env: The environment that the API is invoked under.[in] error: The JavaScript value to be thrown.
Returns napi_ok if the API succeeded.
This API throws the JavaScript value provided.
napi_throw_error#
NAPI_EXTERN napi_status napi_throw_error(napi_env env,
const char* code,
const char* msg);
[in] env: The environment that the API is invoked under.[in] code: Optional error code to be set on the error.[in] msg: C string representing the text to be associated with the error.
Returns napi_ok if the API succeeded.
This API throws a JavaScript Error with the text provided.
napi_throw_type_error#
NAPI_EXTERN napi_status napi_throw_type_error(napi_env env,
const char* code,
const char* msg);
[in] env: The environment that the API is invoked under.[in] code: Optional error code to be set on the error.[in] msg: C string representing the text to be associated with the error.
Returns napi_ok if the API succeeded.
This API throws a JavaScript TypeError with the text provided.
napi_throw_range_error#
NAPI_EXTERN napi_status napi_throw_range_error(napi_env env,
const char* code,
const char* msg);
[in] env: The environment that the API is invoked under.[in] code: Optional error code to be set on the error.[in] msg: C string representing the text to be associated with the error.
Returns napi_ok if the API succeeded.
This API throws a JavaScript RangeError with the text provided.
node_api_throw_syntax_error#
NAPI_EXTERN napi_status node_api_throw_syntax_error(napi_env env,
const char* code,
const char* msg);
[in] env: The environment that the API is invoked under.[in] code: Optional error code to be set on the error.[in] msg: C string representing the text to be associated with the error.
Returns napi_ok if the API succeeded.
This API throws a JavaScript SyntaxError with the text provided.
napi_is_error#
NAPI_EXTERN napi_status napi_is_error(napi_env env,
napi_value value,
bool* result);
[in] env: The environment that the API is invoked under.[in] value: Thenapi_valueto be checked.[out] result: Boolean value that is set to true ifnapi_valuerepresents an error, false otherwise.
Returns napi_ok if the API succeeded.
This API queries a napi_value to check if it represents an error object.
napi_create_error#
NAPI_EXTERN napi_status napi_create_error(napi_env env,
napi_value code,
napi_value msg,
napi_value* result);
[in] env: The environment that the API is invoked under.[in] code: Optionalnapi_valuewith the string for the error code to be associated with the error.[in] msg:napi_valuethat references a JavaScriptstringto be used as the message for theError.[out] result:napi_valuerepresenting the error created.
Returns napi_ok if the API succeeded.
This API returns a JavaScript Error with the text provided.
napi_create_type_error#
NAPI_EXTERN napi_status napi_create_type_error(napi_env env,
napi_value code,
napi_value msg,
napi_value* result);
[in] env: The environment that the API is invoked under.[in] code: Optionalnapi_valuewith the string for the error code to be associated with the error.[in] msg:napi_valuethat references a JavaScriptstringto be used as the message for theError.[out] result:napi_valuerepresenting the error created.
Returns napi_ok if the API succeeded.
This API returns a JavaScript TypeError with the text provided.
napi_create_range_error#
NAPI_EXTERN napi_status napi_create_range_error(napi_env env,
napi_value code,
napi_value msg,
napi_value* result);
[in] env: The environment that the API is invoked under.[in] code: Optionalnapi_valuewith the string for the error code to be associated with the error.[in] msg:napi_valuethat references a JavaScriptstringto be used as the message for theError.[out] result:napi_valuerepresenting the error created.
Returns napi_ok if the API succeeded.
This API returns a JavaScript RangeError with the text provided.
node_api_create_syntax_error#
NAPI_EXTERN napi_status node_api_create_syntax_error(napi_env env,
napi_value code,
napi_value msg,
napi_value* result);
[in] env: The environment that the API is invoked under.[in] code: Optionalnapi_valuewith the string for the error code to be associated with the error.[in] msg:napi_valuethat references a JavaScriptstringto be used as the message for theError.[out] result:napi_valuerepresenting the error created.
Returns napi_ok if the API succeeded.
This API returns a JavaScript SyntaxError with the text provided.
napi_get_and_clear_last_exception#
napi_status napi_get_and_clear_last_exception(napi_env env,
napi_value* result);
[in] env: The environment that the API is invoked under.[out] result: The exception if one is pending,NULLotherwise.
Returns napi_ok if the API succeeded.
This API can be called even if there is a pending JavaScript exception.
napi_is_exception_pending#
napi_status napi_is_exception_pending(napi_env env, bool* result);
[in] env: The environment that the API is invoked under.[out] result: Boolean value that is set to true if an exception is pending.
Returns napi_ok if the API succeeded.
This API can be called even if there is a pending JavaScript exception.
napi_fatal_exception#
napi_status napi_fatal_exception(napi_env env, napi_value err);
[in] env: The environment that the API is invoked under.[in] err: The error that is passed to'uncaughtException'.
Trigger an 'uncaughtException' in JavaScript. Useful if an async callback throws an exception with no way to recover.
Fatal errors#
In the event of an unrecoverable error in a native addon, a fatal error can be thrown to immediately terminate the process.
napi_fatal_error#
NAPI_NO_RETURN void napi_fatal_error(const char* location,
size_t location_len,
const char* message,
size_t message_len);
[in] location: Optional location at which the error occurred.[in] location_len: The length of the location in bytes, orNAPI_AUTO_LENGTHif it is null-terminated.[in] message: The message associated with the error.[in] message_len: The length of the message in bytes, orNAPI_AUTO_LENGTHif it is null-terminated.
The function call does not return, the process will be terminated.
This API can be called even if there is a pending JavaScript exception.
Object lifetime management#
As Node-API calls are made, handles to objects in the heap for the underlying VM may be returned as napi_values. These handles must hold the objects 'live' until they are no longer required by the native code, otherwise the objects could be collected before the native code was finished using them.
As object handles are returned they are associated with a 'scope'. The lifespan for the default scope is tied to the lifespan of the native method call. The result is that, by default, handles remain valid and the objects associated with these handles will be held live for the lifespan of the native method call.
In many cases, however, it is necessary that the handles remain valid for either a shorter or longer lifespan than that of the native method. The sections which follow describe the Node-API functions that can be used to change the handle lifespan from the default.
Making handle lifespan shorter than that of the native method#
It is often necessary to make the lifespan of handles shorter than the lifespan of a native method. For example, consider a native method that has a loop which iterates through the elements in a large array:
for (int i = 0; i < 1000000; i++) {
napi_value result;
napi_status status = napi_get_element(env, object, i, &result);
if (status != napi_ok) {
break;
}
// do something with element
}
This would result in a large number of handles being created, consuming substantial resources. In addition, even though the native code could only use the most recent handle, all of the associated objects would also be kept alive since they all share the same scope.
To handle this case, Node-API provides the ability to establish a new 'scope' to which newly created handles will be associated. Once those handles are no longer required, the scope can be 'closed' and any handles associated with the scope are invalidated. The methods available to open/close scopes are napi_open_handle_scope and napi_close_handle_scope.
Node-API only supports a single nested hierarchy of scopes. There is only one active scope at any time, and all new handles will be associated with that scope while it is active. Scopes must be closed in the reverse order from which they are opened. In addition, all scopes created within a native method must be closed before returning from that method.
Taking the earlier example, adding calls to napi_open_handle_scope and napi_close_handle_scope would ensure that at most a single handle is valid throughout the execution of the loop:
for (int i = 0; i < 1000000; i++) {
napi_handle_scope scope;
napi_status status = napi_open_handle_scope(env, &scope);
if (status != napi_ok) {
break;
}
napi_value result;
status = napi_get_element(env, object, i, &result);
if (status != napi_ok) {
break;
}
// do something with element
status = napi_close_handle_scope(env, scope);
if (status != napi_ok) {
break;
}
}
When nesting scopes, there are cases where a handle from an inner scope needs to live beyond the lifespan of that scope. Node-API supports an 'escapable scope' in order to support this case. An escapable scope allows one handle to be 'promoted' so that it 'escapes' the current scope and the lifespan of the handle changes from the current scope to that of the outer scope.
The methods available to open/close escapable scopes are napi_open_escapable_handle_scope and napi_close_escapable_handle_scope.
The request to promote a handle is made through napi_escape_handle which can only be called once.
napi_open_handle_scope#
NAPI_EXTERN napi_status napi_open_handle_scope(napi_env env,
napi_handle_scope* result);
[in] env: The environment that the API is invoked under.[out] result:napi_valuerepresenting the new scope.
Returns napi_ok if the API succeeded.
This API opens a new scope.
napi_close_handle_scope#
NAPI_EXTERN napi_status napi_close_handle_scope(napi_env env,
napi_handle_scope scope);
[in] env: The environment that the API is invoked under.[in] scope:napi_valuerepresenting the scope to be closed.
Returns napi_ok if the API succeeded.
This API closes the scope passed in. Scopes must be closed in the reverse order from which they were created.
This API can be called even if there is a pending JavaScript exception.
napi_open_escapable_handle_scope#
NAPI_EXTERN napi_status
napi_open_escapable_handle_scope(napi_env env,
napi_handle_scope* result);
[in] env: The environment that the API is invoked under.[out] result:napi_valuerepresenting the new scope.
Returns napi_ok if the API succeeded.
This API opens a new scope from which one object can be promoted to the outer scope.
napi_close_escapable_handle_scope#
NAPI_EXTERN napi_status
napi_close_escapable_handle_scope(napi_env env,
napi_handle_scope scope);
[in] env: The environment that the API is invoked under.[in] scope:napi_valuerepresenting the scope to be closed.
Returns napi_ok if the API succeeded.
This API closes the scope passed in. Scopes must be closed in the reverse order from which they were created.
This API can be called even if there is a pending JavaScript exception.
napi_escape_handle#
napi_status napi_escape_handle(napi_env env,
napi_escapable_handle_scope scope,
napi_value escapee,
napi_value* result);
[in] env: The environment that the API is invoked under.[in] scope:napi_valuerepresenting the current scope.[in] escapee:napi_valuerepresenting the JavaScriptObjectto be escaped.[out] result:napi_valuerepresenting the handle to the escapedObjectin the outer scope.
Returns napi_ok if the API succeeded.
This API promotes the handle to the JavaScript object so that it is valid for the lifetime of the outer scope. It can only be called once per scope. If it is called more than once an error will be returned.
This API can be called even if there is a pending JavaScript exception.
References to values with a lifespan longer than that of the native method#
In some cases, an addon will need to be able to create and reference values with a lifespan longer than that of a single native method invocation. For example, to create a constructor and later use that constructor in a request to create instances, it must be possible to reference the constructor object across many different instance creation requests. This would not be possible with a normal handle returned as a napi_value as described in the earlier section. The lifespan of a normal handle is managed by scopes and all scopes must be closed before the end of a native method.
Node-API provides methods for creating persistent references to values. Currently Node-API only allows references to be created for a limited set of value types, including object, external, function, and symbol.
Each reference has an associated count with a value of 0 or higher, which determines whether the reference will keep the corresponding value alive. References with a count of 0 do not prevent values from being collected. Values of object (object, function, external) and symbol types are becoming 'weak' references and can still be accessed while they are not collected. Any count greater than 0 will prevent the values from being collected.
Symbol values have different flavors. The true weak reference behavior is only supported by local symbols created with the napi_create_symbol function or the JavaScript Symbol() constructor calls. Globally registered symbols created with the node_api_symbol_for function or JavaScript Symbol.for() function calls remain always strong references because the garbage collector does not collect them. The same is true for well-known symbols such as Symbol.iterator. They are also never collected by the garbage collector.
References can be created with an initial reference count. The count can then be modified through napi_reference_ref and napi_reference_unref. If an object is collected while the count for a reference is 0, all subsequent calls to get the object associated with the reference napi_get_reference_value will return NULL for the returned napi_value. An attempt to call napi_reference_ref for a reference whose object has been collected results in an error.
References must be deleted once they are no longer required by the addon. When a reference is deleted, it will no longer prevent the corresponding object from being collected. Failure to delete a persistent reference results in a 'memory leak' with both the native memory for the persistent reference and the corresponding object on the heap being retained forever.
There can be multiple persistent references created which refer to the same object, each of which will either keep the object live or not based on its individual count. Multiple persistent references to the same object can result in unexpectedly keeping alive native memory. The native structures for a persistent reference must be kept alive until finalizers for the referenced object are executed. If a new persistent reference is created for the same object, the finalizers for that object will not be run and the native memory pointed by the earlier persistent reference will not be freed. This can be avoided by calling napi_delete_reference in addition to napi_reference_unref when possible.
Change History:
Version 10 (
NAPI_VERSIONis defined as10or higher):References can be created for all value types. The new supported value types do not support weak reference semantic and the values of these types are released when the reference count becomes 0 and cannot be accessed from the reference anymore.
napi_create_reference#
NAPI_EXTERN napi_status napi_create_reference(napi_env env,
napi_value value,
uint32_t initial_refcount,
napi_ref* result);
[in] env: The environment that the API is invoked under.[in] value: Thenapi_valuefor which a reference is being created.[in] initial_refcount: Initial reference count for the new reference.[out] result:napi_refpointing to the new reference.
Returns napi_ok if the API succeeded.
This API creates a new reference with the specified reference count to the value passed in.
napi_delete_reference#
NAPI_EXTERN napi_status napi_delete_reference(napi_env env, napi_ref ref);
[in] env: The environment that the API is invoked under.[in] ref:napi_refto be deleted.
Returns napi_ok if the API succeeded.
This API deletes the reference passed in.
This API can be called even if there is a pending JavaScript exception.
napi_reference_ref#
NAPI_EXTERN napi_status napi_reference_ref(napi_env env,
napi_ref ref,
uint32_t* result);
[in] env: The environment that the API is invoked under.[in] ref:napi_reffor which the reference count will be incremented.[out] result: The new reference count.
Returns napi_ok if the API succeeded.
This API increments the reference count for the reference passed in and returns the resulting reference count.
napi_reference_unref#
NAPI_EXTERN napi_status napi_reference_unref(napi_env env,
napi_ref ref,
uint32_t* result);
[in] env: The environment that the API is invoked under.[in] ref:napi_reffor which the reference count will be decremented.[out] result: The new reference count.
Returns napi_ok if the API succeeded.
This API decrements the reference count for the reference passed in and returns the resulting reference count.
napi_get_reference_value#
NAPI_EXTERN napi_status napi_get_reference_value(napi_env env,
napi_ref ref,
napi_value* result);
[in] env: The environment that the API is invoked under.[in] ref: Thenapi_reffor which the corresponding value is being requested.[out] result: Thenapi_valuereferenced by thenapi_ref.
Returns napi_ok if the API succeeded.
If still valid, this API returns the napi_value representing the JavaScript value associated with the napi_ref. Otherwise, result will be NULL.
Cleanup on exit of the current Node.js environment#
While a Node.js process typically releases all its resources when exiting, embedders of Node.js, or future Worker support, may require addons to register clean-up hooks that will be run once the current Node.js environment exits.
Node-API provides functions for registering and un-registering such callbacks. When those callbacks are run, all resources that are being held by the addon should be freed up.
napi_add_env_cleanup_hook#
NODE_EXTERN napi_status napi_add_env_cleanup_hook(node_api_basic_env env,
napi_cleanup_hook fun,
void* arg);
Registers fun as a function to be run with the arg parameter once the current Node.js environment exits.
A function can safely be specified multiple times with different arg values. In that case, it will be called multiple times as well. Providing the same fun and arg values multiple times is not allowed and will lead the process to abort.
The hooks will be called in reverse order, i.e. the most recently added one will be called first.
Removing this hook can be done by using napi_remove_env_cleanup_hook. Typically, that happens when the resource for which this hook was added is being torn down anyway.
For asynchronous cleanup, napi_add_async_cleanup_hook is available.
napi_remove_env_cleanup_hook#
NAPI_EXTERN napi_status napi_remove_env_cleanup_hook(node_api_basic_env env,
void (*fun)(void* arg),
void* arg);
Unregisters fun as a function to be run with the arg parameter once the current Node.js environment exits. Both the argument and the function value need to be exact matches.
The function must have originally been registered with napi_add_env_cleanup_hook, otherwise the process will abort.
napi_add_async_cleanup_hook#
NAPI_EXTERN napi_status napi_add_async_cleanup_hook(
node_api_basic_env env,
napi_async_cleanup_hook hook,
void* arg,
napi_async_cleanup_hook_handle* remove_handle);
[in] env: The environment that the API is invoked under.[in] hook: The function pointer to call at environment teardown.[in] arg: The pointer to pass tohookwhen it gets called.[out] remove_handle: Optional handle that refers to the asynchronous cleanup hook.
Registers hook, which is a function of type napi_async_cleanup_hook, as a function to be run with the remove_handle and arg parameters once the current Node.js environment exits.
Unlike napi_add_env_cleanup_hook, the hook is allowed to be asynchronous.
Otherwise, behavior generally matches that of napi_add_env_cleanup_hook.
If remove_handle is not NULL, an opaque value will be stored in it that must later be passed to napi_remove_async_cleanup_hook, regardless of whether the hook has already been invoked. Typically, that happens when the resource for which this hook was added is being torn down anyway.
napi_remove_async_cleanup_hook#
NAPI_EXTERN napi_status napi_remove_async_cleanup_hook(
napi_async_cleanup_hook_handle remove_handle);
[in] remove_handle: The handle to an asynchronous cleanup hook that was created withnapi_add_async_cleanup_hook.
Unregisters the cleanup hook corresponding to remove_handle. This will prevent the hook from being executed, unless it has already started executing. This must be called on any napi_async_cleanup_hook_handle value obtained from napi_add_async_cleanup_hook.
Finalization on the exit of the Node.js environment#
The Node.js environment may be torn down at an arbitrary time as soon as possible with JavaScript execution disallowed, like on the request of worker.terminate(). When the environment is being torn down, the registered napi_finalize callbacks of JavaScript objects, thread-safe functions and environment instance data are invoked immediately and independently.
The invocation of napi_finalize callbacks is scheduled after the manually registered cleanup hooks. In order to ensure a proper order of addon finalization during environment shutdown to avoid use-after-free in the napi_finalize callback, addons should register a cleanup hook with napi_add_env_cleanup_hook and napi_add_async_cleanup_hook to manually release the allocated resource in a proper order.
Module registration#
Node-API modules are registered in a manner similar to other modules except that instead of using the NODE_MODULE macro the following is used:
NAPI_MODULE(NODE_GYP_MODULE_NAME, Init)
The next difference is the signature for the Init method. For a Node-API module it is as follows:
napi_value Init(napi_env env, napi_value exports);
The return value from Init is treated as the exports object for the module. The Init method is passed an empty object via the exports parameter as a convenience. If Init returns NULL, the parameter passed as exports is exported by the module. Node-API modules cannot modify the module object but can specify anything as the exports property of the module.
To add the method hello as a function so that it can be called as a method provided by the addon:
napi_value Init(napi_env env, napi_value exports) {
napi_status status;
napi_property_descriptor desc = {
"hello",
NULL,
Method,
NULL,
NULL,
NULL,
napi_writable | napi_enumerable | napi_configurable,
NULL
};
status = napi_define_properties(env, exports, 1, &desc);
if (status != napi_ok) return NULL;
return exports;
}
To set a function to be returned by the require() for the addon:
napi_value Init(napi_env env, napi_value exports) {
napi_value method;
napi_status status;
status = napi_create_function(env, "exports", NAPI_AUTO_LENGTH, Method, NULL, &method);
if (status != napi_ok) return NULL;
return method;
}
To define a class so that new instances can be created (often used with Object wrap):
// NOTE: partial example, not all referenced code is included
napi_value Init(napi_env env, napi_value exports) {
napi_status status;
napi_property_descriptor properties[] = {
{ "value", NULL, NULL, GetValue, SetValue, NULL, napi_writable | napi_configurable, NULL },
DECLARE_NAPI_METHOD("plusOne", PlusOne),
DECLARE_NAPI_METHOD("multiply", Multiply),
};
napi_value cons;
status =
napi_define_class(env, "MyObject", New, NULL, 3, properties, &cons);
if (status != napi_ok) return NULL;
status = napi_create_reference(env, cons, 1, &constructor);
if (status != napi_ok) return NULL;
status = napi_set_named_property(env, exports, "MyObject", cons);
if (status != napi_ok) return NULL;
return exports;
}
You can also use the NAPI_MODULE_INIT macro, which acts as a shorthand for NAPI_MODULE and defining an Init function:
NAPI_MODULE_INIT(/* napi_env env, napi_value exports */) {
napi_value answer;
napi_status result;
status = napi_create_int64(env, 42, &answer);
if (status != napi_ok) return NULL;
status = napi_set_named_property(env, exports, "answer", answer);
if (status != napi_ok) return NULL;
return exports;
}
The parameters env and exports are provided to the body of the NAPI_MODULE_INIT macro.
All Node-API addons are context-aware, meaning they may be loaded multiple times. There are a few design considerations when declaring such a module. The documentation on context-aware addons provides more details.
The variables env and exports will be available inside the function body following the macro invocation.
For more details on setting properties on objects, see the section on Working with JavaScript properties.
For more details on building addon modules in general, refer to the existing API.
Working with JavaScript values#
Node-API exposes a set of APIs to create all types of JavaScript values. Some of these types are documented under Section language types of the ECMAScript Language Specification.
Fundamentally, these APIs are used to do one of the following:
- Create a new JavaScript object
- Convert from a primitive C type to a Node-API value
- Convert from Node-API value to a primitive C type
- Get global instances including
undefinedandnull
Node-API values are represented by the type napi_value. Any Node-API call that requires a JavaScript value takes in a napi_value. In some cases, the API does check the type of the napi_value up-front. However, for better performance, it's better for the caller to make sure that the napi_value in question is of the JavaScript type expected by the API.
Enum types#
napi_key_collection_mode#
typedef enum {
napi_key_include_prototypes,
napi_key_own_only
} napi_key_collection_mode;
Describes the Keys/Properties filter enums:
napi_key_collection_mode limits the range of collected properties.
napi_key_own_only limits the collected properties to the given object only. napi_key_include_prototypes will include all keys of the objects's prototype chain as well.
napi_key_filter#
typedef enum {
napi_key_all_properties = 0,
napi_key_writable = 1,
napi_key_enumerable = 1 << 1,
napi_key_configurable = 1 << 2,
napi_key_skip_strings = 1 << 3,
napi_key_skip_symbols = 1 << 4
} napi_key_filter;
Property filter bit flag. This works with bit operators to build a composite filter.
napi_key_conversion#
typedef enum {
napi_key_keep_numbers,
napi_key_numbers_to_strings
} napi_key_conversion;
napi_key_numbers_to_strings will convert integer indexes to strings. napi_key_keep_numbers will return numbers for integer indexes.
napi_valuetype#
typedef enum {
// ES6 types (corresponds to typeof)
napi_undefined,
napi_null,
napi_boolean,
napi_number,
napi_string,
napi_symbol,
napi_object,
napi_function,
napi_external,
napi_bigint,
} napi_valuetype;
Describes the type of a napi_value. This generally corresponds to the types described in Section language types of the ECMAScript Language Specification. In addition to types in that section, napi_valuetype can also represent Functions and Objects with external data.
A JavaScript value of type napi_external appears in JavaScript as a plain object such that no properties can be set on it, and no prototype.
napi_typedarray_type#
typedef enum {
napi_int8_array,
napi_uint8_array,
napi_uint8_clamped_array,
napi_int16_array,
napi_uint16_array,
napi_int32_array,
napi_uint32_array,
napi_float32_array,
napi_float64_array,
napi_bigint64_array,
napi_biguint64_array,
napi_float16_array,
} napi_typedarray_type;
This represents the underlying binary scalar datatype of the TypedArray. Elements of this enum correspond to Section TypedArray objects of the ECMAScript Language Specification.
Object creation functions#
napi_create_array#
napi_status napi_create_array(napi_env env, napi_value* result)
[in] env: The environment that the Node-API call is invoked under.[out] result: Anapi_valuerepresenting a JavaScriptArray.
Returns napi_ok if the API succeeded.
This API returns a Node-API value corresponding to a JavaScript Array type. JavaScript arrays are described in Section Array objects of the ECMAScript Language Specification.
napi_create_array_with_length#
napi_status napi_create_array_with_length(napi_env env,
size_t length,
napi_value* result)
[in] env: The environment that the API is invoked under.[in] length: The initial length of theArray.[out] result: Anapi_valuerepresenting a JavaScriptArray.
Returns napi_ok if the API succeeded.
This API returns a Node-API value corresponding to a JavaScript Array type. The Array's length property is set to the passed-in length parameter. However, the underlying buffer is not guaranteed to be pre-allocated by the VM when the array is created. That behavior is left to the underlying VM implementation. If the buffer must be a contiguous block of memory that can be directly read and/or written via C, consider using napi_create_external_arraybuffer.
JavaScript arrays are described in Section Array objects of the ECMAScript Language Specification.
napi_create_arraybuffer#
napi_status napi_create_arraybuffer(napi_env env,
size_t byte_length,
void** data,
napi_value* result)
[in] env: The environment that the API is invoked under.[in] length: The length in bytes of the array buffer to create.[out] data: Pointer to the underlying byte buffer of theArrayBuffer.datacan optionally be ignored by passingNULL.[out] result: Anapi_valuerepresenting a JavaScriptArrayBuffer.
Returns napi_ok if the API succeeded.
This API returns a Node-API value corresponding to a JavaScript ArrayBuffer. ArrayBuffers are used to represent fixed-length binary data buffers. They are normally used as a backing-buffer for TypedArray objects. The ArrayBuffer allocated will have an underlying byte buffer whose size is determined by the length parameter that's passed in. The underlying buffer is optionally returned back to the caller in case the caller wants to directly manipulate the buffer. This buffer can only be written to directly from native code. To write to this buffer from JavaScript, a typed array or DataView object would need to be created.
JavaScript ArrayBuffer objects are described in Section ArrayBuffer objects of the ECMAScript Language Specification.
napi_create_buffer#
napi_status napi_create_buffer(napi_env env,
size_t size,
void** data,
napi_value* result)
[in] env: The environment that the API is invoked under.[in] size: Size in bytes of the underlying buffer.[out] data: Raw pointer to the underlying buffer.datacan optionally be ignored by passingNULL.[out] result: Anapi_valuerepresenting anode::Buffer.
Returns napi_ok if the API succeeded.
This API allocates a node::Buffer object. While this is still a fully-supported data structure, in most cases using a TypedArray will suffice.
napi_create_buffer_copy#
napi_status napi_create_buffer_copy(napi_env env,
size_t length,
const void* data,
void** result_data,
napi_value* result)
[in] env: The environment that the API is invoked under.[in] size: Size in bytes of the input buffer (should be the same as the size of the new buffer).[in] data: Raw pointer to the underlying buffer to copy from.[out] result_data: Pointer to the newBuffer's underlying data buffer.result_datacan optionally be ignored by passingNULL.[out] result: Anapi_valuerepresenting anode::Buffer.
Returns napi_ok if the API succeeded.
This API allocates a node::Buffer object and initializes it with data copied from the passed-in buffer. While this is still a fully-supported data structure, in most cases using a TypedArray will suffice.
napi_create_date#
napi_status napi_create_date(napi_env env,
double time,
napi_value* result);
[in] env: The environment that the API is invoked under.[in] time: ECMAScript time value in milliseconds since 01 January, 1970 UTC.[out] result: Anapi_valuerepresenting a JavaScriptDate.
Returns napi_ok if the API succeeded.
This API does not observe leap seconds; they are ignored, as ECMAScript aligns with POSIX time specification.
This API allocates a JavaScript Date object.
JavaScript Date objects are described in Section Date objects of the ECMAScript Language Specification.
napi_create_external#
napi_status napi_create_external(napi_env env,
void* data,
napi_finalize finalize_cb,
void* finalize_hint,
napi_value* result)
[in] env: The environment that the API is invoked under.[in] data: Raw pointer to the external data.[in] finalize_cb: Optional callback to call when the external value is being collected.napi_finalizeprovides more details.[in] finalize_hint: Optional hint to pass to the finalize callback during collection.[out] result: Anapi_valuerepresenting an external value.
Returns napi_ok if the API succeeded.
This API allocates a JavaScript value with external data attached to it. This is used to pass external data through JavaScript code, so it can be retrieved later by native code using napi_get_value_external.
The API adds a napi_finalize callback which will be called when the JavaScript object just created has been garbage collected.
The created value is not an object, and therefore does not support additional properties. It is considered a distinct value type: calling napi_typeof() with an external value yields napi_external.
napi_create_external_arraybuffer#
napi_status
napi_create_external_arraybuffer(napi_env env,
void* external_data,
size_t byte_length,
napi_finalize finalize_cb,
void* finalize_hint,
napi_value* result)
[in] env: The environment that the API is invoked under.[in] external_data: Pointer to the underlying byte buffer of theArrayBuffer.[in] byte_length: The length in bytes of the underlying buffer.[in] finalize_cb: Optional callback to call when theArrayBufferis being collected.napi_finalizeprovides more details.[in] finalize_hint: Optional hint to pass to the finalize callback during collection.[out] result: Anapi_valuerepresenting a JavaScriptArrayBuffer.
Returns napi_ok if the API succeeded.
Some runtimes other than Node.js have dropped support for external buffers. On runtimes other than Node.js this method may return napi_no_external_buffers_allowed to indicate that external buffers are not supported. One such runtime is Electron as described in this issue electron/issues/35801.
In order to maintain broadest compatibility with all runtimes you may define NODE_API_NO_EXTERNAL_BUFFERS_ALLOWED in your addon before includes for the node-api headers. Doing so will hide the 2 functions that create external buffers. This will ensure a compilation error occurs if you accidentally use one of these methods.
This API returns a Node-API value corresponding to a JavaScript ArrayBuffer. The underlying byte buffer of the ArrayBuffer is externally allocated and managed. The caller must ensure that the byte buffer remains valid until the finalize callback is called.
The API adds a napi_finalize callback which will be called when the JavaScript object just created has been garbage collected.
JavaScript ArrayBuffers are described in Section ArrayBuffer objects of the ECMAScript Language Specification.
napi_create_external_buffer#
napi_status napi_create_external_buffer(napi_env env,
size_t length,
void* data,
napi_finalize finalize_cb,
void* finalize_hint,
napi_value* result)
[in] env: The environment that the API is invoked under.[in] length: Size in bytes of the input buffer (should be the same as the size of the new buffer).[in] data: Raw pointer to the underlying buffer to expose to JavaScript.[in] finalize_cb: Optional callback to call when theArrayBufferis being collected.napi_finalizeprovides more details.[in] finalize_hint: Optional hint to pass to the finalize callback during collection.[out] result: Anapi_valuerepresenting anode::Buffer.
Returns napi_ok if the API succeeded.
Some runtimes other than Node.js have dropped support for external buffers. On runtimes other than Node.js this method may return napi_no_external_buffers_allowed to indicate that external buffers are not supported. One such runtime is Electron as described in this issue electron/issues/35801.
In order to maintain broadest compatibility with all runtimes you may define NODE_API_NO_EXTERNAL_BUFFERS_ALLOWED in your addon before includes for the node-api headers. Doing so will hide the 2 functions that create external buffers. This will ensure a compilation error occurs if you accidentally use one of these methods.
This API allocates a node::Buffer object and initializes it with data backed by the passed in buffer. While this is still a fully-supported data structure, in most cases using a TypedArray will suffice.
The API adds a napi_finalize callback which will be called when the JavaScript object just created has been garbage collected.
For Node.js >=4 Buffers are Uint8Arrays.
napi_create_object#
napi_status napi_create_object(napi_env env, napi_value* result)
[in] env: The environment that the API is invoked under.[out] result: Anapi_valuerepresenting a JavaScriptObject.
Returns napi_ok if the API succeeded.
This API allocates a default JavaScript Object. It is the equivalent of doing new Object() in JavaScript.
The JavaScript Object type is described in Section object type of the ECMAScript Language Specification.
node_api_create_object_with_properties#
Stability: 1 - Experimental
napi_status node_api_create_object_with_properties(napi_env env,
napi_value prototype_or_null,
const napi_value* property_names,
const napi_value* property_values,
size_t property_count,
napi_value* result)
[in] env: The environment that the API is invoked under.[in] prototype_or_null: The prototype object for the new object. Can be anapi_valuerepresenting a JavaScript object to use as the prototype, anapi_valuerepresenting JavaScriptnull, or anullptrthat will be converted tonull.[in] property_names: Array ofnapi_valuerepresenting the property names.[in] property_values: Array ofnapi_valuerepresenting the property values.[in] property_count: Number of properties in the arrays.[out] result: Anapi_valuerepresenting a JavaScriptObject.
Returns napi_ok if the API succeeded.
This API creates a JavaScript Object with the specified prototype and properties. This is more efficient than calling napi_create_object followed by multiple napi_set_property calls, as it can create the object with all properties atomically, avoiding potential V8 map transitions.
The arrays property_names and property_values must have the same length specified by property_count. The properties are added to the object in the order they appear in the arrays.
napi_create_symbol#
napi_status napi_create_symbol(napi_env env,
napi_value description,
napi_value* result)
[in] env: The environment that the API is invoked under.[in] description: Optionalnapi_valuewhich refers to a JavaScriptstringto be set as the description for the symbol.[out] result: Anapi_valuerepresenting a JavaScriptsymbol.
Returns napi_ok if the API succeeded.
This API creates a JavaScript symbol value from a UTF8-encoded C string.
The JavaScript symbol type is described in Section symbol type of the ECMAScript Language Specification.
node_api_symbol_for#
napi_status node_api_symbol_for(napi_env env,
const char* utf8description,
size_t length,
napi_value* result)
[in] env: The environment that the API is invoked under.[in] utf8description: UTF-8 C string representing the text to be used as the description for the symbol.[in] length: The length of the description string in bytes, orNAPI_AUTO_LENGTHif it is null-terminated.[out] result: Anapi_valuerepresenting a JavaScriptsymbol.
Returns napi_ok if the API succeeded.
This API searches in the global registry for an existing symbol with the given description. If the symbol already exists it will be returned, otherwise a new symbol will be created in the registry.
The JavaScript symbol type is described in Section symbol type of the ECMAScript Language Specification.
napi_create_typedarray#
napi_status napi_create_typedarray(napi_env env,
napi_typedarray_type type,
size_t length,
napi_value arraybuffer,
size_t byte_offset,
napi_value* result)
[in] env: The environment that the API is invoked under.[in] type: Scalar datatype of the elements within theTypedArray.[in] length: Number of elements in theTypedArray.[in] arraybuffer:ArrayBufferunderlying the typed array.[in] byte_offset: The byte offset within theArrayBufferfrom which to start projecting theTypedArray.[out] result: Anapi_valuerepresenting a JavaScriptTypedArray.
Returns napi_ok if the API succeeded.
This API creates a JavaScript TypedArray object over an existing ArrayBuffer. TypedArray objects provide an array-like view over an underlying data buffer where each element has the same underlying binary scalar datatype.
It's required that (length * size_of_element) + byte_offset should be <= the size in bytes of the array passed in. If not, a RangeError exception is raised.
JavaScript TypedArray objects are described in Section TypedArray objects of the ECMAScript Language Specification.
node_api_create_buffer_from_arraybuffer#
napi_status NAPI_CDECL node_api_create_buffer_from_arraybuffer(napi_env env,
napi_value arraybuffer,
size_t byte_offset,
size_t byte_length,
napi_value* result)
[in] env: The environment that the API is invoked under.[in] arraybuffer: TheArrayBufferfrom which the buffer will be created.[in] byte_offset: The byte offset within theArrayBufferfrom which to start creating the buffer.[in] byte_length: The length in bytes of the buffer to be created from theArrayBuffer.[out] result: Anapi_valuerepresenting the created JavaScriptBufferobject.
Returns napi_ok if the API succeeded.
This API creates a JavaScript Buffer object from an existing ArrayBuffer. The Buffer object is a Node.js-specific class that provides a way to work with binary data directly in JavaScript.
The byte range [byte_offset, byte_offset + byte_length) must be within the bounds of the ArrayBuffer. If byte_offset + byte_length exceeds the size of the ArrayBuffer, a RangeError exception is raised.
napi_create_dataview#
napi_status napi_create_dataview(napi_env env,
size_t byte_length,
napi_value arraybuffer,
size_t byte_offset,
napi_value* result)
[in] env: The environment that the API is invoked under.[in] length: Number of elements in theDataView.[in] arraybuffer:ArrayBufferorSharedArrayBufferunderlying theDataView.[in] byte_offset: The byte offset within theArrayBufferfrom which to start projecting theDataView.[out] result: Anapi_valuerepresenting a JavaScriptDataView.
Returns napi_ok if the API succeeded.
This API creates a JavaScript DataView object over an existing ArrayBuffer or SharedArrayBuffer. DataView objects provide an array-like view over an underlying data buffer, but one which allows items of different size and type in the ArrayBuffer or SharedArrayBuffer.
It is required that byte_length + byte_offset is less than or equal to the size in bytes of the array passed in. If not, a RangeError exception is raised.
JavaScript DataView objects are described in Section DataView objects of the ECMAScript Language Specification.
Functions to convert from C types to Node-API#
napi_create_int32#
napi_status napi_create_int32(napi_env env, int32_t value, napi_value* result)
[in] env: The environment that the API is invoked under.[in] value: Integer value to be represented in JavaScript.[out] result: Anapi_valuerepresenting a JavaScriptnumber.
Returns napi_ok if the API succeeded.
This API is used to convert from the C int32_t type to the JavaScript number type.
The JavaScript number type is described in Section number type of the ECMAScript Language Specification.
napi_create_uint32#
napi_status napi_create_uint32(napi_env env, uint32_t value, napi_value* result)
[in] env: The environment that the API is invoked under.[in] value: Unsigned integer value to be represented in JavaScript.[out] result: Anapi_valuerepresenting a JavaScriptnumber.
Returns napi_ok if the API succeeded.
This API is used to convert from the C uint32_t type to the JavaScript number type.
The JavaScript number type is described in Section number type of the ECMAScript Language Specification.
napi_create_int64#
napi_status napi_create_int64(napi_env env, int64_t value, napi_value* result)
[in] env: The environment that the API is invoked under.[in] value: Integer value to be represented in JavaScript.[out] result: Anapi_valuerepresenting a JavaScriptnumber.
Returns napi_ok if the API succeeded.
This API is used to convert from the C int64_t type to the JavaScript number type.
The JavaScript number type is described in Section number type of the ECMAScript Language Specification. Note the complete range of int64_t cannot be represented with full precision in JavaScript. Integer values outside the range of Number.MIN_SAFE_INTEGER -(2**53 - 1) - Number.MAX_SAFE_INTEGER (2**53 - 1) will lose precision.
napi_create_double#
napi_status napi_create_double(napi_env env, double value, napi_value* result)
[in] env: The environment that the API is invoked under.[in] value: Double-precision value to be represented in JavaScript.[out] result: Anapi_valuerepresenting a JavaScriptnumber.
Returns napi_ok if the API succeeded.
This API is used to convert from the C double type to the JavaScript number type.
The JavaScript number type is described in Section number type of the ECMAScript Language Specification.
napi_create_bigint_int64#
napi_status napi_create_bigint_int64(napi_env env,
int64_t value,
napi_value* result);
[in] env: The environment that the API is invoked under.[in] value: Integer value to be represented in JavaScript.[out] result: Anapi_valuerepresenting a JavaScriptBigInt.
Returns napi_ok if the API succeeded.
This API converts the C int64_t type to the JavaScript BigInt type.
napi_create_bigint_uint64#
napi_status napi_create_bigint_uint64(napi_env env,
uint64_t value,
napi_value* result);
[in] env: The environment that the API is invoked under.[in] value: Unsigned integer value to be represented in JavaScript.[out] result: Anapi_valuerepresenting a JavaScriptBigInt.
Returns napi_ok if the API succeeded.
This API converts the C uint64_t type to the JavaScript BigInt type.
napi_create_bigint_words#
napi_status napi_create_bigint_words(napi_env env,
int sign_bit,
size_t word_count,
const uint64_t* words,
napi_value* result);
[in] env: The environment that the API is invoked under.[in] sign_bit: Determines if the resultingBigIntwill be positive or negative.[in] word_count: The length of thewordsarray.[in] words: An array ofuint64_tlittle-endian 64-bit words.[out] result: Anapi_valuerepresenting a JavaScriptBigInt.
Returns napi_ok if the API succeeded.
This API converts an array of unsigned 64-bit words into a single BigInt value.
The resulting BigInt is calculated as: (–1)sign_bit (words[0] × (264)0 + words[1] × (264)1 + …)
napi_create_string_latin1#
napi_status napi_create_string_latin1(napi_env env,
const char* str,
size_t length,
napi_value* result);
[in] env: The environment that the API is invoked under.[in] str: Character buffer representing an ISO-8859-1-encoded string.[in] length: The length of the string in bytes, orNAPI_AUTO_LENGTHif it is null-terminated.[out] result: Anapi_valuerepresenting a JavaScriptstring.
Returns napi_ok if the API succeeded.
This API creates a JavaScript string value from an ISO-8859-1-encoded C string. The native string is copied.
The JavaScript string type is described in Section string type of the ECMAScript Language Specification.
node_api_create_external_string_latin1#
napi_status
node_api_create_external_string_latin1(napi_env env,
char* str,
size_t length,
napi_finalize finalize_callback,
void* finalize_hint,
napi_value* result,
bool* copied);
[in] env: The environment that the API is invoked under.[in] str: Character buffer representing an ISO-8859-1-encoded string.[in] length: The length of the string in bytes, orNAPI_AUTO_LENGTHif it is null-terminated.[in] finalize_callback: The function to call when the string is being collected. The function will be called with the following parameters:[in] env: The environment in which the add-on is running. This value may be null if the string is being collected as part of the termination of the worker or the main Node.js instance.[in] data: This is the valuestras avoid*pointer.[in] finalize_hint: This is the valuefinalize_hintthat was given to the API.napi_finalizeprovides more details. This parameter is optional. Passing a null value means that the add-on doesn't need to be notified when the corresponding JavaScript string is collected.
[in] finalize_hint: Optional hint to pass to the finalize callback during collection.[out] result: Anapi_valuerepresenting a JavaScriptstring.[out] copied: Whether the string was copied. If it was, the finalizer will already have been invoked to destroystr.
Returns napi_ok if the API succeeded.
This API creates a JavaScript string value from an ISO-8859-1-encoded C string. The native string may not be copied and must thus exist for the entire life cycle of the JavaScript value.
The JavaScript string type is described in Section string type of the ECMAScript Language Specification.
napi_create_string_utf16#
napi_status napi_create_string_utf16(napi_env env,
const char16_t* str,
size_t length,
napi_value* result)
[in] env: The environment that the API is invoked under.[in] str: Character buffer representing a UTF16-LE-encoded string.[in] length: The length of the string in two-byte code units, orNAPI_AUTO_LENGTHif it is null-terminated.[out] result: Anapi_valuerepresenting a JavaScriptstring.
Returns napi_ok if the API succeeded.
This API creates a JavaScript string value from a UTF16-LE-encoded C string. The native string is copied.
The JavaScript string type is described in Section string type of the ECMAScript Language Specification.
node_api_create_external_string_utf16#
napi_status
node_api_create_external_string_utf16(napi_env env,
char16_t* str,
size_t length,
napi_finalize finalize_callback,
void* finalize_hint,
napi_value* result,
bool* copied);
[in] env: The environment that the API is invoked under.[in] str: Character buffer representing a UTF16-LE-encoded string.[in] length: The length of the string in two-byte code units, orNAPI_AUTO_LENGTHif it is null-terminated.[in] finalize_callback: The function to call when the string is being collected. The function will be called with the following parameters:[in] env: The environment in which the add-on is running. This value may be null if the string is being collected as part of the termination of the worker or the main Node.js instance.[in] data: This is the valuestras avoid*pointer.[in] finalize_hint: This is the valuefinalize_hintthat was given to the API.napi_finalizeprovides more details. This parameter is optional. Passing a null value means that the add-on doesn't need to be notified when the corresponding JavaScript string is collected.
[in] finalize_hint: Optional hint to pass to the finalize callback during collection.[out] result: Anapi_valuerepresenting a JavaScriptstring.[out] copied: Whether the string was copied. If it was, the finalizer will already have been invoked to destroystr.
Returns napi_ok if the API succeeded.
This API creates a JavaScript string value from a UTF16-LE-encoded C string. The native string may not be copied and must thus exist for the entire life cycle of the JavaScript value.
The JavaScript string type is described in Section string type of the ECMAScript Language Specification.
napi_create_string_utf8#
napi_status napi_create_string_utf8(napi_env env,
const char* str,
size_t length,
napi_value* result)
[in] env: The environment that the API is invoked under.[in] str: Character buffer representing a UTF8-encoded string.[in] length: The length of the string in bytes, orNAPI_AUTO_LENGTHif it is null-terminated.[out] result: Anapi_valuerepresenting a JavaScriptstring.
Returns napi_ok if the API succeeded.
This API creates a JavaScript string value from a UTF8-encoded C string. The native string is copied.
The JavaScript string type is described in Section string type of the ECMAScript Language Specification.
Functions to create optimized property keys#
Many JavaScript engines including V8 use internalized strings as keys to set and get property values. They typically use a hash table to create and lookup such strings. While it adds some cost per key creation, it improves the performance after that by enabling comparison of string pointers instead of the whole strings.
If a new JavaScript string is intended to be used as a property key, then for some JavaScript engines it will be more efficient to use the functions in this section. Otherwise, use the napi_create_string_utf8 or node_api_create_external_string_utf8 series functions as there may be additional overhead in creating/storing strings with the property key creation methods.
node_api_create_property_key_latin1#
napi_status NAPI_CDECL node_api_create_property_key_latin1(napi_env env,
const char* str,
size_t length,
napi_value* result);
[in] env: The environment that the API is invoked under.[in] str: Character buffer representing an ISO-8859-1-encoded string.[in] length: The length of the string in bytes, orNAPI_AUTO_LENGTHif it is null-terminated.[out] result: Anapi_valuerepresenting an optimized JavaScriptstringto be used as a property key for objects.
Returns napi_ok if the API succeeded.
This API creates an optimized JavaScript string value from an ISO-8859-1-encoded C string to be used as a property key for objects. The native string is copied. In contrast with napi_create_string_latin1, subsequent calls to this function with the same str pointer may benefit from a speedup in the creation of the requested napi_value, depending on the engine.
The JavaScript string type is described in Section string type of the ECMAScript Language Specification.
node_api_create_property_key_utf16#
napi_status NAPI_CDECL node_api_create_property_key_utf16(napi_env env,
const char16_t* str,
size_t length,
napi_value* result);
[in] env: The environment that the API is invoked under.[in] str: Character buffer representing a UTF16-LE-encoded string.[in] length: The length of the string in two-byte code units, orNAPI_AUTO_LENGTHif it is null-terminated.[out] result: Anapi_valuerepresenting an optimized JavaScriptstringto be used as a property key for objects.
Returns napi_ok if the API succeeded.
This API creates an optimized JavaScript string value from a UTF16-LE-encoded C string to be used as a property key for objects. The native string is copied.
The JavaScript string type is described in Section string type of the ECMAScript Language Specification.
node_api_create_property_key_utf8#
napi_status NAPI_CDECL node_api_create_property_key_utf8(napi_env env,
const char* str,
size_t length,
napi_value* result);
[in] env: The environment that the API is invoked under.[in] str: Character buffer representing a UTF8-encoded string.[in] length: The length of the string in two-byte code units, orNAPI_AUTO_LENGTHif it is null-terminated.[out] result: Anapi_valuerepresenting an optimized JavaScriptstringto be used as a property key for objects.
Returns napi_ok if the API succeeded.
This API creates an optimized JavaScript string value from a UTF8-encoded C string to be used as a property key for objects. The native string is copied.
The JavaScript string type is described in Section string type of the ECMAScript Language Specification.
Functions to convert from Node-API to C types#
napi_get_array_length#
napi_status napi_get_array_length(napi_env env,
napi_value value,
uint32_t* result)
[in] env: The environment that the API is invoked under.[in] value:napi_valuerepresenting the JavaScriptArraywhose length is being queried.[out] result:uint32representing length of the array.
Returns napi_ok if the API succeeded.
This API returns the length of an array.
Array length is described in Section Array instance length of the ECMAScript Language Specification.
napi_get_arraybuffer_info#
napi_status napi_get_arraybuffer_info(napi_env env,
napi_value arraybuffer,
void** data,
size_t* byte_length)
[in] env: The environment that the API is invoked under.[in] arraybuffer:napi_valuerepresenting theArrayBufferorSharedArrayBufferbeing queried.[out] data: The underlying data buffer of theArrayBufferorSharedArrayBufferis0, this may beNULLor any other pointer value.[out] byte_length: Length in bytes of the underlying data buffer.
Returns napi_ok if the API succeeded.
This API is used to retrieve the underlying data buffer of an ArrayBuffer or SharedArrayBuffer and its length.
WARNING: Use caution while using this API. The lifetime of the underlying data buffer is managed by the ArrayBuffer or SharedArrayBuffer even after it's returned. A possible safe way to use this API is in conjunction with napi_create_reference, which can be used to guarantee control over the lifetime of the ArrayBuffer or SharedArrayBuffer. It's also safe to use the returned data buffer within the same callback as long as there are no calls to other APIs that might trigger a GC.
napi_get_buffer_info#
napi_status napi_get_buffer_info(napi_env env,
napi_value value,
void** data,
size_t* length)
[in] env: The environment that the API is invoked under.[in] value:napi_valuerepresenting thenode::BufferorUint8Arraybeing queried.[out] data: The underlying data buffer of thenode::BufferorUint8Array. If length is0, this may beNULLor any other pointer value.[out] length: Length in bytes of the underlying data buffer.
Returns napi_ok if the API succeeded.
This method returns the identical data and byte_length as napi_get_typedarray_info. And napi_get_typedarray_info accepts a node::Buffer (a Uint8Array) as the value too.
This API is used to retrieve the underlying data buffer of a node::Buffer and its length.
Warning: Use caution while using this API since the underlying data buffer's lifetime is not guaranteed if it's managed by the VM.
napi_get_prototype#
napi_status napi_get_prototype(napi_env env,
napi_value object,
napi_value* result)
[in] env: The environment that the API is invoked under.[in] object:napi_valuerepresenting JavaScriptObjectwhose prototype to return. This returns the equivalent ofObject.getPrototypeOf(which is not the same as the function'sprototypeproperty).[out] result:napi_valuerepresenting prototype of the given object.
Returns napi_ok if the API succeeded.
napi_get_typedarray_info#
napi_status napi_get_typedarray_info(napi_env env,
napi_value typedarray,
napi_typedarray_type* type,
size_t* length,
void** data,
napi_value* arraybuffer,
size_t* byte_offset)
[in] env: The environment that the API is invoked under.[in] typedarray:napi_valuerepresenting theTypedArraywhose properties to query.[out] type: Scalar datatype of the elements within theTypedArray.[out] length: The number of elements in theTypedArray.[out] data: The data buffer underlying theTypedArrayadjusted by thebyte_offsetvalue so that it points to the first element in theTypedArray. If the length of the array is0, this may beNULLor any other pointer value.[out] arraybuffer: TheArrayBufferunderlying theTypedArray.[out] byte_offset: The byte offset within the underlying native array at which the first element of the arrays is located. The value for the data parameter has already been adjusted so that data points to the first element in the array. Therefore, the first byte of the native array would be atdata - byte_offset.
Returns napi_ok if the API succeeded.
This API returns various properties of a typed array.
Any of the out parameters may be NULL if that property is unneeded.
Warning: Use caution while using this API since the underlying data buffer is managed by the VM.
napi_get_dataview_info#
napi_status napi_get_dataview_info(napi_env env,
napi_value dataview,
size_t* byte_length,
void** data,
napi_value* arraybuffer,
size_t* byte_offset)
[in] env: The environment that the API is invoked under.[in] dataview:napi_valuerepresenting theDataViewwhose properties to query.[out] byte_length: Number of bytes in theDataView.[out] data: The data buffer underlying theDataView. If byte_length is0, this may beNULLor any other pointer value.[out] arraybuffer:ArrayBufferunderlying theDataView.[out] byte_offset: The byte offset within the data buffer from which to start projecting theDataView.
Returns napi_ok if the API succeeded.
Any of the out parameters may be NULL if that property is unneeded.
This API returns various properties of a DataView.
napi_get_date_value#
napi_status napi_get_date_value(napi_env env,
napi_value value,
double* result)
[in] env: The environment that the API is invoked under.[in] value:napi_valuerepresenting a JavaScriptDate.[out] result: Time value as adoublerepresented as milliseconds since midnight at the beginning of 01 January, 1970 UTC.
This API does not observe leap seconds; they are ignored, as ECMAScript aligns with POSIX time specification.
Returns napi_ok if the API succeeded. If a non-date napi_value is passed in it returns napi_date_expected.
This API returns the C double primitive of time value for the given JavaScript Date.
napi_get_value_bool#
napi_status napi_get_value_bool(napi_env env, napi_value value, bool* result)
[in] env: The environment that the API is invoked under.[in] value:napi_valuerepresenting JavaScriptBoolean.[out] result: C boolean primitive equivalent of the given JavaScriptBoolean.
Returns napi_ok if the API succeeded. If a non-boolean napi_value is passed in it returns napi_boolean_expected.
This API returns the C boolean primitive equivalent of the given JavaScript Boolean.
napi_get_value_double#
napi_status napi_get_value_double(napi_env env,
napi_value value,
double* result)
[in] env: The environment that the API is invoked under.[in] value:napi_valuerepresenting JavaScriptnumber.[out] result: C double primitive equivalent of the given JavaScriptnumber.
Returns napi_ok if the API succeeded. If a non-number napi_value is passed in it returns napi_number_expected.
This API returns the C double primitive equivalent of the given JavaScript number.
napi_get_value_bigint_int64#
napi_status napi_get_value_bigint_int64(napi_env env,
napi_value value,
int64_t* result,
bool* lossless);
[in] env: The environment that the API is invoked under[in] value:napi_valuerepresenting JavaScriptBigInt.[out] result: Cint64_tprimitive equivalent of the given JavaScriptBigInt.[out] lossless: Indicates whether theBigIntvalue was converted losslessly.
Returns napi_ok if the API succeeded. If a non-BigInt is passed in it returns napi_bigint_expected.
This API returns the C int64_t primitive equivalent of the given JavaScript BigInt. If needed it will truncate the value, setting lossless to false.
napi_get_value_bigint_uint64#
napi_status napi_get_value_bigint_uint64(napi_env env,
napi_value value,
uint64_t* result,
bool* lossless);
[in] env: The environment that the API is invoked under.[in] value:napi_valuerepresenting JavaScriptBigInt.[out] result: Cuint64_tprimitive equivalent of the given JavaScriptBigInt.[out] lossless: Indicates whether theBigIntvalue was converted losslessly.
Returns napi_ok if the API succeeded. If a non-BigInt is passed in it returns napi_bigint_expected.
This API returns the C uint64_t primitive equivalent of the given JavaScript BigInt. If needed it will truncate the value, setting lossless to false.
napi_get_value_bigint_words#
napi_status napi_get_value_bigint_words(napi_env env,
napi_value value,
int* sign_bit,
size_t* word_count,
uint64_t* words);
[in] env: The environment that the API is invoked under.[in] value:napi_valuerepresenting JavaScriptBigInt.[out] sign_bit: Integer representing if the JavaScriptBigIntis positive or negative.[in/out] word_count: Must be initialized to the length of thewordsarray. Upon return, it will be set to the actual number of words that would be needed to store thisBigInt.[out] words: Pointer to a pre-allocated 64-bit word array.
Returns napi_ok if the API succeeded.
This API converts a single BigInt value into a sign bit, 64-bit little-endian array, and the number of elements in the array. sign_bit and words may be both set to NULL, in order to get only word_count.
napi_get_value_external#
napi_status napi_get_value_external(napi_env env,
napi_value value,
void** result)
[in] env: The environment that the API is invoked under.[in] value:napi_valuerepresenting JavaScript external value.[out] result: Pointer to the data wrapped by the JavaScript external value.
Returns napi_ok if the API succeeded. If a non-external napi_value is passed in it returns napi_invalid_arg.
This API retrieves the external data pointer that was previously passed to napi_create_external().
napi_get_value_int32#
napi_status napi_get_value_int32(napi_env env,
napi_value value,
int32_t* result)
[in] env: The environment that the API is invoked under.[in] value:napi_valuerepresenting JavaScriptnumber.[out] result: Cint32primitive equivalent of the given JavaScriptnumber.
Returns napi_ok if the API succeeded. If a non-number napi_value is passed in napi_number_expected.
This API returns the C int32 primitive equivalent of the given JavaScript number.
If the number exceeds the range of the 32 bit integer, then the result is truncated to the equivalent of the bottom 32 bits. This can result in a large positive number becoming a negative number if the value is > 231 - 1.
Non-finite number values (NaN, +Infinity, or -Infinity) set the result to zero.
napi_get_value_int64#
napi_status napi_get_value_int64(napi_env env,
napi_value value,
int64_t* result)
[in] env: The environment that the API is invoked under.[in] value:napi_valuerepresenting JavaScriptnumber.[out] result: Cint64primitive equivalent of the given JavaScriptnumber.
Returns napi_ok if the API succeeded. If a non-number napi_value is passed in it returns napi_number_expected.
This API returns the C int64 primitive equivalent of the given JavaScript number.
number values outside the range of Number.MIN_SAFE_INTEGER -(2**53 - 1) - Number.MAX_SAFE_INTEGER (2**53 - 1) will lose precision.
Non-finite number values (NaN, +Infinity, or -Infinity) set the result to zero.
napi_get_value_string_latin1#
napi_status napi_get_value_string_latin1(napi_env env,
napi_value value,
char* buf,
size_t bufsize,
size_t* result)
[in] env: The environment that the API is invoked under.[in] value:napi_valuerepresenting JavaScript string.[in] buf: Buffer to write the ISO-8859-1-encoded string into. IfNULLis passed in, the length of the string in bytes and excluding the null terminator is returned inresult.[in] bufsize: Size of the destination buffer. When this value is insufficient, the returned string is truncated and null-terminated. If this value is zero, then the string is not returned and no changes are done to the buffer.[out] result: Number of bytes copied into the buffer, excluding the null terminator.
Returns napi_ok if the API succeeded. If a non-string napi_value is passed in it returns napi_string_expected.
This API returns the ISO-8859-1-encoded string corresponding the value passed in.
napi_get_value_string_utf8#
napi_status napi_get_value_string_utf8(napi_env env,
napi_value value,
char* buf,
size_t bufsize,
size_t* result)
[in] env: The environment that the API is invoked under.[in] value:napi_valuerepresenting JavaScript string.[in] buf: Buffer to write the UTF8-encoded string into. IfNULLis passed in, the length of the string in bytes and excluding the null terminator is returned inresult.[in] bufsize: Size of the destination buffer. When this value is insufficient, the returned string is truncated and null-terminated. If this value is zero, then the string is not returned and no changes are done to the buffer.[out] result: Number of bytes copied into the buffer, excluding the null terminator.
Returns napi_ok if the API succeeded. If a non-string napi_value is passed in it returns napi_string_expected.
This API returns the UTF8-encoded string corresponding the value passed in.
napi_get_value_string_utf16#
napi_status napi_get_value_string_utf16(napi_env env,
napi_value value,
char16_t* buf,
size_t bufsize,
size_t* result)
[in] env: The environment that the API is invoked under.[in] value:napi_valuerepresenting JavaScript string.[in] buf: Buffer to write the UTF16-LE-encoded string into. IfNULLis passed in, the length of the string in 2-byte code units and excluding the null terminator is returned.[in] bufsize: Size of the destination buffer. When this value is insufficient, the returned string is truncated and null-terminated. If this value is zero, then the string is not returned and no changes are done to the buffer.[out] result: Number of 2-byte code units copied into the buffer, excluding the null terminator.
Returns napi_ok if the API succeeded. If a non-string napi_value is passed in it returns napi_string_expected.
This API returns the UTF16-encoded string corresponding the value passed in.
napi_get_value_uint32#
napi_status napi_get_value_uint32(napi_env env,
napi_value value,
uint32_t* result)
[in] env: The environment that the API is invoked under.[in] value:napi_valuerepresenting JavaScriptnumber.[out] result: C primitive equivalent of the givennapi_valueas auint32_t.
Returns napi_ok if the API succeeded. If a non-number napi_value is passed in it returns napi_number_expected.
This API returns the C primitive equivalent of the given napi_value as a uint32_t.
Functions to get global instances#
napi_get_boolean#
napi_status napi_get_boolean(napi_env env, bool value, napi_value* result)
[in] env: The environment that the API is invoked under.[in] value: The value of the boolean to retrieve.[out] result:napi_valuerepresenting JavaScriptBooleansingleton to retrieve.
Returns napi_ok if the API succeeded.
This API is used to return the JavaScript singleton object that is used to represent the given boolean value.
napi_get_global#
napi_status napi_get_global(napi_env env, napi_value* result)
[in] env: The environment that the API is invoked under.[out] result:napi_valuerepresenting JavaScriptglobalobject.
Returns napi_ok if the API succeeded.
This API returns the global object.
napi_get_null#
napi_status napi_get_null(napi_env env, napi_value* result)
[in] env: The environment that the API is invoked under.[out] result:napi_valuerepresenting JavaScriptnullobject.
Returns napi_ok if the API succeeded.
This API returns the null object.
napi_get_undefined#
napi_status napi_get_undefined(napi_env env, napi_value* result)
[in] env: The environment that the API is invoked under.[out] result:napi_valuerepresenting JavaScript Undefined value.
Returns napi_ok if the API succeeded.
This API returns the Undefined object.
Working with JavaScript values and abstract operations#
Node-API exposes a set of APIs to perform some abstract operations on JavaScript values.
These APIs support doing one of the following:
- Coerce JavaScript values to specific JavaScript types (such as
numberorstring). - Check the type of a JavaScript value.
- Check for equality between two JavaScript values.
napi_coerce_to_bool#
napi_status napi_coerce_to_bool(napi_env env,
napi_value value,
napi_value* result)
[in] env: The environment that the API is invoked under.[in] value: The JavaScript value to coerce.[out] result:napi_valuerepresenting the coerced JavaScriptBoolean.
Returns napi_ok if the API succeeded.
This API implements the abstract operation ToBoolean() as defined in Section ToBoolean of the ECMAScript Language Specification.
napi_coerce_to_number#
napi_status napi_coerce_to_number(napi_env env,
napi_value value,
napi_value* result)
[in] env: The environment that the API is invoked under.[in] value: The JavaScript value to coerce.[out] result:napi_valuerepresenting the coerced JavaScriptnumber.
Returns napi_ok if the API succeeded.
This API implements the abstract operation ToNumber() as defined in Section ToNumber of the ECMAScript Language Specification. This function potentially runs JS code if the passed-in value is an object.
napi_coerce_to_object#
napi_status napi_coerce_to_object(napi_env env,
napi_value value,
napi_value* result)
[in] env: The environment that the API is invoked under.[in] value: The JavaScript value to coerce.[out] result:napi_valuerepresenting the coerced JavaScriptObject.
Returns napi_ok if the API succeeded.
This API implements the abstract operation ToObject() as defined in Section ToObject of the ECMAScript Language Specification.
napi_coerce_to_string#
napi_status napi_coerce_to_string(napi_env env,
napi_value value,
napi_value* result)
[in] env: The environment that the API is invoked under.[in] value: The JavaScript value to coerce.[out] result:napi_valuerepresenting the coerced JavaScriptstring.
Returns napi_ok if the API succeeded.
This API implements the abstract operation ToString() as defined in Section ToString of the ECMAScript Language Specification. This function potentially runs JS code if the passed-in value is an object.
napi_typeof#
napi_status napi_typeof(napi_env env, napi_value value, napi_valuetype* result)
[in] env: The environment that the API is invoked under.[in] value: The JavaScript value whose type to query.[out] result: The type of the JavaScript value.
Returns napi_ok if the API succeeded.
napi_invalid_argif the type ofvalueis not a known ECMAScript type andvalueis not an External value.
This API represents behavior similar to invoking the typeof Operator on the object as defined in Section typeof operator of the ECMAScript Language Specification. However, there are some differences:
- It has support for detecting an External value.
- It detects
nullas a separate type, while ECMAScripttypeofwould detectobject.
If value has a type that is invalid, an error is returned.
napi_instanceof#
napi_status napi_instanceof(napi_env env,
napi_value object,
napi_value constructor,
bool* result)
[in] env: The environment that the API is invoked under.[in] object: The JavaScript value to check.[in] constructor: The JavaScript function object of the constructor function to check against.[out] result: Boolean that is set to true ifobject instanceof constructoris true.
Returns napi_ok if the API succeeded.
This API represents invoking the instanceof Operator on the object as defined in Section instanceof operator of the ECMAScript Language Specification.
napi_is_array#
napi_status napi_is_array(napi_env env, napi_value value, bool* result)
[in] env: The environment that the API is invoked under.[in] value: The JavaScript value to check.[out] result: Whether the given object is an array.
Returns napi_ok if the API succeeded.
This API represents invoking the IsArray operation on the object as defined in Section IsArray of the ECMAScript Language Specification.
napi_is_arraybuffer#
napi_status napi_is_arraybuffer(napi_env env, napi_value value, bool* result)
[in] env: The environment that the API is invoked under.[in] value: The JavaScript value to check.[out] result: Whether the given object is anArrayBuffer.
Returns napi_ok if the API succeeded.
This API checks if the Object passed in is an array buffer.
napi_is_buffer#
napi_status napi_is_buffer(napi_env env, napi_value value, bool* result)
[in] env: The environment that the API is invoked under.[in] value: The JavaScript value to check.[out] result: Whether the givennapi_valuerepresents anode::BufferorUint8Arrayobject.
Returns napi_ok if the API succeeded.
This API checks if the Object passed in is a buffer or Uint8Array. napi_is_typedarray should be preferred if the caller needs to check if the value is a Uint8Array.
napi_is_date#
napi_status napi_is_date(napi_env env, napi_value value, bool* result)
[in] env: The environment that the API is invoked under.[in] value: The JavaScript value to check.[out] result: Whether the givennapi_valuerepresents a JavaScriptDateobject.
Returns napi_ok if the API succeeded.
This API checks if the Object passed in is a date.
napi_is_error#
napi_status napi_is_error(napi_env env, napi_value value, bool* result)
[in] env: The environment that the API is invoked under.[in] value: The JavaScript value to check.[out] result: Whether the givennapi_valuerepresents anErrorobject.
Returns napi_ok if the API succeeded.
This API checks if the Object passed in is an Error.
napi_is_typedarray#
napi_status napi_is_typedarray(napi_env env, napi_value value, bool* result)
[in] env: The environment that the API is invoked under.[in] value: The JavaScript value to check.[out] result: Whether the givennapi_valuerepresents aTypedArray.
Returns napi_ok if the API succeeded.
This API checks if the Object passed in is a typed array.
napi_is_dataview#
napi_status napi_is_dataview(napi_env env, napi_value value, bool* result)
[in] env: The environment that the API is invoked under.[in] value: The JavaScript value to check.[out] result: Whether the givennapi_valuerepresents aDataView.
Returns napi_ok if the API succeeded.
This API checks if the Object passed in is a DataView.
napi_strict_equals#
napi_status napi_strict_equals(napi_env env,
napi_value lhs,
napi_value rhs,
bool* result)
[in] env: The environment that the API is invoked under.[in] lhs: The JavaScript value to check.[in] rhs: The JavaScript value to check against.[out] result: Whether the twonapi_valueobjects are equal.
Returns napi_ok if the API succeeded.
This API represents the invocation of the Strict Equality algorithm as defined in Section IsStrctEqual of the ECMAScript Language Specification.
napi_detach_arraybuffer#
napi_status napi_detach_arraybuffer(napi_env env,
napi_value arraybuffer)
[in] env: The environment that the API is invoked under.[in] arraybuffer: The JavaScriptArrayBufferto be detached.
Returns napi_ok if the API succeeded. If a non-detachable ArrayBuffer is passed in it returns napi_detachable_arraybuffer_expected.
Generally, an ArrayBuffer is non-detachable if it has been detached before. The engine may impose additional conditions on whether an ArrayBuffer is detachable. For example, V8 requires that the ArrayBuffer be external, that is, created with napi_create_external_arraybuffer.
This API represents the invocation of the ArrayBuffer detach operation as defined in Section detachArrayBuffer of the ECMAScript Language Specification.
napi_is_detached_arraybuffer#
napi_status napi_is_detached_arraybuffer(napi_env env,
napi_value arraybuffer,
bool* result)
[in] env: The environment that the API is invoked under.[in] arraybuffer: The JavaScriptArrayBufferto be checked.[out] result: Whether thearraybufferis detached.
Returns napi_ok if the API succeeded.
The ArrayBuffer is considered detached if its internal data is null.
This API represents the invocation of the ArrayBuffer IsDetachedBuffer operation as defined in Section isDetachedBuffer of the ECMAScript Language Specification.
node_api_is_sharedarraybuffer#
Stability: 1 - Experimental
napi_status node_api_is_sharedarraybuffer(napi_env env, napi_value value, bool* result)
[in] env: The environment that the API is invoked under.[in] value: The JavaScript value to check.[out] result: Whether the givennapi_valuerepresents aSharedArrayBuffer.
Returns napi_ok if the API succeeded.
This API checks if the Object passed in is a SharedArrayBuffer.
node_api_create_sharedarraybuffer#
Stability: 1 - Experimental
napi_status node_api_create_sharedarraybuffer(napi_env env,
size_t byte_length,
void** data,
napi_value* result)
[in] env: The environment that the API is invoked under.[in] byte_length: The length in bytes of the shared array buffer to create.[out] data: Pointer to the underlying byte buffer of theSharedArrayBuffer.datacan optionally be ignored by passingNULL.[out] result: Anapi_valuerepresenting a JavaScriptSharedArrayBuffer.
Returns napi_ok if the API succeeded.
This API returns a Node-API value corresponding to a JavaScript SharedArrayBuffer. SharedArrayBuffers are used to represent fixed-length binary data buffers that can be shared across multiple workers.
The SharedArrayBuffer allocated will have an underlying byte buffer whose size is determined by the byte_length parameter that's passed in. The underlying buffer is optionally returned back to the caller in case the caller wants to directly manipulate the buffer. This buffer can only be written to directly from native code. To write to this buffer from JavaScript, a typed array or DataView object would need to be created.
JavaScript SharedArrayBuffer objects are described in Section SharedArrayBuffer objects of the ECMAScript Language Specification.
Working with JavaScript properties#
Node-API exposes a set of APIs to get and set properties on JavaScript objects.
Properties in JavaScript are represented as a tuple of a key and a value. Fundamentally, all property keys in Node-API can be represented in one of the following forms:
- Named: a simple UTF8-encoded string
- Integer-Indexed: an index value represented by
uint32_t - JavaScript value: these are represented in Node-API by
napi_value. This can be anapi_valuerepresenting astring,number, orsymbol.
Node-API values are represented by the type napi_value. Any Node-API call that requires a JavaScript value takes in a napi_value. However, it's the caller's responsibility to make sure that the napi_value in question is of the JavaScript type expected by the API.
The APIs documented in this section provide a simple interface to get and set properties on arbitrary JavaScript objects represented by napi_value.
For instance, consider the following JavaScript code snippet:
const obj = {};
obj.myProp = 123;
The equivalent can be done using Node-API values with the following snippet:
napi_status status = napi_generic_failure;
// const obj = {}
napi_value obj, value;
status = napi_create_object(env, &obj);
if (status != napi_ok) return status;
// Create a napi_value for 123
status = napi_create_int32(env, 123, &value);
if (status != napi_ok) return status;
// obj.myProp = 123
status = napi_set_named_property(env, obj, "myProp", value);
if (status != napi_ok) return status;
Indexed properties can be set in a similar manner. Consider the following JavaScript snippet:
const arr = [];
arr[123] = 'hello';
The equivalent can be done using Node-API values with the following snippet:
napi_status status = napi_generic_failure;
// const arr = [];
napi_value arr, value;
status = napi_create_array(env, &arr);
if (status != napi_ok) return status;
// Create a napi_value for 'hello'
status = napi_create_string_utf8(env, "hello", NAPI_AUTO_LENGTH, &value);
if (status != napi_ok) return status;
// arr[123] = 'hello';
status = napi_set_element(env, arr, 123, value);
if (status != napi_ok) return status;
Properties can be retrieved using the APIs described in this section. Consider the following JavaScript snippet:
const arr = [];
const value = arr[123];
The following is the approximate equivalent of the Node-API counterpart:
napi_status status = napi_generic_failure;
// const arr = []
napi_value arr, value;
status = napi_create_array(env, &arr);
if (status != napi_ok) return status;
// const value = arr[123]
status = napi_get_element(env, arr, 123, &value);
if (status != napi_ok) return status;
Finally, multiple properties can also be defined on an object for performance reasons. Consider the following JavaScript:
const obj = {};
Object.defineProperties(obj, {
'foo': { value: 123, writable: true, configurable: true, enumerable: true },
'bar': { value: 456, writable: true, configurable: true, enumerable: true },
});
The following is the approximate equivalent of the Node-API counterpart:
napi_status status = napi_status_generic_failure;
// const obj = {};
napi_value obj;
status = napi_create_object(env, &obj);
if (status != napi_ok) return status;
// Create napi_values for 123 and 456
napi_value fooValue, barValue;
status = napi_create_int32(env, 123, &fooValue);
if (status != napi_ok) return status;
status = napi_create_int32(env, 456, &barValue);
if (status != napi_ok) return status;
// Set the properties
napi_property_descriptor descriptors[] = {
{ "foo", NULL, NULL, NULL, NULL, fooValue, napi_writable | napi_configurable, NULL },
{ "bar", NULL, NULL, NULL, NULL, barValue, napi_writable | napi_configurable, NULL }
}
status = napi_define_properties(env,
obj,
sizeof(descriptors) / sizeof(descriptors[0]),
descriptors);
if (status != napi_ok) return status;
Structures#
napi_property_attributes#
typedef enum {
napi_default = 0,
napi_writable = 1 << 0,
napi_enumerable = 1 << 1,
napi_configurable = 1 << 2,
// Used with napi_define_class to distinguish static properties
// from instance properties. Ignored by napi_define_properties.
napi_static = 1 << 10,
// Default for class methods.
napi_default_method = napi_writable | napi_configurable,
// Default for object properties, like in JS obj[prop].
napi_default_jsproperty = napi_writable |
napi_enumerable |
napi_configurable,
} napi_property_attributes;
napi_property_attributes are bit flags used to control the behavior of properties set on a JavaScript object. Other than napi_static they correspond to the attributes listed in Section property attributes of the ECMAScript Language Specification. They can be one or more of the following bit flags:
napi_default: No explicit attributes are set on the property. By default, a property is read only, not enumerable and not configurable.napi_writable: The property is writable.napi_enumerable: The property is enumerable.napi_configurable: The property is configurable as defined in Section property attributes of the ECMAScript Language Specification.napi_static: The property will be defined as a static property on a class as opposed to an instance property, which is the default. This is used only bynapi_define_class. It is ignored bynapi_define_properties.napi_default_method: Like a method in a JS class, the property is configurable and writeable, but not enumerable.napi_default_jsproperty: Like a property set via assignment in JavaScript, the property is writable, enumerable, and configurable.
napi_property_descriptor#
typedef struct {
// One of utf8name or name should be NULL.
const char* utf8name;
napi_value name;
napi_callback method;
napi_callback getter;
napi_callback setter;
napi_value value;
napi_property_attributes attributes;
void* data;
} napi_property_descriptor;
utf8name: Optional string describing the key for the property, encoded as UTF8. One ofutf8nameornamemust be provided for the property.name: Optionalnapi_valuethat points to a JavaScript string or symbol to be used as the key for the property. One ofutf8nameornamemust be provided for the property.value: The value that's retrieved by a get access of the property if the property is a data property. If this is passed in, setgetter,setter,methodanddatatoNULL(since these members won't be used).getter: A function to call when a get access of the property is performed. If this is passed in, setvalueandmethodtoNULL(since these members won't be used). The given function is called implicitly by the runtime when the property is accessed from JavaScript code (or if a get on the property is performed using a Node-API call).napi_callbackprovides more details.setter: A function to call when a set access of the property is performed. If this is passed in, setvalueandmethodtoNULL(since these members won't be used). The given function is called implicitly by the runtime when the property is set from JavaScript code (or if a set on the property is performed using a Node-API call).napi_callbackprovides more details.method: Set this to make the property descriptor object'svalueproperty to be a JavaScript function represented bymethod. If this is passed in, setvalue,getterandsettertoNULL(since these members won't be used).napi_callbackprovides more details.attributes: The attributes associated with the particular property. Seenapi_property_attributes.data: The callback data passed intomethod,getterandsetterif this function is invoked.
Functions#
napi_get_property_names#
napi_status napi_get_property_names(napi_env env,
napi_value object,
napi_value* result);
[in] env: The environment that the Node-API call is invoked under.[in] object: The object from which to retrieve the properties.[out] result: Anapi_valuerepresenting an array of JavaScript values that represent the property names of the object. The API can be used to iterate overresultusingnapi_get_array_lengthandnapi_get_element.
Returns napi_ok if the API succeeded.
This API returns the names of the enumerable properties of object as an array of strings. The properties of object whose key is a symbol will not be included.
napi_get_all_property_names#
napi_get_all_property_names(napi_env env,
napi_value object,
napi_key_collection_mode key_mode,
napi_key_filter key_filter,
napi_key_conversion key_conversion,
napi_value* result);
[in] env: The environment that the Node-API call is invoked under.[in] object: The object from which to retrieve the properties.[in] key_mode: Whether to retrieve prototype properties as well.[in] key_filter: Which properties to retrieve (enumerable/readable/writable).[in] key_conversion: Whether to convert numbered property keys to strings.[out] result: Anapi_valuerepresenting an array of JavaScript values that represent the property names of the object.napi_get_array_lengthandnapi_get_elementcan be used to iterate overresult.
Returns napi_ok if the API succeeded.
This API returns an array containing the names of the available properties of this object.
napi_set_property#
napi_status napi_set_property(napi_env env,
napi_value object,
napi_value key,
napi_value value);
[in] env: The environment that the Node-API call is invoked under.[in] object: The object on which to set the property.[in] key: The name of the property to set.[in] value: The property value.
Returns napi_ok if the API succeeded.
This API set a property on the Object passed in.
napi_get_property#
napi_status napi_get_property(napi_env env,
napi_value object,
napi_value key,
napi_value* result);
[in] env: The environment that the Node-API call is invoked under.[in] object: The object from which to retrieve the property.[in] key: The name of the property to retrieve.[out] result: The value of the property.
Returns napi_ok if the API succeeded.
This API gets the requested property from the Object passed in.
napi_has_property#
napi_status napi_has_property(napi_env env,
napi_value object,
napi_value key,
bool* result);
[in] env: The environment that the Node-API call is invoked under.[in] object: The object to query.[in] key: The name of the property whose existence to check.[out] result: Whether the property exists on the object or not.
Returns napi_ok if the API succeeded.
This API checks if the Object passed in has the named property.
napi_delete_property#
napi_status napi_delete_property(napi_env env,
napi_value object,
napi_value key,
bool* result);
[in] env: The environment that the Node-API call is invoked under.[in] object: The object to query.[in] key: The name of the property to delete.[out] result: Whether the property deletion succeeded or not.resultcan optionally be ignored by passingNULL.
Returns napi_ok if the API succeeded.
This API attempts to delete the key own property from object.
napi_has_own_property#
napi_status napi_has_own_property(napi_env env,
napi_value object,
napi_value key,
bool* result);
[in] env: The environment that the Node-API call is invoked under.[in] object: The object to query.[in] key: The name of the own property whose existence to check.[out] result: Whether the own property exists on the object or not.
Returns napi_ok if the API succeeded.
This API checks if the Object passed in has the named own property. key must be a string or a symbol, or an error will be thrown. Node-API will not perform any conversion between data types.
napi_set_named_property#
napi_status napi_set_named_property(napi_env env,
napi_value object,
const char* utf8Name,
napi_value value);
[in] env: The environment that the Node-API call is invoked under.[in] object: The object on which to set the property.[in] utf8Name: The name of the property to set.[in] value: The property value.
Returns napi_ok if the API succeeded.
This method is equivalent to calling napi_set_property with a napi_value created from the string passed in as utf8Name.
napi_get_named_property#
napi_status napi_get_named_property(napi_env env,
napi_value object,
const char* utf8Name,
napi_value* result);
[in] env: The environment that the Node-API call is invoked under.[in] object: The object from which to retrieve the property.[in] utf8Name: The name of the property to get.[out] result: The value of the property.
Returns napi_ok if the API succeeded.
This method is equivalent to calling napi_get_property with a napi_value created from the string passed in as utf8Name.
napi_has_named_property#
napi_status napi_has_named_property(napi_env env,
napi_value object,
const char* utf8Name,
bool* result);
[in] env: The environment that the Node-API call is invoked under.[in] object: The object to query.[in] utf8Name: The name of the property whose existence to check.[out] result: Whether the property exists on the object or not.
Returns napi_ok if the API succeeded.
This method is equivalent to calling napi_has_property with a napi_value created from the string passed in as utf8Name.
napi_set_element#
napi_status napi_set_element(napi_env env,
napi_value object,
uint32_t index,
napi_value value);
[in] env: The environment that the Node-API call is invoked under.[in] object: The object from which to set the properties.[in] index: The index of the property to set.[in] value: The property value.
Returns napi_ok if the API succeeded.
This API sets an element on the Object passed in.
napi_get_element#
napi_status napi_get_element(napi_env env,
napi_value object,
uint32_t index,
napi_value* result);
[in] env: The environment that the Node-API call is invoked under.[in] object: The object from which to retrieve the property.[in] index: The index of the property to get.[out] result: The value of the property.
Returns napi_ok if the API succeeded.
This API gets the element at the requested index.
napi_has_element#
napi_status napi_has_element(napi_env env,
napi_value object,
uint32_t index,
bool* result);
[in] env: The environment that the Node-API call is invoked under.[in] object: The object to query.[in] index: The index of the property whose existence to check.[out] result: Whether the property exists on the object or not.
Returns napi_ok if the API succeeded.
This API returns if the Object passed in has an element at the requested index.
napi_delete_element#
napi_status napi_delete_element(napi_env env,
napi_value object,
uint32_t index,
bool* result);
[in] env: The environment that the Node-API call is invoked under.[in] object: The object to query.[in] index: The index of the property to delete.[out] result: Whether the element deletion succeeded or not.resultcan optionally be ignored by passingNULL.
Returns napi_ok if the API succeeded.
This API attempts to delete the specified index from object.
napi_define_properties#
napi_status napi_define_properties(napi_env env,
napi_value object,
size_t property_count,
const napi_property_descriptor* properties);
[in] env: The environment that the Node-API call is invoked under.[in] object: The object from which to retrieve the properties.[in] property_count: The number of elements in thepropertiesarray.[in] properties: The array of property descriptors.
Returns napi_ok if the API succeeded.
This method allows the efficient definition of multiple properties on a given object. The properties are defined using property descriptors (see napi_property_descriptor). Given an array of such property descriptors, this API will set the properties on the object one at a time, as defined by DefineOwnProperty() (described in Section DefineOwnProperty of the ECMA-262 specification).
napi_object_freeze#
napi_status napi_object_freeze(napi_env env,
napi_value object);
[in] env: The environment that the Node-API call is invoked under.[in] object: The object to freeze.
Returns napi_ok if the API succeeded.
This method freezes a given object. This prevents new properties from being added to it, existing properties from being removed, prevents changing the enumerability, configurability, or writability of existing properties, and prevents the values of existing properties from being changed. It also prevents the object's prototype from being changed. This is described in Section 19.1.2.6 of the ECMA-262 specification.
napi_object_seal#
napi_status napi_object_seal(napi_env env,
napi_value object);
[in] env: The environment that the Node-API call is invoked under.[in] object: The object to seal.
Returns napi_ok if the API succeeded.
This method seals a given object. This prevents new properties from being added to it, as well as marking all existing properties as non-configurable. This is described in Section 19.1.2.20 of the ECMA-262 specification.
node_api_set_prototype#
Stability: 1 - Experimental
napi_status node_api_set_prototype(napi_env env,
napi_value object,
napi_value value);
[in] env: The environment that the Node-API call is invoked under.[in] object: The object on which to set the prototype.[in] value: The prototype value.
Returns napi_ok if the API succeeded.
This API sets the prototype of the Object passed in.
Working with JavaScript functions#
Node-API provides a set of APIs that allow JavaScript code to call back into native code. Node-APIs that support calling back into native code take in a callback functions represented by the napi_callback type. When the JavaScript VM calls back to native code, the napi_callback function provided is invoked. The APIs documented in this section allow the callback function to do the following:
- Get information about the context in which the callback was invoked.
- Get the arguments passed into the callback.
- Return a
napi_valueback from the callback.
Additionally, Node-API provides a set of functions which allow calling JavaScript functions from native code. One can either call a function like a regular JavaScript function call, or as a constructor function.
Any non-NULL data which is passed to this API via the data field of the napi_property_descriptor items can be associated with object and freed whenever object is garbage-collected by passing both object and the data to napi_add_finalizer.
napi_call_function#
NAPI_EXTERN napi_status napi_call_function(napi_env env,
napi_value recv,
napi_value func,
size_t argc,
const napi_value* argv,
napi_value* result);
[in] env: The environment that the API is invoked under.[in] recv: Thethisvalue passed to the called function.[in] func:napi_valuerepresenting the JavaScript function to be invoked.[in] argc: The count of elements in theargvarray.[in] argv: Array ofnapi_valuesrepresenting JavaScript values passed in as arguments to the function.[out] result:napi_valuerepresenting the JavaScript object returned.
Returns napi_ok if the API succeeded.
This method allows a JavaScript function object to be called from a native add-on. This is the primary mechanism of calling back from the add-on's native code into JavaScript. For the special case of calling into JavaScript after an async operation, see napi_make_callback.
A sample use case might look as follows. Consider the following JavaScript snippet:
function AddTwo(num) {
return num + 2;
}
global.AddTwo = AddTwo;
Then, the above function can be invoked from a native add-on using the following code:
// Get the function named "AddTwo" on the global object
napi_value global, add_two, arg;
napi_status status = napi_get_global(env, &global);
if (status != napi_ok) return;
status = napi_get_named_property(env, global, "AddTwo", &add_two);
if (status != napi_ok) return;
// const arg = 1337
status = napi_create_int32(env, 1337, &arg);
if (status != napi_ok) return;
napi_value* argv = &arg;
size_t argc = 1;
// AddTwo(arg);
napi_value return_val;
status = napi_call_function(env, global, add_two, argc, argv, &return_val);
if (status != napi_ok) return;
// Convert the result back to a native type
int32_t result;
status = napi_get_value_int32(env, return_val, &result);
if (status != napi_ok) return;
napi_create_function#
napi_status napi_create_function(napi_env env,
const char* utf8name,
size_t length,
napi_callback cb,
void* data,
napi_value* result);
[in] env: The environment that the API is invoked under.[in] utf8Name: Optional name of the function encoded as UTF8. This is visible within JavaScript as the new function object'snameproperty.[in] length: The length of theutf8namein bytes, orNAPI_AUTO_LENGTHif it is null-terminated.[in] cb: The native function which should be called when this function object is invoked.napi_callbackprovides more details.[in] data: User-provided data context. This will be passed back into the function when invoked later.[out] result:napi_valuerepresenting the JavaScript function object for the newly created function.
Returns napi_ok if the API succeeded.
This API allows an add-on author to create a function object in native code. This is the primary mechanism to allow calling into the add-on's native code from JavaScript.
The newly created function is not automatically visible from script after this call. Instead, a property must be explicitly set on any object that is visible to JavaScript, in order for the function to be accessible from script.
In order to expose a function as part of the add-on's module exports, set the newly created function on the exports object. A sample module might look as follows:
napi_value SayHello(napi_env env, napi_callback_info info) {
printf("Hello\n");
return NULL;
}
napi_value Init(napi_env env, napi_value exports) {
napi_status status;
napi_value fn;
status = napi_create_function(env, NULL, 0, SayHello, NULL, &fn);
if (status != napi_ok) return NULL;
status = napi_set_named_property(env, exports, "sayHello", fn);
if (status != napi_ok) return NULL;
return exports;
}
NAPI_MODULE(NODE_GYP_MODULE_NAME, Init)
Given the above code, the add-on can be used from JavaScript as follows:
const myaddon = require('./addon');
myaddon.sayHello();
The string passed to require() is the name of the target in binding.gyp responsible for creating the .node file.
Any non-NULL data which is passed to this API via the data parameter can be associated with the resulting JavaScript function (which is returned in the result parameter) and freed whenever the function is garbage-collected by passing both the JavaScript function and the data to napi_add_finalizer.
JavaScript Functions are described in Section Function objects of the ECMAScript Language Specification.
napi_get_cb_info#
napi_status napi_get_cb_info(napi_env env,
napi_callback_info cbinfo,
size_t* argc,
napi_value* argv,
napi_value* thisArg,
void** data)
[in] env: The environment that the API is invoked under.[in] cbinfo: The callback info passed into the callback function.[in-out] argc: Specifies the length of the providedargvarray and receives the actual count of arguments.argccan optionally be ignored by passingNULL.[out] argv: C array ofnapi_values to which the arguments will be copied. If there are more arguments than the provided count, only the requested number of arguments are copied. If there are fewer arguments provided than claimed, the rest ofargvis filled withnapi_valuevalues that representundefined.argvcan optionally be ignored by passingNULL.[out] thisArg: Receives the JavaScriptthisargument for the call.thisArgcan optionally be ignored by passingNULL.[out] data: Receives the data pointer for the callback.datacan optionally be ignored by passingNULL.
Returns napi_ok if the API succeeded.
This method is used within a callback function to retrieve details about the call like the arguments and the this pointer from a given callback info.
napi_get_new_target#
napi_status napi_get_new_target(napi_env env,
napi_callback_info cbinfo,
napi_value* result)
[in] env: The environment that the API is invoked under.[in] cbinfo: The callback info passed into the callback function.[out] result: Thenew.targetof the constructor call.
Returns napi_ok if the API succeeded.
This API returns the new.target of the constructor call. If the current callback is not a constructor call, the result is NULL.
napi_new_instance#
napi_status napi_new_instance(napi_env env,
napi_value cons,
size_t argc,
napi_value* argv,
napi_value* result)
[in] env: The environment that the API is invoked under.[in] cons:napi_valuerepresenting the JavaScript function to be invoked as a constructor.[in] argc: The count of elements in theargvarray.[in] argv: Array of JavaScript values asnapi_valuerepresenting the arguments to the constructor. Ifargcis zero this parameter may be omitted by passing inNULL.[out] result:napi_valuerepresenting the JavaScript object returned, which in this case is the constructed object.
This method is used to instantiate a new JavaScript value using a given napi_value that represents the constructor for the object. For example, consider the following snippet:
function MyObject(param) {
this.param = param;
}
const arg = 'hello';
const value = new MyObject(arg);
The following can be approximated in Node-API using the following snippet:
// Get the constructor function MyObject
napi_value global, constructor, arg, value;
napi_status status = napi_get_global(env, &global);
if (status != napi_ok) return;
status = napi_get_named_property(env, global, "MyObject", &constructor);
if (status != napi_ok) return;
// const arg = "hello"
status = napi_create_string_utf8(env, "hello", NAPI_AUTO_LENGTH, &arg);
if (status != napi_ok) return;
napi_value* argv = &arg;
size_t argc = 1;
// const value = new MyObject(arg)
status = napi_new_instance(env, constructor, argc, argv, &value);
Returns napi_ok if the API succeeded.
Object wrap#
Node-API offers a way to "wrap" C++ classes and instances so that the class constructor and methods can be called from JavaScript.
- The
napi_define_classAPI defines a JavaScript class with constructor, static properties and methods, and instance properties and methods that correspond to the C++ class. - When JavaScript code invokes the constructor, the constructor callback uses
napi_wrapto wrap a new C++ instance in a JavaScript object, then returns the wrapper object. - When JavaScript code invokes a method or property accessor on the class, the corresponding
napi_callbackC++ function is invoked. For an instance callback,napi_unwrapobtains the C++ instance that is the target of the call.
For wrapped objects it may be difficult to distinguish between a function called on a class prototype and a function called on an instance of a class. A common pattern used to address this problem is to save a persistent reference to the class constructor for later instanceof checks.
napi_value MyClass_constructor = NULL;
status = napi_get_reference_value(env, MyClass::es_constructor, &MyClass_constructor);
assert(napi_ok == status);
bool is_instance = false;
status = napi_instanceof(env, es_this, MyClass_constructor, &is_instance);
assert(napi_ok == status);
if (is_instance) {
// napi_unwrap() ...
} else {
// otherwise...
}
The reference must be freed once it is no longer needed.
There are occasions where napi_instanceof() is insufficient for ensuring that a JavaScript object is a wrapper for a certain native type. This is the case especially when wrapped JavaScript objects are passed back into the addon via static methods rather than as the this value of prototype methods. In such cases there is a chance that they may be unwrapped incorrectly.
const myAddon = require('./build/Release/my_addon.node');
// `openDatabase()` returns a JavaScript object that wraps a native database
// handle.
const dbHandle = myAddon.openDatabase();
// `query()` returns a JavaScript object that wraps a native query handle.
const queryHandle = myAddon.query(dbHandle, 'Gimme ALL the things!');
// There is an accidental error in the line below. The first parameter to
// `myAddon.queryHasRecords()` should be the database handle (`dbHandle`), not
// the query handle (`query`), so the correct condition for the while-loop
// should be
//
// myAddon.queryHasRecords(dbHandle, queryHandle)
//
while (myAddon.queryHasRecords(queryHandle, dbHandle)) {
// retrieve records
}
In the above example myAddon.queryHasRecords() is a method that accepts two arguments. The first is a database handle and the second is a query handle. Internally, it unwraps the first argument and casts the resulting pointer to a native database handle. It then unwraps the second argument and casts the resulting pointer to a query handle. If the arguments are passed in the wrong order, the casts will work, however, there is a good chance that the underlying database operation will fail, or will even cause an invalid memory access.
To ensure that the pointer retrieved from the first argument is indeed a pointer to a database handle and, similarly, that the pointer retrieved from the second argument is indeed a pointer to a query handle, the implementation of queryHasRecords() has to perform a type validation. Retaining the JavaScript class constructor from which the database handle was instantiated and the constructor from which the query handle was instantiated in napi_refs can help, because napi_instanceof() can then be used to ensure that the instances passed into queryHashRecords() are indeed of the correct type.
Unfortunately, napi_instanceof() does not protect against prototype manipulation. For example, the prototype of the database handle instance can be set to the prototype of the constructor for query handle instances. In this case, the database handle instance can appear as a query handle instance, and it will pass the napi_instanceof() test for a query handle instance, while still containing a pointer to a database handle.
To this end, Node-API provides type-tagging capabilities.
A type tag is a 128-bit integer unique to the addon. Node-API provides the napi_type_tag structure for storing a type tag. When such a value is passed along with a JavaScript object or external stored in a napi_value to napi_type_tag_object(), the JavaScript object will be "marked" with the type tag. The "mark" is invisible on the JavaScript side. When a JavaScript object arrives into a native binding, napi_check_object_type_tag() can be used along with the original type tag to determine whether the JavaScript object was previously "marked" with the type tag. This creates a type-checking capability of a higher fidelity than napi_instanceof() can provide, because such type- tagging survives prototype manipulation and addon unloading/reloading.
Continuing the above example, the following skeleton addon implementation illustrates the use of napi_type_tag_object() and napi_check_object_type_tag().
// This value is the type tag for a database handle. The command
//
// uuidgen | sed -r -e 's/-//g' -e 's/(.{16})(.*)/0x\1, 0x\2/'
//
// can be used to obtain the two values with which to initialize the structure.
static const napi_type_tag DatabaseHandleTypeTag = {
0x1edf75a38336451d, 0xa5ed9ce2e4c00c38
};
// This value is the type tag for a query handle.
static const napi_type_tag QueryHandleTypeTag = {
0x9c73317f9fad44a3, 0x93c3920bf3b0ad6a
};
static napi_value
openDatabase(napi_env env, napi_callback_info info) {
napi_status status;
napi_value result;
// Perform the underlying action which results in a database handle.
DatabaseHandle* dbHandle = open_database();
// Create a new, empty JS object.
status = napi_create_object(env, &result);
if (status != napi_ok) return NULL;
// Tag the object to indicate that it holds a pointer to a `DatabaseHandle`.
status = napi_type_tag_object(env, result, &DatabaseHandleTypeTag);
if (status != napi_ok) return NULL;
// Store the pointer to the `DatabaseHandle` structure inside the JS object.
status = napi_wrap(env, result, dbHandle, NULL, NULL, NULL);
if (status != napi_ok) return NULL;
return result;
}
// Later when we receive a JavaScript object purporting to be a database handle
// we can use `napi_check_object_type_tag()` to ensure that it is indeed such a
// handle.
static napi_value
query(napi_env env, napi_callback_info info) {
napi_status status;
size_t argc = 2;
napi_value argv[2];
bool is_db_handle;
status = napi_get_cb_info(env, info, &argc, argv, NULL, NULL);
if (status != napi_ok) return NULL;
// Check that the object passed as the first parameter has the previously
// applied tag.
status = napi_check_object_type_tag(env,
argv[0],
&DatabaseHandleTypeTag,
&is_db_handle);
if (status != napi_ok) return NULL;
// Throw a `TypeError` if it doesn't.
if (!is_db_handle) {
// Throw a TypeError.
return NULL;
}
}
napi_define_class#
napi_status napi_define_class(napi_env env,
const char* utf8name,
size_t length,
napi_callback constructor,
void* data,
size_t property_count,
const napi_property_descriptor* properties,
napi_value* result);
[in] env: The environment that the API is invoked under.[in] utf8name: Name of the JavaScript constructor function. For clarity, it is recommended to use the C++ class name when wrapping a C++ class.[in] length: The length of theutf8namein bytes, orNAPI_AUTO_LENGTHif it is null-terminated.[in] constructor: Callback function that handles constructing instances of the class. When wrapping a C++ class, this method must be a static member with thenapi_callbacksignature. A C++ class constructor cannot be used.napi_callbackprovides more details.[in] data: Optional data to be passed to the constructor callback as thedataproperty of the callback info.[in] property_count: Number of items in thepropertiesarray argument.[in] properties: Array of property descriptors describing static and instance data properties, accessors, and methods on the class Seenapi_property_descriptor.[out] result: Anapi_valuerepresenting the constructor function for the class.
Returns napi_ok if the API succeeded.
Defines a JavaScript class, including:
- A JavaScript constructor function that has the class name. When wrapping a corresponding C++ class, the callback passed via
constructorcan be used to instantiate a new C++ class instance, which can then be placed inside the JavaScript object instance being constructed usingnapi_wrap. - Properties on the constructor function whose implementation can call corresponding static data properties, accessors, and methods of the C++ class (defined by property descriptors with the
napi_staticattribute). - Properties on the constructor function's
prototypeobject. When wrapping a C++ class, non-static data properties, accessors, and methods of the C++ class can be called from the static functions given in the property descriptors without thenapi_staticattribute after retrieving the C++ class instance placed inside the JavaScript object instance by usingnapi_unwrap.
When wrapping a C++ class, the C++ constructor callback passed via constructor should be a static method on the class that calls the actual class constructor, then wraps the new C++ instance in a JavaScript object, and returns the wrapper object. See napi_wrap for details.
The JavaScript constructor function returned from napi_define_class is often saved and used later to construct new instances of the class from native code, and/or to check whether provided values are instances of the class. In that case, to prevent the function value from being garbage-collected, a strong persistent reference to it can be created using napi_create_reference, ensuring that the reference count is kept >= 1.
Any non-NULL data which is passed to this API via the data parameter or via the data field of the napi_property_descriptor array items can be associated with the resulting JavaScript constructor (which is returned in the result parameter) and freed whenever the class is garbage-collected by passing both the JavaScript function and the data to napi_add_finalizer.
napi_wrap#
napi_status napi_wrap(napi_env env,
napi_value js_object,
void* native_object,
napi_finalize finalize_cb,
void* finalize_hint,
napi_ref* result);
[in] env: The environment that the API is invoked under.[in] js_object: The JavaScript object that will be the wrapper for the native object.[in] native_object: The native instance that will be wrapped in the JavaScript object.[in] finalize_cb: Optional native callback that can be used to free the native instance when the JavaScript object has been garbage-collected.napi_finalizeprovides more details.[in] finalize_hint: Optional contextual hint that is passed to the finalize callback.[out] result: Optional reference to the wrapped object.
Returns napi_ok if the API succeeded.
Wraps a native instance in a JavaScript object. The native instance can be retrieved later using napi_unwrap().
When JavaScript code invokes a constructor for a class that was defined using napi_define_class(), the napi_callback for the constructor is invoked. After constructing an instance of the native class, the callback must then call napi_wrap() to wrap the newly constructed instance in the already-created JavaScript object that is the this argument to the constructor callback. (That this object was created from the constructor function's prototype, so it already has definitions of all the instance properties and methods.)
Typically when wrapping a class instance, a finalize callback should be provided that simply deletes the native instance that is received as the data argument to the finalize callback.
The optional returned reference is initially a weak reference, meaning it has a reference count of 0. Typically this reference count would be incremented temporarily during async operations that require the instance to remain valid.
Caution: The optional returned reference (if obtained) should be deleted via napi_delete_reference ONLY in response to the finalize callback invocation. If it is deleted before then, then the finalize callback may never be invoked. Therefore, when obtaining a reference a finalize callback is also required in order to enable correct disposal of the reference.
Finalizer callbacks may be deferred, leaving a window where the object has been garbage collected (and the weak reference is invalid) but the finalizer hasn't been called yet. When using napi_get_reference_value() on weak references returned by napi_wrap(), you should still handle an empty result.
Calling napi_wrap() a second time on an object will return an error. To associate another native instance with the object, use napi_remove_wrap() first.
napi_unwrap#
napi_status napi_unwrap(napi_env env,
napi_value js_object,
void** result);
[in] env: The environment that the API is invoked under.[in] js_object: The object associated with the native instance.[out] result: Pointer to the wrapped native instance.
Returns napi_ok if the API succeeded.
Retrieves a native instance that was previously wrapped in a JavaScript object using napi_wrap().
When JavaScript code invokes a method or property accessor on the class, the corresponding napi_callback is invoked. If the callback is for an instance method or accessor, then the this argument to the callback is the wrapper object; the wrapped C++ instance that is the target of the call can be obtained then by calling napi_unwrap() on the wrapper object.
napi_remove_wrap#
napi_status napi_remove_wrap(napi_env env,
napi_value js_object,
void** result);
[in] env: The environment that the API is invoked under.[in] js_object: The object associated with the native instance.[out] result: Pointer to the wrapped native instance.
Returns napi_ok if the API succeeded.
Retrieves a native instance that was previously wrapped in the JavaScript object js_object using napi_wrap() and removes the wrapping. If a finalize callback was associated with the wrapping, it will no longer be called when the JavaScript object becomes garbage-collected.
napi_type_tag_object#
napi_status napi_type_tag_object(napi_env env,
napi_value js_object,
const napi_type_tag* type_tag);
[in] env: The environment that the API is invoked under.[in] js_object: The JavaScript object or external to be marked.[in] type_tag: The tag with which the object is to be marked.
Returns napi_ok if the API succeeded.
Associates the value of the type_tag pointer with the JavaScript object or external. napi_check_object_type_tag() can then be used to compare the tag that was attached to the object with one owned by the addon to ensure that the object has the right type.
If the object already has an associated type tag, this API will return napi_invalid_arg.
napi_check_object_type_tag#
napi_status napi_check_object_type_tag(napi_env env,
napi_value js_object,
const napi_type_tag* type_tag,
bool* result);
[in] env: The environment that the API is invoked under.[in] js_object: The JavaScript object or external whose type tag to examine.[in] type_tag: The tag with which to compare any tag found on the object.[out] result: Whether the type tag given matched the type tag on the object.falseis also returned if no type tag was found on the object.
Returns napi_ok if the API succeeded.
Compares the pointer given as type_tag with any that can be found on js_object. If no tag is found on js_object or, if a tag is found but it does not match type_tag, then result is set to false. If a tag is found and it matches type_tag, then result is set to true.
napi_add_finalizer#
napi_status napi_add_finalizer(napi_env env,
napi_value js_object,
void* finalize_data,
node_api_basic_finalize finalize_cb,
void* finalize_hint,
napi_ref* result);
[in] env: The environment that the API is invoked under.[in] js_object: The JavaScript object to which the native data will be attached.[in] finalize_data: Optional data to be passed tofinalize_cb.[in] finalize_cb: Native callback that will be used to free the native data when the JavaScript object has been garbage-collected.napi_finalizeprovides more details.[in] finalize_hint: Optional contextual hint that is passed to the finalize callback.[out] result: Optional reference to the JavaScript object.
Returns napi_ok if the API succeeded.
Adds a napi_finalize callback which will be called when the JavaScript object in js_object has been garbage-collected.
This API can be called multiple times on a single JavaScript object.
Caution: The optional returned reference (if obtained) should be deleted via napi_delete_reference ONLY in response to the finalize callback invocation. If it is deleted before then, then the finalize callback may never be invoked. Therefore, when obtaining a reference a finalize callback is also required in order to enable correct disposal of the reference.
node_api_post_finalizer#
Stability: 1 - Experimental
napi_status node_api_post_finalizer(node_api_basic_env env,
napi_finalize finalize_cb,
void* finalize_data,
void* finalize_hint);
[in] env: The environment that the API is invoked under.[in] finalize_cb: Native callback that will be used to free the native data when the JavaScript object has been garbage-collected.napi_finalizeprovides more details.[in] finalize_data: Optional data to be passed tofinalize_cb.[in] finalize_hint: Optional contextual hint that is passed to the finalize callback.
Returns napi_ok if the API succeeded.
Schedules a napi_finalize callback to be called asynchronously in the event loop.
Normally, finalizers are called while the GC (garbage collector) collects objects. At that point calling any Node-API that may cause changes in the GC state will be disabled and will crash Node.js.
node_api_post_finalizer helps to work around this limitation by allowing the add-on to defer calls to such Node-APIs to a point in time outside of the GC finalization.
Simple asynchronous operations#
Addon modules often need to leverage async helpers from libuv as part of their implementation. This allows them to schedule work to be executed asynchronously so that their methods can return in advance of the work being completed. This allows them to avoid blocking overall execution of the Node.js application.
Node-API provides an ABI-stable interface for these supporting functions which covers the most common asynchronous use cases.
Node-API defines the napi_async_work structure which is used to manage asynchronous workers. Instances are created/deleted with napi_create_async_work and napi_delete_async_work.
The execute and complete callbacks are functions that will be invoked when the executor is ready to execute and when it completes its task respectively.
The execute function should avoid making any Node-API calls that could result in the execution of JavaScript or interaction with JavaScript objects. Most often, any code that needs to make Node-API calls should be made in complete callback instead. Avoid using the napi_env parameter in the execute callback as it will likely execute JavaScript.
These functions implement the following interfaces:
typedef void (*napi_async_execute_callback)(napi_env env,
void* data);
typedef void (*napi_async_complete_callback)(napi_env env,
napi_status status,
void* data);
When these methods are invoked, the data parameter passed will be the addon-provided void* data that was passed into the napi_create_async_work call.
Once created the async worker can be queued for execution using the napi_queue_async_work function:
napi_status napi_queue_async_work(node_api_basic_env env,
napi_async_work work);
napi_cancel_async_work can be used if the work needs to be cancelled before the work has started execution.
After calling napi_cancel_async_work, the complete callback will be invoked with a status value of napi_cancelled. The work should not be deleted before the complete callback invocation, even when it was cancelled.
napi_create_async_work#
napi_status napi_create_async_work(napi_env env,
napi_value async_resource,
napi_value async_resource_name,
napi_async_execute_callback execute,
napi_async_complete_callback complete,
void* data,
napi_async_work* result);
[in] env: The environment that the API is invoked under.[in] async_resource: An optional object associated with the async work that will be passed to possibleasync_hooksinithooks.[in] async_resource_name: Identifier for the kind of resource that is being provided for diagnostic information exposed by theasync_hooksAPI.[in] execute: The native function which should be called to execute the logic asynchronously. The given function is called from a worker pool thread and can execute in parallel with the main event loop thread.[in] complete: The native function which will be called when the asynchronous logic is completed or is cancelled. The given function is called from the main event loop thread.napi_async_complete_callbackprovides more details.[in] data: User-provided data context. This will be passed back into the execute and complete functions.[out] result:napi_async_work*which is the handle to the newly created async work.
Returns napi_ok if the API succeeded.
This API allocates a work object that is used to execute logic asynchronously. It should be freed using napi_delete_async_work once the work is no longer required.
async_resource_name should be a null-terminated, UTF-8-encoded string.
The async_resource_name identifier is provided by the user and should be representative of the type of async work being performed. It is also recommended to apply namespacing to the identifier, e.g. by including the module name. See the async_hooks documentation for more information.
napi_delete_async_work#
napi_status napi_delete_async_work(napi_env env,
napi_async_work work);
[in] env: The environment that the API is invoked under.[in] work: The handle returned by the call tonapi_create_async_work.
Returns napi_ok if the API succeeded.
This API frees a previously allocated work object.
This API can be called even if there is a pending JavaScript exception.
napi_queue_async_work#
napi_status napi_queue_async_work(node_api_basic_env env,
napi_async_work work);
[in] env: The environment that the API is invoked under.[in] work: The handle returned by the call tonapi_create_async_work.
Returns napi_ok if the API succeeded.
This API requests that the previously allocated work be scheduled for execution. Once it returns successfully, this API must not be called again with the same napi_async_work item or the result will be undefined.
napi_cancel_async_work#
napi_status napi_cancel_async_work(node_api_basic_env env,
napi_async_work work);
[in] env: The environment that the API is invoked under.[in] work: The handle returned by the call tonapi_create_async_work.
Returns napi_ok if the API succeeded.
This API cancels queued work if it has not yet been started. If it has already started executing, it cannot be cancelled and napi_generic_failure will be returned. If successful, the complete callback will be invoked with a status value of napi_cancelled. The work should not be deleted before the complete callback invocation, even if it has been successfully cancelled.
This API can be called even if there is a pending JavaScript exception.
Custom asynchronous operations#
The simple asynchronous work APIs above may not be appropriate for every scenario. When using any other asynchronous mechanism, the following APIs are necessary to ensure an asynchronous operation is properly tracked by the runtime.
napi_async_init#
napi_status napi_async_init(napi_env env,
napi_value async_resource,
napi_value async_resource_name,
napi_async_context* result)
[in] env: The environment that the API is invoked under.[in] async_resource: Object associated with the async work that will be passed to possibleasync_hooksinithooks and can be accessed byasync_hooks.executionAsyncResource().[in] async_resource_name: Identifier for the kind of resource that is being provided for diagnostic information exposed by theasync_hooksAPI.[out] result: The initialized async context.
Returns napi_ok if the API succeeded.
In order to retain ABI compatibility with previous versions, passing NULL for async_resource does not result in an error. However, this is not recommended as this will result in undesirable behavior with async_hooks init hooks and async_hooks.executionAsyncResource() as the resource is now required by the underlying async_hooks implementation in order to provide the linkage between async callbacks.
Previous versions of this API were not maintaining a strong reference to async_resource while the napi_async_context object existed and instead expected the caller to hold a strong reference. This has been changed, as a corresponding call to napi_async_destroy for every call to napi_async_init() is a requirement in any case to avoid memory leaks.
napi_async_destroy#
napi_status napi_async_destroy(napi_env env,
napi_async_context async_context);
[in] env: The environment that the API is invoked under.[in] async_context: The async context to be destroyed.
Returns napi_ok if the API succeeded.
This API can be called even if there is a pending JavaScript exception.
napi_make_callback#
NAPI_EXTERN napi_status napi_make_callback(napi_env env,
napi_async_context async_context,
napi_value recv,
napi_value func,
size_t argc,
const napi_value* argv,
napi_value* result);
[in] env: The environment that the API is invoked under.[in] async_context: Context for the async operation that is invoking the callback. This should normally be a value previously obtained fromnapi_async_init. In order to retain ABI compatibility with previous versions, passingNULLforasync_contextdoes not result in an error. However, this results in incorrect operation of async hooks. Potential issues include loss of async context when using theAsyncLocalStorageAPI.[in] recv: Thethisvalue passed to the called function.[in] func:napi_valuerepresenting the JavaScript function to be invoked.[in] argc: The count of elements in theargvarray.[in] argv: Array of JavaScript values asnapi_valuerepresenting the arguments to the function. Ifargcis zero this parameter may be omitted by passing inNULL.[out] result:napi_valuerepresenting the JavaScript object returned.
Returns napi_ok if the API succeeded.
This method allows a JavaScript function object to be called from a native add-on. This API is similar to napi_call_function. However, it is used to call from native code back into JavaScript after returning from an async operation (when there is no other script on the stack). It is a fairly simple wrapper around node::MakeCallback.
Note it is not necessary to use napi_make_callback from within a napi_async_complete_callback; in that situation the callback's async context has already been set up, so a direct call to napi_call_function is sufficient and appropriate. Use of the napi_make_callback function may be required when implementing custom async behavior that does not use napi_create_async_work.
Any process.nextTicks or Promises scheduled on the microtask queue by JavaScript during the callback are ran before returning back to C/C++.
napi_open_callback_scope#
NAPI_EXTERN napi_status napi_open_callback_scope(napi_env env,
napi_value resource_object,
napi_async_context context,
napi_callback_scope* result)
[in] env: The environment that the API is invoked under.[in] resource_object: An object associated with the async work that will be passed to possibleasync_hooksinithooks. This parameter has been deprecated and is ignored at runtime. Use theasync_resourceparameter innapi_async_initinstead.[in] context: Context for the async operation that is invoking the callback. This should be a value previously obtained fromnapi_async_init.[out] result: The newly created scope.
There are cases (for example, resolving promises) where it is necessary to have the equivalent of the scope associated with a callback in place when making certain Node-API calls. If there is no other script on the stack the napi_open_callback_scope and napi_close_callback_scope functions can be used to open/close the required scope.
napi_close_callback_scope#
NAPI_EXTERN napi_status napi_close_callback_scope(napi_env env,
napi_callback_scope scope)
[in] env: The environment that the API is invoked under.[in] scope: The scope to be closed.
This API can be called even if there is a pending JavaScript exception.
Version management#
napi_get_node_version#
typedef struct {
uint32_t major;
uint32_t minor;
uint32_t patch;
const char* release;
} napi_node_version;
napi_status napi_get_node_version(node_api_basic_env env,
const napi_node_version** version);
[in] env: The environment that the API is invoked under.[out] version: A pointer to version information for Node.js itself.
Returns napi_ok if the API succeeded.
This function fills the version struct with the major, minor, and patch version of Node.js that is currently running, and the release field with the value of process.release.name.
The returned buffer is statically allocated and does not need to be freed.
napi_get_version#
napi_status napi_get_version(node_api_basic_env env,
uint32_t* result);
[in] env: The environment that the API is invoked under.[out] result: The highest version of Node-API supported.
Returns napi_ok if the API succeeded.
This API returns the highest Node-API version supported by the Node.js runtime. Node-API is planned to be additive such that newer releases of Node.js may support additional API functions. In order to allow an addon to use a newer function when running with versions of Node.js that support it, while providing fallback behavior when running with Node.js versions that don't support it:
- Call
napi_get_version()to determine if the API is available. - If available, dynamically load a pointer to the function using
uv_dlsym(). - Use the dynamically loaded pointer to invoke the function.
- If the function is not available, provide an alternate implementation that does not use the function.
Memory management#
napi_adjust_external_memory#
NAPI_EXTERN napi_status napi_adjust_external_memory(node_api_basic_env env,
int64_t change_in_bytes,
int64_t* result);
[in] env: The environment that the API is invoked under.[in] change_in_bytes: The change in externally allocated memory that is kept alive by JavaScript objects.[out] result: The adjusted value. This value should reflect the total amount of external memory with the givenchange_in_bytesincluded. The absolute value of the returned value should not be depended on. For example, implementations may use a single counter for all addons, or a counter for each addon.
Returns napi_ok if the API succeeded.
This function gives the runtime an indication of the amount of externally allocated memory that is kept alive by JavaScript objects (i.e. a JavaScript object that points to its own memory allocated by a native addon). Registering externally allocated memory may, but is not guaranteed to, trigger global garbage collections more often than it would otherwise.
This function is expected to be called in a manner such that an addon does not decrease the external memory more than it has increased the external memory.
Promises#
Node-API provides facilities for creating Promise objects as described in Section Promise objects of the ECMA specification. It implements promises as a pair of objects. When a promise is created by napi_create_promise(), a "deferred" object is created and returned alongside the Promise. The deferred object is bound to the created Promise and is the only means to resolve or reject the Promise using napi_resolve_deferred() or napi_reject_deferred(). The deferred object that is created by napi_create_promise() is freed by napi_resolve_deferred() or napi_reject_deferred(). The Promise object may be returned to JavaScript where it can be used in the usual fashion.
For example, to create a promise and pass it to an asynchronous worker:
napi_deferred deferred;
napi_value promise;
napi_status status;
// Create the promise.
status = napi_create_promise(env, &deferred, &promise);
if (status != napi_ok) return NULL;
// Pass the deferred to a function that performs an asynchronous action.
do_something_asynchronous(deferred);
// Return the promise to JS
return promise;
The above function do_something_asynchronous() would perform its asynchronous action and then it would resolve or reject the deferred, thereby concluding the promise and freeing the deferred:
napi_deferred deferred;
napi_value undefined;
napi_status status;
// Create a value with which to conclude the deferred.
status = napi_get_undefined(env, &undefined);
if (status != napi_ok) return NULL;
// Resolve or reject the promise associated with the deferred depending on
// whether the asynchronous action succeeded.
if (asynchronous_action_succeeded) {
status = napi_resolve_deferred(env, deferred, undefined);
} else {
status = napi_reject_deferred(env, deferred, undefined);
}
if (status != napi_ok) return NULL;
// At this point the deferred has been freed, so we should assign NULL to it.
deferred = NULL;
napi_create_promise#
napi_status napi_create_promise(napi_env env,
napi_deferred* deferred,
napi_value* promise);
[in] env: The environment that the API is invoked under.[out] deferred: A newly created deferred object which can later be passed tonapi_resolve_deferred()ornapi_reject_deferred()to resolve resp. reject the associated promise.[out] promise: The JavaScript promise associated with the deferred object.
Returns napi_ok if the API succeeded.
This API creates a deferred object and a JavaScript promise.
napi_resolve_deferred#
napi_status napi_resolve_deferred(napi_env env,
napi_deferred deferred,
napi_value resolution);
[in] env: The environment that the API is invoked under.[in] deferred: The deferred object whose associated promise to resolve.[in] resolution: The value with which to resolve the promise.
This API resolves a JavaScript promise by way of the deferred object with which it is associated. Thus, it can only be used to resolve JavaScript promises for which the corresponding deferred object is available. This effectively means that the promise must have been created using napi_create_promise() and the deferred object returned from that call must have been retained in order to be passed to this API.
The deferred object is freed upon successful completion.
napi_reject_deferred#
napi_status napi_reject_deferred(napi_env env,
napi_deferred deferred,
napi_value rejection);
[in] env: The environment that the API is invoked under.[in] deferred: The deferred object whose associated promise to resolve.[in] rejection: The value with which to reject the promise.
This API rejects a JavaScript promise by way of the deferred object with which it is associated. Thus, it can only be used to reject JavaScript promises for which the corresponding deferred object is available. This effectively means that the promise must have been created using napi_create_promise() and the deferred object returned from that call must have been retained in order to be passed to this API.
The deferred object is freed upon successful completion.
napi_is_promise#
napi_status napi_is_promise(napi_env env,
napi_value value,
bool* is_promise);
[in] env: The environment that the API is invoked under.[in] value: The value to examine[out] is_promise: Flag indicating whetherpromiseis a native promise object (that is, a promise object created by the underlying engine).
Script execution#
Node-API provides an API for executing a string containing JavaScript using the underlying JavaScript engine.
napi_run_script#
NAPI_EXTERN napi_status napi_run_script(napi_env env,
napi_value script,
napi_value* result);
[in] env: The environment that the API is invoked under.[in] script: A JavaScript string containing the script to execute.[out] result: The value resulting from having executed the script.
This function executes a string of JavaScript code and returns its result with the following caveats:
- Unlike
eval, this function does not allow the script to access the current lexical scope, and therefore also does not allow to access the module scope, meaning that pseudo-globals such asrequirewill not be available. - The script can access the global scope. Function and
vardeclarations in the script will be added to theglobalobject. Variable declarations made usingletandconstwill be visible globally, but will not be added to theglobalobject. - The value of
thisisglobalwithin the script.
libuv event loop#
Node-API provides a function for getting the current event loop associated with a specific napi_env.
napi_get_uv_event_loop#
NAPI_EXTERN napi_status napi_get_uv_event_loop(node_api_basic_env env,
struct uv_loop_s** loop);
[in] env: The environment that the API is invoked under.[out] loop: The current libuv loop instance.
Note: While libuv has been relatively stable over time, it does not provide an ABI stability guarantee. Use of this function should be avoided. Its use may result in an addon that does not work across Node.js versions. asynchronous-thread-safe-function-calls are an alternative for many use cases.
Asynchronous thread-safe function calls#
JavaScript functions can normally only be called from a native addon's main thread. If an addon creates additional threads, then Node-API functions that require a napi_env, napi_value, or napi_ref must not be called from those threads.
When an addon has additional threads and JavaScript functions need to be invoked based on the processing completed by those threads, those threads must communicate with the addon's main thread so that the main thread can invoke the JavaScript function on their behalf. The thread-safe function APIs provide an easy way to do this.
These APIs provide the type napi_threadsafe_function as well as APIs to create, destroy, and call objects of this type. napi_create_threadsafe_function() creates a persistent reference to a napi_value that holds a JavaScript function which can be called from multiple threads. The calls happen asynchronously. This means that values with which the JavaScript callback is to be called will be placed in a queue, and, for each value in the queue, a call will eventually be made to the JavaScript function.
Upon creation of a napi_threadsafe_function a napi_finalize callback can be provided. This callback will be invoked on the main thread when the thread-safe function is about to be destroyed. It receives the context and the finalize data given during construction, and provides an opportunity for cleaning up after the threads e.g. by calling uv_thread_join(). Aside from the main loop thread, no threads should be using the thread-safe function after the finalize callback completes.
The context given during the call to napi_create_threadsafe_function() can be retrieved from any thread with a call to napi_get_threadsafe_function_context().
Calling a thread-safe function#
napi_call_threadsafe_function() can be used for initiating a call into JavaScript. napi_call_threadsafe_function() accepts a parameter which controls whether the API behaves blockingly. If set to napi_tsfn_nonblocking, the API behaves non-blockingly, returning napi_queue_full if the queue was full, preventing data from being successfully added to the queue. If set to napi_tsfn_blocking, the API blocks until space becomes available in the queue. napi_call_threadsafe_function() never blocks if the thread-safe function was created with a maximum queue size of 0.
napi_call_threadsafe_function() should not be called with napi_tsfn_blocking from a JavaScript thread, because, if the queue is full, it may cause the JavaScript thread to deadlock.
The actual call into JavaScript is controlled by the callback given via the call_js_cb parameter. call_js_cb is invoked on the main thread once for each value that was placed into the queue by a successful call to napi_call_threadsafe_function(). If such a callback is not given, a default callback will be used, and the resulting JavaScript call will have no arguments. The call_js_cb callback receives the JavaScript function to call as a napi_value in its parameters, as well as the void* context pointer used when creating the napi_threadsafe_function, and the next data pointer that was created by one of the secondary threads. The callback can then use an API such as napi_call_function() to call into JavaScript.
The callback may also be invoked with env and call_js_cb both set to NULL to indicate that calls into JavaScript are no longer possible, while items remain in the queue that may need to be freed. This normally occurs when the Node.js process exits while there is a thread-safe function still active.
It is not necessary to call into JavaScript via napi_make_callback() because Node-API runs call_js_cb in a context appropriate for callbacks.
Zero or more queued items may be invoked in each tick of the event loop. Applications should not depend on a specific behavior other than progress in invoking callbacks will be made and events will be invoked as time moves forward.
Reference counting of thread-safe functions#
Threads can be added to and removed from a napi_threadsafe_function object during its existence. Thus, in addition to specifying an initial number of threads upon creation, napi_acquire_threadsafe_function can be called to indicate that a new thread will start making use of the thread-safe function. Similarly, napi_release_threadsafe_function can be called to indicate that an existing thread will stop making use of the thread-safe function.
napi_threadsafe_function objects are destroyed when every thread which uses the object has called napi_release_threadsafe_function() or has received a return status of napi_closing in response to a call to napi_call_threadsafe_function. The queue is emptied before the napi_threadsafe_function is destroyed. napi_release_threadsafe_function() should be the last API call made in conjunction with a given napi_threadsafe_function, because after the call completes, there is no guarantee that the napi_threadsafe_function is still allocated. For the same reason, do not use a thread-safe function after receiving a return value of napi_closing in response to a call to napi_call_threadsafe_function. Data associated with the napi_threadsafe_function can be freed in its napi_finalize callback which was passed to napi_create_threadsafe_function(). The parameter initial_thread_count of napi_create_threadsafe_function marks the initial number of acquisitions of the thread-safe functions, instead of calling napi_acquire_threadsafe_function multiple times at creation.
Once the number of threads making use of a napi_threadsafe_function reaches zero, no further threads can start making use of it by calling napi_acquire_threadsafe_function(). In fact, all subsequent API calls associated with it, except napi_release_threadsafe_function(), will return an error value of napi_closing.
The thread-safe function can be "aborted" by giving a value of napi_tsfn_abort to napi_release_threadsafe_function(). This will cause all subsequent APIs associated with the thread-safe function except napi_release_threadsafe_function() to return napi_closing even before its reference count reaches zero. In particular, napi_call_threadsafe_function() will return napi_closing, thus informing the threads that it is no longer possible to make asynchronous calls to the thread-safe function. This can be used as a criterion for terminating the thread. Upon receiving a return value of napi_closing from napi_call_threadsafe_function() a thread must not use the thread-safe function anymore because it is no longer guaranteed to be allocated.
Deciding whether to keep the process running#
Similarly to libuv handles, thread-safe functions can be "referenced" and "unreferenced". A "referenced" thread-safe function will cause the event loop on the thread on which it is created to remain alive until the thread-safe function is destroyed. In contrast, an "unreferenced" thread-safe function will not prevent the event loop from exiting. The APIs napi_ref_threadsafe_function and napi_unref_threadsafe_function exist for this purpose.
Neither does napi_unref_threadsafe_function mark the thread-safe functions as able to be destroyed nor does napi_ref_threadsafe_function prevent it from being destroyed.
napi_create_threadsafe_function#
NAPI_EXTERN napi_status
napi_create_threadsafe_function(napi_env env,
napi_value func,
napi_value async_resource,
napi_value async_resource_name,
size_t max_queue_size,
size_t initial_thread_count,
void* thread_finalize_data,
napi_finalize thread_finalize_cb,
void* context,
napi_threadsafe_function_call_js call_js_cb,
napi_threadsafe_function* result);
[in] env: The environment that the API is invoked under.[in] func: An optional JavaScript function to call from another thread. It must be provided ifNULLis passed tocall_js_cb.[in] async_resource: An optional object associated with the async work that will be passed to possibleasync_hooksinithooks.[in] async_resource_name: A JavaScript string to provide an identifier for the kind of resource that is being provided for diagnostic information exposed by theasync_hooksAPI.[in] max_queue_size: Maximum size of the queue.0for no limit.[in] initial_thread_count: The initial number of acquisitions, i.e. the initial number of threads, including the main thread, which will be making use of this function.[in] thread_finalize_data: Optional data to be passed tothread_finalize_cb.[in] thread_finalize_cb: Optional function to call when thenapi_threadsafe_functionis being destroyed.[in] context: Optional data to attach to the resultingnapi_threadsafe_function.[in] call_js_cb: Optional callback which calls the JavaScript function in response to a call on a different thread. This callback will be called on the main thread. If not given, the JavaScript function will be called with no parameters and withundefinedas itsthisvalue.napi_threadsafe_function_call_jsprovides more details.[out] result: The asynchronous thread-safe JavaScript function.
Change History:
Version 10 (
NAPI_VERSIONis defined as10or higher):Uncaught exceptions thrown in
call_js_cbare handled with the'uncaughtException'event, instead of being ignored.
napi_get_threadsafe_function_context#
NAPI_EXTERN napi_status
napi_get_threadsafe_function_context(napi_threadsafe_function func,
void** result);
[in] func: The thread-safe function for which to retrieve the context.[out] result: The location where to store the context.
This API may be called from any thread which makes use of func.
napi_call_threadsafe_function#
NAPI_EXTERN napi_status
napi_call_threadsafe_function(napi_threadsafe_function func,
void* data,
napi_threadsafe_function_call_mode is_blocking);
[in] func: The asynchronous thread-safe JavaScript function to invoke.[in] data: Data to send into JavaScript via the callbackcall_js_cbprovided during the creation of the thread-safe JavaScript function.[in] is_blocking: Flag whose value can be eithernapi_tsfn_blockingto indicate that the call should block if the queue is full ornapi_tsfn_nonblockingto indicate that the call should return immediately with a status ofnapi_queue_fullwhenever the queue is full.
This API should not be called with napi_tsfn_blocking from a JavaScript thread, because, if the queue is full, it may cause the JavaScript thread to deadlock.
This API will return napi_closing if napi_release_threadsafe_function() was called with abort set to napi_tsfn_abort from any thread. The value is only added to the queue if the API returns napi_ok.
This API may be called from any thread which makes use of func.
napi_acquire_threadsafe_function#
NAPI_EXTERN napi_status
napi_acquire_threadsafe_function(napi_threadsafe_function func);
[in] func: The asynchronous thread-safe JavaScript function to start making use of.
A thread should call this API before passing func to any other thread-safe function APIs to indicate that it will be making use of func. This prevents func from being destroyed when all other threads have stopped making use of it.
This API may be called from any thread which will start making use of func.
napi_release_threadsafe_function#
NAPI_EXTERN napi_status
napi_release_threadsafe_function(napi_threadsafe_function func,
napi_threadsafe_function_release_mode mode);
[in] func: The asynchronous thread-safe JavaScript function whose reference count to decrement.[in] mode: Flag whose value can be eithernapi_tsfn_releaseto indicate that the current thread will make no further calls to the thread-safe function, ornapi_tsfn_abortto indicate that in addition to the current thread, no other thread should make any further calls to the thread-safe function. If set tonapi_tsfn_abort, further calls tonapi_call_threadsafe_function()will returnnapi_closing, and no further values will be placed in the queue.
A thread should call this API when it stops making use of func. Passing func to any thread-safe APIs after having called this API has undefined results, as func may have been destroyed.
This API may be called from any thread which will stop making use of func.
napi_ref_threadsafe_function#
NAPI_EXTERN napi_status
napi_ref_threadsafe_function(node_api_basic_env env, napi_threadsafe_function func);
[in] env: The environment that the API is invoked under.[in] func: The thread-safe function to reference.
This API is used to indicate that the event loop running on the main thread should not exit until func has been destroyed. Similar to uv_ref it is also idempotent.
Neither does napi_unref_threadsafe_function mark the thread-safe functions as able to be destroyed nor does napi_ref_threadsafe_function prevent it from being destroyed. napi_acquire_threadsafe_function and napi_release_threadsafe_function are available for that purpose.
This API may only be called from the main thread.
napi_unref_threadsafe_function#
NAPI_EXTERN napi_status
napi_unref_threadsafe_function(node_api_basic_env env, napi_threadsafe_function func);
[in] env: The environment that the API is invoked under.[in] func: The thread-safe function to unreference.
This API is used to indicate that the event loop running on the main thread may exit before func is destroyed. Similar to uv_unref it is also idempotent.
This API may only be called from the main thread.
Miscellaneous utilities#
node_api_get_module_file_name#
NAPI_EXTERN napi_status
node_api_get_module_file_name(node_api_basic_env env, const char** result);
[in] env: The environment that the API is invoked under.[out] result: A URL containing the absolute path of the location from which the add-on was loaded. For a file on the local file system it will start withfile://. The string is null-terminated and owned byenvand must thus not be modified or freed.
result may be an empty string if the add-on loading process fails to establish the add-on's file name during loading.
OS#
Stability: 2 - Stable
The node:os module provides operating system-related utility methods and properties. It can be accessed using:
import os from 'node:os';const os = require('node:os');
os.EOL#
- Type:
<string>
The operating system-specific end-of-line marker.
\non POSIX\r\non Windows
os.availableParallelism()#
- Returns:
<integer>
Returns an estimate of the default amount of parallelism a program should use. Always returns a value greater than zero.
This function is a small wrapper about libuv's uv_available_parallelism().
os.arch()#
- Returns:
<string>
Returns the operating system CPU architecture for which the Node.js binary was compiled. Possible values are 'arm', 'arm64', 'ia32', 'loong64', 'mips', 'mipsel', 'ppc64', 'riscv64', 's390x', and 'x64'.
The return value is equivalent to process.arch.
os.constants#
- Type:
<Object>
Contains commonly used operating system-specific constants for error codes, process signals, and so on. The specific constants defined are described in OS constants.
os.cpus()#
- Returns:
<Object[]>
Returns an array of objects containing information about each logical CPU core. The array will be empty if no CPU information is available, such as if the /proc file system is unavailable.
The properties included on each object include:
model<string>speed<number>(in MHz)times<Object>user<number>The number of milliseconds the CPU has spent in user mode.nice<number>The number of milliseconds the CPU has spent in nice mode.sys<number>The number of milliseconds the CPU has spent in sys mode.idle<number>The number of milliseconds the CPU has spent in idle mode.irq<number>The number of milliseconds the CPU has spent in irq mode.
[
{
model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz',
speed: 2926,
times: {
user: 252020,
nice: 0,
sys: 30340,
idle: 1070356870,
irq: 0,
},
},
{
model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz',
speed: 2926,
times: {
user: 306960,
nice: 0,
sys: 26980,
idle: 1071569080,
irq: 0,
},
},
{
model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz',
speed: 2926,
times: {
user: 248450,
nice: 0,
sys: 21750,
idle: 1070919370,
irq: 0,
},
},
{
model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz',
speed: 2926,
times: {
user: 256880,
nice: 0,
sys: 19430,
idle: 1070905480,
irq: 20,
},
},
]
nice values are POSIX-only. On Windows, the nice values of all processors are always 0.
os.cpus().length should not be used to calculate the amount of parallelism available to an application. Use os.availableParallelism() for this purpose.
os.devNull#
- Type:
<string>
The platform-specific file path of the null device.
\\.\nulon Windows/dev/nullon POSIX
os.endianness()#
- Returns:
<string>
Returns a string identifying the endianness of the CPU for which the Node.js binary was compiled.
Possible values are 'BE' for big endian and 'LE' for little endian.
os.freemem()#
- Returns:
<integer>
Returns the amount of free system memory in bytes as an integer.
os.getPriority([pid])#
Returns the scheduling priority for the process specified by pid. If pid is not provided or is 0, the priority of the current process is returned.
os.homedir()#
- Returns:
<string>
Returns the string path of the current user's home directory.
On POSIX, it uses the $HOME environment variable if defined. Otherwise it uses the effective UID to look up the user's home directory.
On Windows, it uses the USERPROFILE environment variable if defined. Otherwise it uses the path to the profile directory of the current user.
os.hostname()#
- Returns:
<string>
Returns the host name of the operating system as a string.
os.loadavg()#
- Returns:
<number[]>
Returns an array containing the 1, 5, and 15 minute load averages.
The load average is a measure of system activity calculated by the operating system and expressed as a fractional number.
The load average is a Unix-specific concept. On Windows, the return value is always [0, 0, 0].
os.machine()#
- Returns:
<string>
Returns the machine type as a string, such as arm, arm64, aarch64, mips, mips64, ppc64, ppc64le, s390x, i386, i686, x86_64.
On POSIX systems, the machine type is determined by calling uname(3). On Windows, RtlGetVersion() is used, and if it is not available, GetVersionExW() will be used. See https://en.wikipedia.org/wiki/Uname#Examples for more information.
os.networkInterfaces()#
- Returns:
<Object>
Returns an object containing network interfaces that have been assigned a network address.
Each key on the returned object identifies a network interface. The associated value is an array of objects that each describe an assigned network address.
The properties available on the assigned network address object include:
address<string>The assigned IPv4 or IPv6 addressnetmask<string>The IPv4 or IPv6 network maskfamily<string>EitherIPv4orIPv6mac<string>The MAC address of the network interfaceinternal<boolean>trueif the network interface is a loopback or similar interface that is not remotely accessible; otherwisefalsescopeid<number>The numeric IPv6 scope ID (only specified whenfamilyisIPv6)cidr<string>The assigned IPv4 or IPv6 address with the routing prefix in CIDR notation. If thenetmaskis invalid, this property is set tonull.
{
lo: [
{
address: '127.0.0.1',
netmask: '255.0.0.0',
family: 'IPv4',
mac: '00:00:00:00:00:00',
internal: true,
cidr: '127.0.0.1/8'
},
{
address: '::1',
netmask: 'ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff',
family: 'IPv6',
mac: '00:00:00:00:00:00',
scopeid: 0,
internal: true,
cidr: '::1/128'
}
],
eth0: [
{
address: '192.168.1.108',
netmask: '255.255.255.0',
family: 'IPv4',
mac: '01:02:03:0a:0b:0c',
internal: false,
cidr: '192.168.1.108/24'
},
{
address: 'fe80::a00:27ff:fe4e:66a1',
netmask: 'ffff:ffff:ffff:ffff::',
family: 'IPv6',
mac: '01:02:03:0a:0b:0c',
scopeid: 1,
internal: false,
cidr: 'fe80::a00:27ff:fe4e:66a1/64'
}
]
}
os.platform()#
- Returns:
<string>
Returns a string identifying the operating system platform for which the Node.js binary was compiled. The value is set at compile time. Possible values are 'aix', 'darwin', 'freebsd','linux', 'openbsd', 'sunos', and 'win32'.
The return value is equivalent to process.platform.
The value 'android' may also be returned if Node.js is built on the Android operating system. Android support is experimental.
os.release()#
- Returns:
<string>
Returns the operating system as a string.
On POSIX systems, the operating system release is determined by calling uname(3). On Windows, GetVersionExW() is used. See https://en.wikipedia.org/wiki/Uname#Examples for more information.
os.setPriority([pid, ]priority)#
pid<integer>The process ID to set scheduling priority for. Default:0.priority<integer>The scheduling priority to assign to the process.
Attempts to set the scheduling priority for the process specified by pid. If pid is not provided or is 0, the process ID of the current process is used.
The priority input must be an integer between -20 (high priority) and 19 (low priority). Due to differences between Unix priority levels and Windows priority classes, priority is mapped to one of six priority constants in os.constants.priority. When retrieving a process priority level, this range mapping may cause the return value to be slightly different on Windows. To avoid confusion, set priority to one of the priority constants.
On Windows, setting priority to PRIORITY_HIGHEST requires elevated user privileges. Otherwise the set priority will be silently reduced to PRIORITY_HIGH.
os.tmpdir()#
- Returns:
<string>
Returns the operating system's default directory for temporary files as a string.
On Windows, the result can be overridden by TEMP and TMP environment variables, and TEMP takes precedence over TMP. If neither is set, it defaults to %SystemRoot%\temp or %windir%\temp.
On non-Windows platforms, TMPDIR, TMP and TEMP environment variables will be checked to override the result of this method, in the described order. If none of them is set, it defaults to /tmp.
Some operating system distributions would either configure TMPDIR (non-Windows) or TEMP and TMP (Windows) by default without additional configurations by the system administrators. The result of os.tmpdir() typically reflects the system preference unless it's explicitly overridden by the users.
os.totalmem()#
- Returns:
<integer>
Returns the total amount of system memory in bytes as an integer.
os.type()#
- Returns:
<string>
Returns the operating system name as returned by uname(3). For example, it returns 'Linux' on Linux, 'Darwin' on macOS, and 'Windows_NT' on Windows.
See https://en.wikipedia.org/wiki/Uname#Examples for additional information about the output of running uname(3) on various operating systems.
os.uptime()#
- Returns:
<integer>
Returns the system uptime in number of seconds.
os.userInfo([options])#
options<Object>encoding<string>Character encoding used to interpret resulting strings. Ifencodingis set to'buffer', theusername,shell, andhomedirvalues will beBufferinstances. Default:'utf8'.
- Returns:
<Object>
Returns information about the currently effective user. On POSIX platforms, this is typically a subset of the password file. The returned object includes the username, uid, gid, shell, and homedir. On Windows, the uid and gid fields are -1, and shell is null.
The value of homedir returned by os.userInfo() is provided by the operating system. This differs from the result of os.homedir(), which queries environment variables for the home directory before falling back to the operating system response.
Throws a SystemError if a user has no username or homedir.
os.version()#
- Returns:
<string>
Returns a string identifying the kernel version.
On POSIX systems, the operating system release is determined by calling uname(3). On Windows, RtlGetVersion() is used, and if it is not available, GetVersionExW() will be used. See https://en.wikipedia.org/wiki/Uname#Examples for more information.
OS constants#
The following constants are exported by os.constants.
Not all constants will be available on every operating system.
Signal constants#
The following signal constants are exported by os.constants.signals.
| Constant | Description |
|---|---|
SIGHUP | Sent to indicate when a controlling terminal is closed or a parent process exits. |
SIGINT | Sent to indicate when a user wishes to interrupt a process (Ctrl+C). |
SIGQUIT | Sent to indicate when a user wishes to terminate a process and perform a core dump. |
SIGILL | Sent to a process to notify that it has attempted to perform an illegal, malformed, unknown, or privileged instruction. |
SIGTRAP | Sent to a process when an exception has occurred. |
SIGABRT | Sent to a process to request that it abort. |
SIGIOT | Synonym for SIGABRT |
SIGBUS | Sent to a process to notify that it has caused a bus error. |
SIGFPE | Sent to a process to notify that it has performed an illegal arithmetic operation. |
SIGKILL | Sent to a process to terminate it immediately. |
SIGUSR1 SIGUSR2 | Sent to a process to identify user-defined conditions. |
SIGSEGV | Sent to a process to notify of a segmentation fault. |
SIGPIPE | Sent to a process when it has attempted to write to a disconnected pipe. |
SIGALRM | Sent to a process when a system timer elapses. |
SIGTERM | Sent to a process to request termination. |
SIGCHLD | Sent to a process when a child process terminates. |
SIGSTKFLT | Sent to a process to indicate a stack fault on a coprocessor. |
SIGCONT | Sent to instruct the operating system to continue a paused process. |
SIGSTOP | Sent to instruct the operating system to halt a process. |
SIGTSTP | Sent to a process to request it to stop. |
SIGBREAK | Sent to indicate when a user wishes to interrupt a process. |
SIGTTIN | Sent to a process when it reads from the TTY while in the background. |
SIGTTOU | Sent to a process when it writes to the TTY while in the background. |
SIGURG | Sent to a process when a socket has urgent data to read. |
SIGXCPU | Sent to a process when it has exceeded its limit on CPU usage. |
SIGXFSZ | Sent to a process when it grows a file larger than the maximum allowed. |
SIGVTALRM | Sent to a process when a virtual timer has elapsed. |
SIGPROF | Sent to a process when a system timer has elapsed. |
SIGWINCH | Sent to a process when the controlling terminal has changed its size. |
SIGIO | Sent to a process when I/O is available. |
SIGPOLL | Synonym for SIGIO |
SIGLOST | Sent to a process when a file lock has been lost. |
SIGPWR | Sent to a process to notify of a power failure. |
SIGINFO | Synonym for SIGPWR |
SIGSYS | Sent to a process to notify of a bad argument. |
SIGUNUSED | Synonym for SIGSYS |
Error constants#
The following error constants are exported by os.constants.errno.
POSIX error constants#
| Constant | Description |
|---|---|
E2BIG | Indicates that the list of arguments is longer than expected. |
EACCES | Indicates that the operation did not have sufficient permissions. |
EADDRINUSE | Indicates that the network address is already in use. |
EADDRNOTAVAIL | Indicates that the network address is currently unavailable for use. |
EAFNOSUPPORT | Indicates that the network address family is not supported. |
EAGAIN | Indicates that there is no data available and to try the operation again later. |
EALREADY | Indicates that the socket already has a pending connection in progress. |
EBADF | Indicates that a file descriptor is not valid. |
EBADMSG | Indicates an invalid data message. |
EBUSY | Indicates that a device or resource is busy. |
ECANCELED | Indicates that an operation was canceled. |
ECHILD | Indicates that there are no child processes. |
ECONNABORTED | Indicates that the network connection has been aborted. |
ECONNREFUSED | Indicates that the network connection has been refused. |
ECONNRESET | Indicates that the network connection has been reset. |
EDEADLK | Indicates that a resource deadlock has been avoided. |
EDESTADDRREQ | Indicates that a destination address is required. |
EDOM | Indicates that an argument is out of the domain of the function. |
EDQUOT | Indicates that the disk quota has been exceeded. |
EEXIST | Indicates that the file already exists. |
EFAULT | Indicates an invalid pointer address. |
EFBIG | Indicates that the file is too large. |
EHOSTUNREACH | Indicates that the host is unreachable. |
EIDRM | Indicates that the identifier has been removed. |
EILSEQ | Indicates an illegal byte sequence. |
EINPROGRESS | Indicates that an operation is already in progress. |
EINTR | Indicates that a function call was interrupted. |
EINVAL | Indicates that an invalid argument was provided. |
EIO | Indicates an otherwise unspecified I/O error. |
EISCONN | Indicates that the socket is connected. |
EISDIR | Indicates that the path is a directory. |
ELOOP | Indicates too many levels of symbolic links in a path. |
EMFILE | Indicates that there are too many open files. |
EMLINK | Indicates that there are too many hard links to a file. |
EMSGSIZE | Indicates that the provided message is too long. |
EMULTIHOP | Indicates that a multihop was attempted. |
ENAMETOOLONG | Indicates that the filename is too long. |
ENETDOWN | Indicates that the network is down. |
ENETRESET | Indicates that the connection has been aborted by the network. |
ENETUNREACH | Indicates that the network is unreachable. |
ENFILE | Indicates too many open files in the system. |
ENOBUFS | Indicates that no buffer space is available. |
ENODATA | Indicates that no message is available on the stream head read queue. |
ENODEV | Indicates that there is no such device. |
ENOENT | Indicates that there is no such file or directory. |
ENOEXEC | Indicates an exec format error. |
ENOLCK | Indicates that there are no locks available. |
ENOLINK | Indications that a link has been severed. |
ENOMEM | Indicates that there is not enough space. |
ENOMSG | Indicates that there is no message of the desired type. |
ENOPROTOOPT | Indicates that a given protocol is not available. |
ENOSPC | Indicates that there is no space available on the device. |
ENOSR | Indicates that there are no stream resources available. |
ENOSTR | Indicates that a given resource is not a stream. |
ENOSYS | Indicates that a function has not been implemented. |
ENOTCONN | Indicates that the socket is not connected. |
ENOTDIR | Indicates that the path is not a directory. |
ENOTEMPTY | Indicates that the directory is not empty. |
ENOTSOCK | Indicates that the given item is not a socket. |
ENOTSUP | Indicates that a given operation is not supported. |
ENOTTY | Indicates an inappropriate I/O control operation. |
ENXIO | Indicates no such device or address. |
EOPNOTSUPP | Indicates that an operation is not supported on the socket. Although ENOTSUP and EOPNOTSUPP have the same value on Linux, according to POSIX.1 these error values should be distinct.) |
EOVERFLOW | Indicates that a value is too large to be stored in a given data type. |
EPERM | Indicates that the operation is not permitted. |
EPIPE | Indicates a broken pipe. |
EPROTO | Indicates a protocol error. |
EPROTONOSUPPORT | Indicates that a protocol is not supported. |
EPROTOTYPE | Indicates the wrong type of protocol for a socket. |
ERANGE | Indicates that the results are too large. |
EROFS | Indicates that the file system is read only. |
ESPIPE | Indicates an invalid seek operation. |
ESRCH | Indicates that there is no such process. |
ESTALE | Indicates that the file handle is stale. |
ETIME | Indicates an expired timer. |
ETIMEDOUT | Indicates that the connection timed out. |
ETXTBSY | Indicates that a text file is busy. |
EWOULDBLOCK | Indicates that the operation would block. |
EXDEV | Indicates an improper link. |
Windows-specific error constants#
The following error codes are specific to the Windows operating system.
| Constant | Description |
|---|---|
WSAEINTR | Indicates an interrupted function call. |
WSAEBADF | Indicates an invalid file handle. |
WSAEACCES | Indicates insufficient permissions to complete the operation. |
WSAEFAULT | Indicates an invalid pointer address. |
WSAEINVAL | Indicates that an invalid argument was passed. |
WSAEMFILE | Indicates that there are too many open files. |
WSAEWOULDBLOCK | Indicates that a resource is temporarily unavailable. |
WSAEINPROGRESS | Indicates that an operation is currently in progress. |
WSAEALREADY | Indicates that an operation is already in progress. |
WSAENOTSOCK | Indicates that the resource is not a socket. |
WSAEDESTADDRREQ | Indicates that a destination address is required. |
WSAEMSGSIZE | Indicates that the message size is too long. |
WSAEPROTOTYPE | Indicates the wrong protocol type for the socket. |
WSAENOPROTOOPT | Indicates a bad protocol option. |
WSAEPROTONOSUPPORT | Indicates that the protocol is not supported. |
WSAESOCKTNOSUPPORT | Indicates that the socket type is not supported. |
WSAEOPNOTSUPP | Indicates that the operation is not supported. |
WSAEPFNOSUPPORT | Indicates that the protocol family is not supported. |
WSAEAFNOSUPPORT | Indicates that the address family is not supported. |
WSAEADDRINUSE | Indicates that the network address is already in use. |
WSAEADDRNOTAVAIL | Indicates that the network address is not available. |
WSAENETDOWN | Indicates that the network is down. |
WSAENETUNREACH | Indicates that the network is unreachable. |
WSAENETRESET | Indicates that the network connection has been reset. |
WSAECONNABORTED | Indicates that the connection has been aborted. |
WSAECONNRESET | Indicates that the connection has been reset by the peer. |
WSAENOBUFS | Indicates that there is no buffer space available. |
WSAEISCONN | Indicates that the socket is already connected. |
WSAENOTCONN | Indicates that the socket is not connected. |
WSAESHUTDOWN | Indicates that data cannot be sent after the socket has been shutdown. |
WSAETOOMANYREFS | Indicates that there are too many references. |
WSAETIMEDOUT | Indicates that the connection has timed out. |
WSAECONNREFUSED | Indicates that the connection has been refused. |
WSAELOOP | Indicates that a name cannot be translated. |
WSAENAMETOOLONG | Indicates that a name was too long. |
WSAEHOSTDOWN | Indicates that a network host is down. |
WSAEHOSTUNREACH | Indicates that there is no route to a network host. |
WSAENOTEMPTY | Indicates that the directory is not empty. |
WSAEPROCLIM | Indicates that there are too many processes. |
WSAEUSERS | Indicates that the user quota has been exceeded. |
WSAEDQUOT | Indicates that the disk quota has been exceeded. |
WSAESTALE | Indicates a stale file handle reference. |
WSAEREMOTE | Indicates that the item is remote. |
WSASYSNOTREADY | Indicates that the network subsystem is not ready. |
WSAVERNOTSUPPORTED | Indicates that the winsock.dll version is out of range. |
WSANOTINITIALISED | Indicates that successful WSAStartup has not yet been performed. |
WSAEDISCON | Indicates that a graceful shutdown is in progress. |
WSAENOMORE | Indicates that there are no more results. |
WSAECANCELLED | Indicates that an operation has been canceled. |
WSAEINVALIDPROCTABLE | Indicates that the procedure call table is invalid. |
WSAEINVALIDPROVIDER | Indicates an invalid service provider. |
WSAEPROVIDERFAILEDINIT | Indicates that the service provider failed to initialized. |
WSASYSCALLFAILURE | Indicates a system call failure. |
WSASERVICE_NOT_FOUND | Indicates that a service was not found. |
WSATYPE_NOT_FOUND | Indicates that a class type was not found. |
WSA_E_NO_MORE | Indicates that there are no more results. |
WSA_E_CANCELLED | Indicates that the call was canceled. |
WSAEREFUSED | Indicates that a database query was refused. |
dlopen constants#
If available on the operating system, the following constants are exported in os.constants.dlopen. See dlopen(3) for detailed information.
| Constant | Description |
|---|---|
RTLD_LAZY | Perform lazy binding. Node.js sets this flag by default. |
RTLD_NOW | Resolve all undefined symbols in the library before dlopen(3) returns. |
RTLD_GLOBAL | Symbols defined by the library will be made available for symbol resolution of subsequently loaded libraries. |
RTLD_LOCAL | The converse of RTLD_GLOBAL. This is the default behavior if neither flag is specified. |
RTLD_DEEPBIND | Make a self-contained library use its own symbols in preference to symbols from previously loaded libraries. |
Priority constants#
The following process scheduling constants are exported by os.constants.priority.
| Constant | Description |
|---|---|
PRIORITY_LOW | The lowest process scheduling priority. This corresponds to IDLE_PRIORITY_CLASS on Windows, and a nice value of 19 on all other platforms. |
PRIORITY_BELOW_NORMAL | The process scheduling priority above PRIORITY_LOW and below PRIORITY_NORMAL. This corresponds to BELOW_NORMAL_PRIORITY_CLASS on Windows, and a nice value of 10 on all other platforms. |
PRIORITY_NORMAL | The default process scheduling priority. This corresponds to NORMAL_PRIORITY_CLASS on Windows, and a nice value of 0 on all other platforms. |
PRIORITY_ABOVE_NORMAL | The process scheduling priority above PRIORITY_NORMAL and below PRIORITY_HIGH. This corresponds to ABOVE_NORMAL_PRIORITY_CLASS on Windows, and a nice value of -7 on all other platforms. |
PRIORITY_HIGH | The process scheduling priority above PRIORITY_ABOVE_NORMAL and below PRIORITY_HIGHEST. This corresponds to HIGH_PRIORITY_CLASS on Windows, and a nice value of -14 on all other platforms. |
PRIORITY_HIGHEST | The highest process scheduling priority. This corresponds to REALTIME_PRIORITY_CLASS on Windows, and a nice value of -20 on all other platforms. |
libuv constants#
| Constant | Description |
|---|---|
UV_UDP_REUSEADDR |
Path#
Stability: 2 - Stable
The node:path module provides utilities for working with file and directory paths. It can be accessed using:
const path = require('node:path');import path from 'node:path';
Windows vs. POSIX#
The default operation of the node:path module varies based on the operating system on which a Node.js application is running. Specifically, when running on a Windows operating system, the node:path module will assume that Windows-style paths are being used.
So using path.basename() might yield different results on POSIX and Windows:
On POSIX:
path.basename('C:\\temp\\myfile.html');
// Returns: 'C:\\temp\\myfile.html'
On Windows:
path.basename('C:\\temp\\myfile.html');
// Returns: 'myfile.html'
To achieve consistent results when working with Windows file paths on any operating system, use path.win32:
On POSIX and Windows:
path.win32.basename('C:\\temp\\myfile.html');
// Returns: 'myfile.html'
To achieve consistent results when working with POSIX file paths on any operating system, use path.posix:
On POSIX and Windows:
path.posix.basename('/tmp/myfile.html');
// Returns: 'myfile.html'
On Windows Node.js follows the concept of per-drive working directory. This behavior can be observed when using a drive path without a backslash. For example, path.resolve('C:\\') can potentially return a different result than path.resolve('C:'). For more information, see this MSDN page.
path.basename(path[, suffix])#
The path.basename() method returns the last portion of a path, similar to the Unix basename command. Trailing directory separators are ignored.
path.basename('/foo/bar/baz/asdf/quux.html');
// Returns: 'quux.html'
path.basename('/foo/bar/baz/asdf/quux.html', '.html');
// Returns: 'quux'
Although Windows usually treats file names, including file extensions, in a case-insensitive manner, this function does not. For example, C:\\foo.html and C:\\foo.HTML refer to the same file, but basename treats the extension as a case-sensitive string:
path.win32.basename('C:\\foo.html', '.html');
// Returns: 'foo'
path.win32.basename('C:\\foo.HTML', '.html');
// Returns: 'foo.HTML'
A TypeError is thrown if path is not a string or if suffix is given and is not a string.
path.delimiter#
- Type:
<string>
Provides the platform-specific path delimiter:
;for Windows:for POSIX
For example, on POSIX:
console.log(process.env.PATH);
// Prints: '/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin'
process.env.PATH.split(path.delimiter);
// Returns: ['/usr/bin', '/bin', '/usr/sbin', '/sbin', '/usr/local/bin']
On Windows:
console.log(process.env.PATH);
// Prints: 'C:\Windows\system32;C:\Windows;C:\Program Files\node\'
process.env.PATH.split(path.delimiter);
// Returns ['C:\\Windows\\system32', 'C:\\Windows', 'C:\\Program Files\\node\\']
path.dirname(path)#
The path.dirname() method returns the directory name of a path, similar to the Unix dirname command. Trailing directory separators are ignored, see path.sep.
path.dirname('/foo/bar/baz/asdf/quux');
// Returns: '/foo/bar/baz/asdf'
A TypeError is thrown if path is not a string.
path.extname(path)#
The path.extname() method returns the extension of the path, from the last occurrence of the . (period) character to end of string in the last portion of the path. If there is no . in the last portion of the path, or if there are no . characters other than the first character of the basename of path (see path.basename()) , an empty string is returned.
path.extname('index.html');
// Returns: '.html'
path.extname('index.coffee.md');
// Returns: '.md'
path.extname('index.');
// Returns: '.'
path.extname('index');
// Returns: ''
path.extname('.index');
// Returns: ''
path.extname('.index.md');
// Returns: '.md'
A TypeError is thrown if path is not a string.
path.format(pathObject)#
The path.format() method returns a path string from an object. This is the opposite of path.parse().
When providing properties to the pathObject remember that there are combinations where one property has priority over another:
pathObject.rootis ignored ifpathObject.diris providedpathObject.extandpathObject.nameare ignored ifpathObject.baseexists
For example, on POSIX:
// If `dir`, `root` and `base` are provided,
// `${dir}${path.sep}${base}`
// will be returned. `root` is ignored.
path.format({
root: '/ignored',
dir: '/home/user/dir',
base: 'file.txt',
});
// Returns: '/home/user/dir/file.txt'
// `root` will be used if `dir` is not specified.
// If only `root` is provided or `dir` is equal to `root` then the
// platform separator will not be included. `ext` will be ignored.
path.format({
root: '/',
base: 'file.txt',
ext: 'ignored',
});
// Returns: '/file.txt'
// `name` + `ext` will be used if `base` is not specified.
path.format({
root: '/',
name: 'file',
ext: '.txt',
});
// Returns: '/file.txt'
// The dot will be added if it is not specified in `ext`.
path.format({
root: '/',
name: 'file',
ext: 'txt',
});
// Returns: '/file.txt'
On Windows:
path.format({
dir: 'C:\\path\\dir',
base: 'file.txt',
});
// Returns: 'C:\\path\\dir\\file.txt'
path.matchesGlob(path, pattern)#
path<string>The path to glob-match against.pattern<string>The glob to check the path against.- Returns:
<boolean>Whether or not thepathmatched thepattern.
The path.matchesGlob() method determines if path matches the pattern.
For example:
path.matchesGlob('/foo/bar', '/foo/*'); // true
path.matchesGlob('/foo/bar*', 'foo/bird'); // false
A TypeError is thrown if path or pattern are not strings.
path.isAbsolute(path)#
The path.isAbsolute() method determines if the literal path is absolute. Therefore, it’s not safe for mitigating path traversals.
If the given path is a zero-length string, false will be returned.
For example, on POSIX:
path.isAbsolute('/foo/bar'); // true
path.isAbsolute('/baz/..'); // true
path.isAbsolute('/baz/../..'); // true
path.isAbsolute('qux/'); // false
path.isAbsolute('.'); // false
On Windows:
path.isAbsolute('//server'); // true
path.isAbsolute('\\\\server'); // true
path.isAbsolute('C:/foo/..'); // true
path.isAbsolute('C:\\foo\\..'); // true
path.isAbsolute('bar\\baz'); // false
path.isAbsolute('bar/baz'); // false
path.isAbsolute('.'); // false
A TypeError is thrown if path is not a string.
path.join([...paths])#
The path.join() method joins all given path segments together using the platform-specific separator as a delimiter, then normalizes the resulting path.
Zero-length path segments are ignored. If the joined path string is a zero-length string then '.' will be returned, representing the current working directory.
path.join('/foo', 'bar', 'baz/asdf', 'quux', '..');
// Returns: '/foo/bar/baz/asdf'
path.join('foo', {}, 'bar');
// Throws 'TypeError: Path must be a string. Received {}'
A TypeError is thrown if any of the path segments is not a string.
path.normalize(path)#
The path.normalize() method normalizes the given path, resolving '..' and '.' segments.
When multiple, sequential path segment separation characters are found (e.g. / on POSIX and either \ or / on Windows), they are replaced by a single instance of the platform-specific path segment separator (/ on POSIX and \ on Windows). Trailing separators are preserved.
If the path is a zero-length string, '.' is returned, representing the current working directory.
On POSIX, the types of normalization applied by this function do not strictly adhere to the POSIX specification. For example, this function will replace two leading forward slashes with a single slash as if it was a regular absolute path, whereas a few POSIX systems assign special meaning to paths beginning with exactly two forward slashes. Similarly, other substitutions performed by this function, such as removing .. segments, may change how the underlying system resolves the path.
For example, on POSIX:
path.normalize('/foo/bar//baz/asdf/quux/..');
// Returns: '/foo/bar/baz/asdf'
On Windows:
path.normalize('C:\\temp\\\\foo\\bar\\..\\');
// Returns: 'C:\\temp\\foo\\'
Since Windows recognizes multiple path separators, both separators will be replaced by instances of the Windows preferred separator (\):
path.win32.normalize('C:////temp\\\\/\\/\\/foo/bar');
// Returns: 'C:\\temp\\foo\\bar'
A TypeError is thrown if path is not a string.
path.parse(path)#
The path.parse() method returns an object whose properties represent significant elements of the path. Trailing directory separators are ignored, see path.sep.
The returned object will have the following properties:
For example, on POSIX:
path.parse('/home/user/dir/file.txt');
// Returns:
// { root: '/',
// dir: '/home/user/dir',
// base: 'file.txt',
// ext: '.txt',
// name: 'file' }
┌─────────────────────┬────────────┐
│ dir │ base │
├──────┬ ├──────┬─────┤
│ root │ │ name │ ext │
" / home/user/dir / file .txt "
└──────┴──────────────┴──────┴─────┘
(All spaces in the "" line should be ignored. They are purely for formatting.)
On Windows:
path.parse('C:\\path\\dir\\file.txt');
// Returns:
// { root: 'C:\\',
// dir: 'C:\\path\\dir',
// base: 'file.txt',
// ext: '.txt',
// name: 'file' }
┌─────────────────────┬────────────┐
│ dir │ base │
├──────┬ ├──────┬─────┤
│ root │ │ name │ ext │
" C:\ path\dir \ file .txt "
└──────┴──────────────┴──────┴─────┘
(All spaces in the "" line should be ignored. They are purely for formatting.)
A TypeError is thrown if path is not a string.
path.posix#
- Type:
<Object>
The path.posix property provides access to POSIX specific implementations of the path methods.
The API is accessible via require('node:path').posix or require('node:path/posix').
path.relative(from, to)#
The path.relative() method returns the relative path from from to to based on the current working directory. If from and to each resolve to the same path (after calling path.resolve() on each), a zero-length string is returned.
If a zero-length string is passed as from or to, the current working directory will be used instead of the zero-length strings.
For example, on POSIX:
path.relative('/data/orandea/test/aaa', '/data/orandea/impl/bbb');
// Returns: '../../impl/bbb'
On Windows:
path.relative('C:\\orandea\\test\\aaa', 'C:\\orandea\\impl\\bbb');
// Returns: '..\\..\\impl\\bbb'
A TypeError is thrown if either from or to is not a string.
path.resolve([...paths])#
The path.resolve() method resolves a sequence of paths or path segments into an absolute path.
The given sequence of paths is processed from right to left, with each subsequent path prepended until an absolute path is constructed. For instance, given the sequence of path segments: /foo, /bar, baz, calling path.resolve('/foo', '/bar', 'baz') would return /bar/baz because 'baz' is not an absolute path but '/bar' + '/' + 'baz' is.
If, after processing all given path segments, an absolute path has not yet been generated, the current working directory is used.
The resulting path is normalized and trailing slashes are removed unless the path is resolved to the root directory.
Zero-length path segments are ignored.
If no path segments are passed, path.resolve() will return the absolute path of the current working directory.
path.resolve('/foo/bar', './baz');
// Returns: '/foo/bar/baz'
path.resolve('/foo/bar', '/tmp/file/');
// Returns: '/tmp/file'
path.resolve('wwwroot', 'static_files/png/', '../gif/image.gif');
// If the current working directory is /home/myself/node,
// this returns '/home/myself/node/wwwroot/static_files/gif/image.gif'
A TypeError is thrown if any of the arguments is not a string.
path.sep#
- Type:
<string>
Provides the platform-specific path segment separator:
\on Windows/on POSIX
For example, on POSIX:
'foo/bar/baz'.split(path.sep);
// Returns: ['foo', 'bar', 'baz']
On Windows:
'foo\\bar\\baz'.split(path.sep);
// Returns: ['foo', 'bar', 'baz']
On Windows, both the forward slash (/) and backward slash (\) are accepted as path segment separators; however, the path methods only add backward slashes (\).
path.toNamespacedPath(path)#
On Windows systems only, returns an equivalent namespace-prefixed path for the given path. If path is not a string, path will be returned without modifications.
This method is meaningful only on Windows systems. On POSIX systems, the method is non-operational and always returns path without modifications.
path.win32#
- Type:
<Object>
The path.win32 property provides access to Windows-specific implementations of the path methods.
The API is accessible via require('node:path').win32 or require('node:path/win32').
Performance measurement APIs#
Stability: 2 - Stable
This module provides an implementation of a subset of the W3C Web Performance APIs as well as additional APIs for Node.js-specific performance measurements.
Node.js supports the following Web Performance APIs:
import { performance, PerformanceObserver } from 'node:perf_hooks'; const obs = new PerformanceObserver((items) => { console.log(items.getEntries()[0].duration); performance.clearMarks(); }); obs.observe({ type: 'measure' }); performance.measure('Start to Now'); performance.mark('A'); doSomeLongRunningProcess(() => { performance.measure('A to Now', 'A'); performance.mark('B'); performance.measure('A to B', 'A', 'B'); });const { PerformanceObserver, performance } = require('node:perf_hooks'); const obs = new PerformanceObserver((items) => { console.log(items.getEntries()[0].duration); }); obs.observe({ type: 'measure' }); performance.measure('Start to Now'); performance.mark('A'); (async function doSomeLongRunningProcess() { await new Promise((r) => setTimeout(r, 5000)); performance.measure('A to Now', 'A'); performance.mark('B'); performance.measure('A to B', 'A', 'B'); })();
perf_hooks.performance#
An object that can be used to collect performance metrics from the current Node.js instance. It is similar to window.performance in browsers.
performance.clearMarks([name])#
name<string>
If name is not provided, removes all PerformanceMark objects from the Performance Timeline. If name is provided, removes only the named mark.
performance.clearMeasures([name])#
name<string>
If name is not provided, removes all PerformanceMeasure objects from the Performance Timeline. If name is provided, removes only the named measure.
performance.clearResourceTimings([name])#
name<string>
If name is not provided, removes all PerformanceResourceTiming objects from the Resource Timeline. If name is provided, removes only the named resource.
performance.eventLoopUtilization([utilization1[, utilization2]])#
utilization1<Object>The result of a previous call toeventLoopUtilization().utilization2<Object>The result of a previous call toeventLoopUtilization()prior toutilization1.- Returns:
<Object>
This is an alias of perf_hooks.eventLoopUtilization().
This property is an extension by Node.js. It is not available in Web browsers.
performance.getEntries()#
- Returns:
<PerformanceEntry[]>
Returns a list of PerformanceEntry objects in chronological order with respect to performanceEntry.startTime. If you are only interested in performance entries of certain types or that have certain names, see performance.getEntriesByType() and performance.getEntriesByName().
performance.getEntriesByName(name[, type])#
name<string>type<string>- Returns:
<PerformanceEntry[]>
Returns a list of PerformanceEntry objects in chronological order with respect to performanceEntry.startTime whose performanceEntry.name is equal to name, and optionally, whose performanceEntry.entryType is equal to type.
performance.getEntriesByType(type)#
type<string>- Returns:
<PerformanceEntry[]>
Returns a list of PerformanceEntry objects in chronological order with respect to performanceEntry.startTime whose performanceEntry.entryType is equal to type.
performance.mark(name[, options])#
Creates a new PerformanceMark entry in the Performance Timeline. A PerformanceMark is a subclass of PerformanceEntry whose performanceEntry.entryType is always 'mark', and whose performanceEntry.duration is always 0. Performance marks are used to mark specific significant moments in the Performance Timeline.
The created PerformanceMark entry is put in the global Performance Timeline and can be queried with performance.getEntries, performance.getEntriesByName, and performance.getEntriesByType. When the observation is performed, the entries should be cleared from the global Performance Timeline manually with performance.clearMarks.
performance.markResourceTiming(timingInfo, requestedUrl, initiatorType, global, cacheMode, bodyInfo, responseStatus[, deliveryType])#
timingInfo<Object>Fetch Timing InforequestedUrl<string>The resource urlinitiatorType<string>The initiator name, e.g: 'fetch'global<Object>cacheMode<string>The cache mode must be an empty string ('') or 'local'bodyInfo<Object>Fetch Response Body InforesponseStatus<number>The response's status codedeliveryType<string>The delivery type. Default:''.
This property is an extension by Node.js. It is not available in Web browsers.
Creates a new PerformanceResourceTiming entry in the Resource Timeline. A PerformanceResourceTiming is a subclass of PerformanceEntry whose performanceEntry.entryType is always 'resource'. Performance resources are used to mark moments in the Resource Timeline.
The created PerformanceMark entry is put in the global Resource Timeline and can be queried with performance.getEntries, performance.getEntriesByName, and performance.getEntriesByType. When the observation is performed, the entries should be cleared from the global Performance Timeline manually with performance.clearResourceTimings.
performance.measure(name[, startMarkOrOptions[, endMark]])#
name<string>startMarkOrOptions<string>|<Object>Optional.detail<any>Additional optional detail to include with the measure.duration<number>Duration between start and end times.end<number>|<string>Timestamp to be used as the end time, or a string identifying a previously recorded mark.start<number>|<string>Timestamp to be used as the start time, or a string identifying a previously recorded mark.
endMark<string>Optional. Must be omitted ifstartMarkOrOptionsis an<Object>.
Creates a new PerformanceMeasure entry in the Performance Timeline. A PerformanceMeasure is a subclass of PerformanceEntry whose performanceEntry.entryType is always 'measure', and whose performanceEntry.duration measures the number of milliseconds elapsed since startMark and endMark.
The startMark argument may identify any existing PerformanceMark in the Performance Timeline, or may identify any of the timestamp properties provided by the PerformanceNodeTiming class. If the named startMark does not exist, an error is thrown.
The optional endMark argument must identify any existing PerformanceMark in the Performance Timeline or any of the timestamp properties provided by the PerformanceNodeTiming class. endMark will be performance.now() if no parameter is passed, otherwise if the named endMark does not exist, an error will be thrown.
The created PerformanceMeasure entry is put in the global Performance Timeline and can be queried with performance.getEntries, performance.getEntriesByName, and performance.getEntriesByType. When the observation is performed, the entries should be cleared from the global Performance Timeline manually with performance.clearMeasures.
performance.nodeTiming#
- Type:
<PerformanceNodeTiming>
This property is an extension by Node.js. It is not available in Web browsers.
An instance of the PerformanceNodeTiming class that provides performance metrics for specific Node.js operational milestones.
performance.now()#
- Returns:
<number>
Returns the current high resolution millisecond timestamp, where 0 represents the start of the current node process.
performance.setResourceTimingBufferSize(maxSize)#
Sets the global performance resource timing buffer size to the specified number of "resource" type performance entry objects.
By default the max buffer size is set to 250.
performance.timeOrigin#
- Type:
<number>
The timeOrigin specifies the high resolution millisecond timestamp at which the current node process began, measured in Unix time.
performance.timerify(fn[, options])#
fn<Function>options<Object>histogram<RecordableHistogram>A histogram object created usingperf_hooks.createHistogram()that will record runtime durations in nanoseconds.
This is an alias of perf_hooks.timerify().
This property is an extension by Node.js. It is not available in Web browsers.
performance.toJSON()#
An object which is JSON representation of the performance object. It is similar to window.performance.toJSON in browsers.
Event: 'resourcetimingbufferfull'#
The 'resourcetimingbufferfull' event is fired when the global performance resource timing buffer is full. Adjust resource timing buffer size with performance.setResourceTimingBufferSize() or clear the buffer with performance.clearResourceTimings() in the event listener to allow more entries to be added to the performance timeline buffer.
Class: PerformanceEntry#
The constructor of this class is not exposed to users directly.
performanceEntry.duration#
- Type:
<number>
The total number of milliseconds elapsed for this entry. This value will not be meaningful for all Performance Entry types.
performanceEntry.entryType#
- Type:
<string>
The type of the performance entry. It may be one of:
'dns'(Node.js only)'function'(Node.js only)'gc'(Node.js only)'http2'(Node.js only)'http'(Node.js only)'mark'(available on the Web)'measure'(available on the Web)'net'(Node.js only)'node'(Node.js only)'resource'(available on the Web)
performanceEntry.name#
- Type:
<string>
The name of the performance entry.
performanceEntry.startTime#
- Type:
<number>
The high resolution millisecond timestamp marking the starting time of the Performance Entry.
Class: PerformanceMark#
- Extends:
<PerformanceEntry>
Exposes marks created via the Performance.mark() method.
performanceMark.detail#
- Type:
<any>
Additional detail specified when creating with Performance.mark() method.
Class: PerformanceMeasure#
- Extends:
<PerformanceEntry>
Exposes measures created via the Performance.measure() method.
The constructor of this class is not exposed to users directly.
performanceMeasure.detail#
- Type:
<any>
Additional detail specified when creating with Performance.measure() method.
Class: PerformanceNodeEntry#
- Extends:
<PerformanceEntry>
This class is an extension by Node.js. It is not available in Web browsers.
Provides detailed Node.js timing data.
The constructor of this class is not exposed to users directly.
performanceNodeEntry.detail#
- Type:
<any>
Additional detail specific to the entryType.
performanceNodeEntry.flags#
Stability: 0 - Deprecated: Use performanceNodeEntry.detail instead.
- Type:
<number>
When performanceEntry.entryType is equal to 'gc', the performance.flags property contains additional information about garbage collection operation. The value may be one of:
perf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_NOperf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_CONSTRUCT_RETAINEDperf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_FORCEDperf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_SYNCHRONOUS_PHANTOM_PROCESSINGperf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_ALL_AVAILABLE_GARBAGEperf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_ALL_EXTERNAL_MEMORYperf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_SCHEDULE_IDLE
performanceNodeEntry.kind#
Stability: 0 - Deprecated: Use performanceNodeEntry.detail instead.
- Type:
<number>
When performanceEntry.entryType is equal to 'gc', the performance.kind property identifies the type of garbage collection operation that occurred. The value may be one of:
perf_hooks.constants.NODE_PERFORMANCE_GC_MAJORperf_hooks.constants.NODE_PERFORMANCE_GC_MINORperf_hooks.constants.NODE_PERFORMANCE_GC_INCREMENTALperf_hooks.constants.NODE_PERFORMANCE_GC_WEAKCB
Garbage Collection ('gc') Details#
When performanceEntry.type is equal to 'gc', the performanceNodeEntry.detail property will be an <Object> with two properties:
kind<number>One of:perf_hooks.constants.NODE_PERFORMANCE_GC_MAJORperf_hooks.constants.NODE_PERFORMANCE_GC_MINORperf_hooks.constants.NODE_PERFORMANCE_GC_INCREMENTALperf_hooks.constants.NODE_PERFORMANCE_GC_WEAKCB
flags<number>One of:perf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_NOperf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_CONSTRUCT_RETAINEDperf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_FORCEDperf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_SYNCHRONOUS_PHANTOM_PROCESSINGperf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_ALL_AVAILABLE_GARBAGEperf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_ALL_EXTERNAL_MEMORYperf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_SCHEDULE_IDLE
HTTP ('http') Details#
When performanceEntry.type is equal to 'http', the performanceNodeEntry.detail property will be an <Object> containing additional information.
If performanceEntry.name is equal to HttpClient, the detail will contain the following properties: req, res. And the req property will be an <Object> containing method, url, headers, the res property will be an <Object> containing statusCode, statusMessage, headers.
If performanceEntry.name is equal to HttpRequest, the detail will contain the following properties: req, res. And the req property will be an <Object> containing method, url, headers, the res property will be an <Object> containing statusCode, statusMessage, headers.
This could add additional memory overhead and should only be used for diagnostic purposes, not left turned on in production by default.
HTTP/2 ('http2') Details#
When performanceEntry.type is equal to 'http2', the performanceNodeEntry.detail property will be an <Object> containing additional performance information.
If performanceEntry.name is equal to Http2Stream, the detail will contain the following properties:
bytesRead<number>The number ofDATAframe bytes received for thisHttp2Stream.bytesWritten<number>The number ofDATAframe bytes sent for thisHttp2Stream.id<number>The identifier of the associatedHttp2StreamtimeToFirstByte<number>The number of milliseconds elapsed between thePerformanceEntrystartTimeand the reception of the firstDATAframe.timeToFirstByteSent<number>The number of milliseconds elapsed between thePerformanceEntrystartTimeand sending of the firstDATAframe.timeToFirstHeader<number>The number of milliseconds elapsed between thePerformanceEntrystartTimeand the reception of the first header.
If performanceEntry.name is equal to Http2Session, the detail will contain the following properties:
bytesRead<number>The number of bytes received for thisHttp2Session.bytesWritten<number>The number of bytes sent for thisHttp2Session.framesReceived<number>The number of HTTP/2 frames received by theHttp2Session.framesSent<number>The number of HTTP/2 frames sent by theHttp2Session.maxConcurrentStreams<number>The maximum number of streams concurrently open during the lifetime of theHttp2Session.pingRTT<number>The number of milliseconds elapsed since the transmission of aPINGframe and the reception of its acknowledgment. Only present if aPINGframe has been sent on theHttp2Session.streamAverageDuration<number>The average duration (in milliseconds) for allHttp2Streaminstances.streamCount<number>The number ofHttp2Streaminstances processed by theHttp2Session.type<string>Either'server'or'client'to identify the type ofHttp2Session.
Timerify ('function') Details#
When performanceEntry.type is equal to 'function', the performanceNodeEntry.detail property will be an <Array> listing the input arguments to the timed function.
Net ('net') Details#
When performanceEntry.type is equal to 'net', the performanceNodeEntry.detail property will be an <Object> containing additional information.
If performanceEntry.name is equal to connect, the detail will contain the following properties: host, port.
DNS ('dns') Details#
When performanceEntry.type is equal to 'dns', the performanceNodeEntry.detail property will be an <Object> containing additional information.
If performanceEntry.name is equal to lookup, the detail will contain the following properties: hostname, family, hints, verbatim, addresses.
If performanceEntry.name is equal to lookupService, the detail will contain the following properties: host, port, hostname, service.
If performanceEntry.name is equal to queryxxx or getHostByAddr, the detail will contain the following properties: host, ttl, result. The value of result is same as the result of queryxxx or getHostByAddr.
Class: PerformanceNodeTiming#
- Extends:
<PerformanceEntry>
This property is an extension by Node.js. It is not available in Web browsers.
Provides timing details for Node.js itself. The constructor of this class is not exposed to users.
performanceNodeTiming.bootstrapComplete#
- Type:
<number>
The high resolution millisecond timestamp at which the Node.js process completed bootstrapping. If bootstrapping has not yet finished, the property has the value of -1.
performanceNodeTiming.environment#
- Type:
<number>
The high resolution millisecond timestamp at which the Node.js environment was initialized.
performanceNodeTiming.idleTime#
- Type:
<number>
The high resolution millisecond timestamp of the amount of time the event loop has been idle within the event loop's event provider (e.g. epoll_wait). This does not take CPU usage into consideration. If the event loop has not yet started (e.g., in the first tick of the main script), the property has the value of 0.
performanceNodeTiming.loopExit#
- Type:
<number>
The high resolution millisecond timestamp at which the Node.js event loop exited. If the event loop has not yet exited, the property has the value of -1. It can only have a value of not -1 in a handler of the 'exit' event.
performanceNodeTiming.loopStart#
- Type:
<number>
The high resolution millisecond timestamp at which the Node.js event loop started. If the event loop has not yet started (e.g., in the first tick of the main script), the property has the value of -1.
performanceNodeTiming.nodeStart#
- Type:
<number>
The high resolution millisecond timestamp at which the Node.js process was initialized.
performanceNodeTiming.uvMetricsInfo#
- Returns:
<Object>
This is a wrapper to the uv_metrics_info function. It returns the current set of event loop metrics.
It is recommended to use this property inside a function whose execution was scheduled using setImmediate to avoid collecting metrics before finishing all operations scheduled during the current loop iteration.
const { performance } = require('node:perf_hooks'); setImmediate(() => { console.log(performance.nodeTiming.uvMetricsInfo); });import { performance } from 'node:perf_hooks'; setImmediate(() => { console.log(performance.nodeTiming.uvMetricsInfo); });
performanceNodeTiming.v8Start#
- Type:
<number>
The high resolution millisecond timestamp at which the V8 platform was initialized.
Class: PerformanceResourceTiming#
- Extends:
<PerformanceEntry>
Provides detailed network timing data regarding the loading of an application's resources.
The constructor of this class is not exposed to users directly.
performanceResourceTiming.workerStart#
- Type:
<number>
The high resolution millisecond timestamp at immediately before dispatching the fetch request. If the resource is not intercepted by a worker the property will always return 0.
performanceResourceTiming.redirectStart#
- Type:
<number>
The high resolution millisecond timestamp that represents the start time of the fetch which initiates the redirect.
performanceResourceTiming.redirectEnd#
- Type:
<number>
The high resolution millisecond timestamp that will be created immediately after receiving the last byte of the response of the last redirect.
performanceResourceTiming.fetchStart#
- Type:
<number>
The high resolution millisecond timestamp immediately before the Node.js starts to fetch the resource.
performanceResourceTiming.domainLookupStart#
- Type:
<number>
The high resolution millisecond timestamp immediately before the Node.js starts the domain name lookup for the resource.
performanceResourceTiming.domainLookupEnd#
- Type:
<number>
The high resolution millisecond timestamp representing the time immediately after the Node.js finished the domain name lookup for the resource.
performanceResourceTiming.connectStart#
- Type:
<number>
The high resolution millisecond timestamp representing the time immediately before Node.js starts to establish the connection to the server to retrieve the resource.
performanceResourceTiming.connectEnd#
- Type:
<number>
The high resolution millisecond timestamp representing the time immediately after Node.js finishes establishing the connection to the server to retrieve the resource.
performanceResourceTiming.secureConnectionStart#
- Type:
<number>
The high resolution millisecond timestamp representing the time immediately before Node.js starts the handshake process to secure the current connection.
performanceResourceTiming.requestStart#
- Type:
<number>
The high resolution millisecond timestamp representing the time immediately before Node.js receives the first byte of the response from the server.
performanceResourceTiming.responseEnd#
- Type:
<number>
The high resolution millisecond timestamp representing the time immediately after Node.js receives the last byte of the resource or immediately before the transport connection is closed, whichever comes first.
performanceResourceTiming.transferSize#
- Type:
<number>
A number representing the size (in octets) of the fetched resource. The size includes the response header fields plus the response payload body.
performanceResourceTiming.encodedBodySize#
- Type:
<number>
A number representing the size (in octets) received from the fetch (HTTP or cache), of the payload body, before removing any applied content-codings.
performanceResourceTiming.decodedBodySize#
- Type:
<number>
A number representing the size (in octets) received from the fetch (HTTP or cache), of the message body, after removing any applied content-codings.
performanceResourceTiming.toJSON()#
Returns a object that is the JSON representation of the PerformanceResourceTiming object
Class: PerformanceObserver#
PerformanceObserver.supportedEntryTypes#
- Type:
<string[]>
Get supported types.
new PerformanceObserver(callback)#
callback<Function>list<PerformanceObserverEntryList>observer<PerformanceObserver>
PerformanceObserver objects provide notifications when new PerformanceEntry instances have been added to the Performance Timeline.
import { performance, PerformanceObserver } from 'node:perf_hooks'; const obs = new PerformanceObserver((list, observer) => { console.log(list.getEntries()); performance.clearMarks(); performance.clearMeasures(); observer.disconnect(); }); obs.observe({ entryTypes: ['mark'], buffered: true }); performance.mark('test');const { performance, PerformanceObserver, } = require('node:perf_hooks'); const obs = new PerformanceObserver((list, observer) => { console.log(list.getEntries()); performance.clearMarks(); performance.clearMeasures(); observer.disconnect(); }); obs.observe({ entryTypes: ['mark'], buffered: true }); performance.mark('test');
Because PerformanceObserver instances introduce their own additional performance overhead, instances should not be left subscribed to notifications indefinitely. Users should disconnect observers as soon as they are no longer needed.
The callback is invoked when a PerformanceObserver is notified about new PerformanceEntry instances. The callback receives a PerformanceObserverEntryList instance and a reference to the PerformanceObserver.
performanceObserver.disconnect()#
Disconnects the PerformanceObserver instance from all notifications.
performanceObserver.observe(options)#
options<Object>type<string>A single<PerformanceEntry>type. Must not be given ifentryTypesis already specified.entryTypes<string[]>An array of strings identifying the types of<PerformanceEntry>instances the observer is interested in. If not provided an error will be thrown.buffered<boolean>If true, the observer callback is called with a list globalPerformanceEntrybuffered entries. If false, onlyPerformanceEntrys created after the time point are sent to the observer callback. Default:false.
Subscribes the <PerformanceObserver> instance to notifications of new <PerformanceEntry> instances identified either by options.entryTypes or options.type:
import { performance, PerformanceObserver } from 'node:perf_hooks'; const obs = new PerformanceObserver((list, observer) => { // Called once asynchronously. `list` contains three items. }); obs.observe({ type: 'mark' }); for (let n = 0; n < 3; n++) performance.mark(`test${n}`);const { performance, PerformanceObserver, } = require('node:perf_hooks'); const obs = new PerformanceObserver((list, observer) => { // Called once asynchronously. `list` contains three items. }); obs.observe({ type: 'mark' }); for (let n = 0; n < 3; n++) performance.mark(`test${n}`);
performanceObserver.takeRecords()#
- Returns:
<PerformanceEntry[]>Current list of entries stored in the performance observer, emptying it out.
Class: PerformanceObserverEntryList#
The PerformanceObserverEntryList class is used to provide access to the PerformanceEntry instances passed to a PerformanceObserver. The constructor of this class is not exposed to users.
performanceObserverEntryList.getEntries()#
- Returns:
<PerformanceEntry[]>
Returns a list of PerformanceEntry objects in chronological order with respect to performanceEntry.startTime.
import { performance, PerformanceObserver } from 'node:perf_hooks'; const obs = new PerformanceObserver((perfObserverList, observer) => { console.log(perfObserverList.getEntries()); /** * [ * PerformanceEntry { * name: 'test', * entryType: 'mark', * startTime: 81.465639, * duration: 0, * detail: null * }, * PerformanceEntry { * name: 'meow', * entryType: 'mark', * startTime: 81.860064, * duration: 0, * detail: null * } * ] */ performance.clearMarks(); performance.clearMeasures(); observer.disconnect(); }); obs.observe({ type: 'mark' }); performance.mark('test'); performance.mark('meow');const { performance, PerformanceObserver, } = require('node:perf_hooks'); const obs = new PerformanceObserver((perfObserverList, observer) => { console.log(perfObserverList.getEntries()); /** * [ * PerformanceEntry { * name: 'test', * entryType: 'mark', * startTime: 81.465639, * duration: 0, * detail: null * }, * PerformanceEntry { * name: 'meow', * entryType: 'mark', * startTime: 81.860064, * duration: 0, * detail: null * } * ] */ performance.clearMarks(); performance.clearMeasures(); observer.disconnect(); }); obs.observe({ type: 'mark' }); performance.mark('test'); performance.mark('meow');
performanceObserverEntryList.getEntriesByName(name[, type])#
name<string>type<string>- Returns:
<PerformanceEntry[]>
Returns a list of PerformanceEntry objects in chronological order with respect to performanceEntry.startTime whose performanceEntry.name is equal to name, and optionally, whose performanceEntry.entryType is equal to type.
import { performance, PerformanceObserver } from 'node:perf_hooks'; const obs = new PerformanceObserver((perfObserverList, observer) => { console.log(perfObserverList.getEntriesByName('meow')); /** * [ * PerformanceEntry { * name: 'meow', * entryType: 'mark', * startTime: 98.545991, * duration: 0, * detail: null * } * ] */ console.log(perfObserverList.getEntriesByName('nope')); // [] console.log(perfObserverList.getEntriesByName('test', 'mark')); /** * [ * PerformanceEntry { * name: 'test', * entryType: 'mark', * startTime: 63.518931, * duration: 0, * detail: null * } * ] */ console.log(perfObserverList.getEntriesByName('test', 'measure')); // [] performance.clearMarks(); performance.clearMeasures(); observer.disconnect(); }); obs.observe({ entryTypes: ['mark', 'measure'] }); performance.mark('test'); performance.mark('meow');const { performance, PerformanceObserver, } = require('node:perf_hooks'); const obs = new PerformanceObserver((perfObserverList, observer) => { console.log(perfObserverList.getEntriesByName('meow')); /** * [ * PerformanceEntry { * name: 'meow', * entryType: 'mark', * startTime: 98.545991, * duration: 0, * detail: null * } * ] */ console.log(perfObserverList.getEntriesByName('nope')); // [] console.log(perfObserverList.getEntriesByName('test', 'mark')); /** * [ * PerformanceEntry { * name: 'test', * entryType: 'mark', * startTime: 63.518931, * duration: 0, * detail: null * } * ] */ console.log(perfObserverList.getEntriesByName('test', 'measure')); // [] performance.clearMarks(); performance.clearMeasures(); observer.disconnect(); }); obs.observe({ entryTypes: ['mark', 'measure'] }); performance.mark('test'); performance.mark('meow');
performanceObserverEntryList.getEntriesByType(type)#
type<string>- Returns:
<PerformanceEntry[]>
Returns a list of PerformanceEntry objects in chronological order with respect to performanceEntry.startTime whose performanceEntry.entryType is equal to type.
import { performance, PerformanceObserver } from 'node:perf_hooks'; const obs = new PerformanceObserver((perfObserverList, observer) => { console.log(perfObserverList.getEntriesByType('mark')); /** * [ * PerformanceEntry { * name: 'test', * entryType: 'mark', * startTime: 55.897834, * duration: 0, * detail: null * }, * PerformanceEntry { * name: 'meow', * entryType: 'mark', * startTime: 56.350146, * duration: 0, * detail: null * } * ] */ performance.clearMarks(); performance.clearMeasures(); observer.disconnect(); }); obs.observe({ type: 'mark' }); performance.mark('test'); performance.mark('meow');const { performance, PerformanceObserver, } = require('node:perf_hooks'); const obs = new PerformanceObserver((perfObserverList, observer) => { console.log(perfObserverList.getEntriesByType('mark')); /** * [ * PerformanceEntry { * name: 'test', * entryType: 'mark', * startTime: 55.897834, * duration: 0, * detail: null * }, * PerformanceEntry { * name: 'meow', * entryType: 'mark', * startTime: 56.350146, * duration: 0, * detail: null * } * ] */ performance.clearMarks(); performance.clearMeasures(); observer.disconnect(); }); obs.observe({ type: 'mark' }); performance.mark('test'); performance.mark('meow');
perf_hooks.createHistogram([options])#
options<Object>lowest<number>|<bigint>The lowest discernible value. Must be an integer value greater than 0. Default:1.highest<number>|<bigint>The highest recordable value. Must be an integer value that is equal to or greater than two timeslowest. Default:Number.MAX_SAFE_INTEGER.figures<number>The number of accuracy digits. Must be a number between1and5. Default:3.
- Returns:
<RecordableHistogram>
Returns a <RecordableHistogram>.
perf_hooks.eventLoopUtilization([utilization1[, utilization2]])#
utilization1<Object>The result of a previous call toeventLoopUtilization().utilization2<Object>The result of a previous call toeventLoopUtilization()prior toutilization1.- Returns:
<Object>
The eventLoopUtilization() function returns an object that contains the cumulative duration of time the event loop has been both idle and active as a high resolution milliseconds timer. The utilization value is the calculated Event Loop Utilization (ELU).
If bootstrapping has not yet finished on the main thread the properties have the value of 0. The ELU is immediately available on Worker threads since bootstrap happens within the event loop.
Both utilization1 and utilization2 are optional parameters.
If utilization1 is passed, then the delta between the current call's active and idle times, as well as the corresponding utilization value are calculated and returned (similar to process.hrtime()).
If utilization1 and utilization2 are both passed, then the delta is calculated between the two arguments. This is a convenience option because, unlike process.hrtime(), calculating the ELU is more complex than a single subtraction.
ELU is similar to CPU utilization, except that it only measures event loop statistics and not CPU usage. It represents the percentage of time the event loop has spent outside the event loop's event provider (e.g. epoll_wait). No other CPU idle time is taken into consideration. The following is an example of how a mostly idle process will have a high ELU.
import { eventLoopUtilization } from 'node:perf_hooks'; import { spawnSync } from 'node:child_process'; setImmediate(() => { const elu = eventLoopUtilization(); spawnSync('sleep', ['5']); console.log(eventLoopUtilization(elu).utilization); });'use strict'; const { eventLoopUtilization } = require('node:perf_hooks'); const { spawnSync } = require('node:child_process'); setImmediate(() => { const elu = eventLoopUtilization(); spawnSync('sleep', ['5']); console.log(eventLoopUtilization(elu).utilization); });
Although the CPU is mostly idle while running this script, the value of utilization is 1. This is because the call to child_process.spawnSync() blocks the event loop from proceeding.
Passing in a user-defined object instead of the result of a previous call to eventLoopUtilization() will lead to undefined behavior. The return values are not guaranteed to reflect any correct state of the event loop.
perf_hooks.monitorEventLoopDelay([options])#
options<Object>resolution<number>The sampling rate in milliseconds. Must be greater than zero. Default:10.
- Returns:
<IntervalHistogram>
This property is an extension by Node.js. It is not available in Web browsers.
Creates an IntervalHistogram object that samples and reports the event loop delay over time. The delays will be reported in nanoseconds.
Using a timer to detect approximate event loop delay works because the execution of timers is tied specifically to the lifecycle of the libuv event loop. That is, a delay in the loop will cause a delay in the execution of the timer, and those delays are specifically what this API is intended to detect.
import { monitorEventLoopDelay } from 'node:perf_hooks'; const h = monitorEventLoopDelay({ resolution: 20 }); h.enable(); // Do something. h.disable(); console.log(h.min); console.log(h.max); console.log(h.mean); console.log(h.stddev); console.log(h.percentiles); console.log(h.percentile(50)); console.log(h.percentile(99));const { monitorEventLoopDelay } = require('node:perf_hooks'); const h = monitorEventLoopDelay({ resolution: 20 }); h.enable(); // Do something. h.disable(); console.log(h.min); console.log(h.max); console.log(h.mean); console.log(h.stddev); console.log(h.percentiles); console.log(h.percentile(50)); console.log(h.percentile(99));
perf_hooks.timerify(fn[, options])#
fn<Function>options<Object>histogram<RecordableHistogram>A histogram object created usingperf_hooks.createHistogram()that will record runtime durations in nanoseconds.
This property is an extension by Node.js. It is not available in Web browsers.
Wraps a function within a new function that measures the running time of the wrapped function. A PerformanceObserver must be subscribed to the 'function' event type in order for the timing details to be accessed.
import { timerify, performance, PerformanceObserver } from 'node:perf_hooks'; function someFunction() { console.log('hello world'); } const wrapped = timerify(someFunction); const obs = new PerformanceObserver((list) => { console.log(list.getEntries()[0].duration); performance.clearMarks(); performance.clearMeasures(); obs.disconnect(); }); obs.observe({ entryTypes: ['function'] }); // A performance timeline entry will be created wrapped();const { timerify, performance, PerformanceObserver, } = require('node:perf_hooks'); function someFunction() { console.log('hello world'); } const wrapped = timerify(someFunction); const obs = new PerformanceObserver((list) => { console.log(list.getEntries()[0].duration); performance.clearMarks(); performance.clearMeasures(); obs.disconnect(); }); obs.observe({ entryTypes: ['function'] }); // A performance timeline entry will be created wrapped();
If the wrapped function returns a promise, a finally handler will be attached to the promise and the duration will be reported once the finally handler is invoked.
Class: Histogram#
histogram.count#
- Type:
<number>
The number of samples recorded by the histogram.
histogram.countBigInt#
- Type:
<bigint>
The number of samples recorded by the histogram.
histogram.exceeds#
- Type:
<number>
The number of times the event loop delay exceeded the maximum 1 hour event loop delay threshold.
histogram.exceedsBigInt#
- Type:
<bigint>
The number of times the event loop delay exceeded the maximum 1 hour event loop delay threshold.
histogram.max#
- Type:
<number>
The maximum recorded event loop delay.
histogram.maxBigInt#
- Type:
<bigint>
The maximum recorded event loop delay.
histogram.mean#
- Type:
<number>
The mean of the recorded event loop delays.
histogram.min#
- Type:
<number>
The minimum recorded event loop delay.
histogram.minBigInt#
- Type:
<bigint>
The minimum recorded event loop delay.
histogram.percentile(percentile)#
Returns the value at the given percentile.
histogram.percentileBigInt(percentile)#
Returns the value at the given percentile.
histogram.percentiles#
- Type:
<Map>
Returns a Map object detailing the accumulated percentile distribution.
histogram.percentilesBigInt#
- Type:
<Map>
Returns a Map object detailing the accumulated percentile distribution.
histogram.reset()#
Resets the collected histogram data.
histogram.stddev#
- Type:
<number>
The standard deviation of the recorded event loop delays.
Class: IntervalHistogram extends Histogram#
A Histogram that is periodically updated on a given interval.
histogram.disable()#
- Returns:
<boolean>
Disables the update interval timer. Returns true if the timer was stopped, false if it was already stopped.
histogram.enable()#
- Returns:
<boolean>
Enables the update interval timer. Returns true if the timer was started, false if it was already started.
histogram[Symbol.dispose]()#
Disables the update interval timer when the histogram is disposed.
const { monitorEventLoopDelay } = require('node:perf_hooks');
{
using hist = monitorEventLoopDelay({ resolution: 20 });
hist.enable();
// The histogram will be disabled when the block is exited.
}
Cloning an IntervalHistogram#
<IntervalHistogram> instances can be cloned via <MessagePort>. On the receiving end, the histogram is cloned as a plain <Histogram> object that does not implement the enable() and disable() methods.
Class: RecordableHistogram extends Histogram#
histogram.add(other)#
other<RecordableHistogram>
Adds the values from other to this histogram.
histogram.record(val)#
histogram.recordDelta()#
Calculates the amount of time (in nanoseconds) that has passed since the previous call to recordDelta() and records that amount in the histogram.
Examples#
Measuring the duration of async operations#
The following example uses the Async Hooks and Performance APIs to measure the actual duration of a Timeout operation (including the amount of time it took to execute the callback).
import { createHook } from 'node:async_hooks'; import { performance, PerformanceObserver } from 'node:perf_hooks'; const set = new Set(); const hook = createHook({ init(id, type) { if (type === 'Timeout') { performance.mark(`Timeout-${id}-Init`); set.add(id); } }, destroy(id) { if (set.has(id)) { set.delete(id); performance.mark(`Timeout-${id}-Destroy`); performance.measure(`Timeout-${id}`, `Timeout-${id}-Init`, `Timeout-${id}-Destroy`); } }, }); hook.enable(); const obs = new PerformanceObserver((list, observer) => { console.log(list.getEntries()[0]); performance.clearMarks(); performance.clearMeasures(); observer.disconnect(); }); obs.observe({ entryTypes: ['measure'], buffered: true }); setTimeout(() => {}, 1000);'use strict'; const async_hooks = require('node:async_hooks'); const { performance, PerformanceObserver, } = require('node:perf_hooks'); const set = new Set(); const hook = async_hooks.createHook({ init(id, type) { if (type === 'Timeout') { performance.mark(`Timeout-${id}-Init`); set.add(id); } }, destroy(id) { if (set.has(id)) { set.delete(id); performance.mark(`Timeout-${id}-Destroy`); performance.measure(`Timeout-${id}`, `Timeout-${id}-Init`, `Timeout-${id}-Destroy`); } }, }); hook.enable(); const obs = new PerformanceObserver((list, observer) => { console.log(list.getEntries()[0]); performance.clearMarks(); performance.clearMeasures(); observer.disconnect(); }); obs.observe({ entryTypes: ['measure'] }); setTimeout(() => {}, 1000);
Measuring how long it takes to load dependencies#
The following example measures the duration of require() operations to load dependencies:
import { performance, PerformanceObserver } from 'node:perf_hooks'; // Activate the observer const obs = new PerformanceObserver((list) => { const entries = list.getEntries(); entries.forEach((entry) => { console.log(`import('${entry[0]}')`, entry.duration); }); performance.clearMarks(); performance.clearMeasures(); obs.disconnect(); }); obs.observe({ entryTypes: ['function'], buffered: true }); const timedImport = performance.timerify(async (module) => { return await import(module); }); await timedImport('some-module');'use strict'; const { performance, PerformanceObserver, } = require('node:perf_hooks'); const mod = require('node:module'); // Monkey patch the require function mod.Module.prototype.require = performance.timerify(mod.Module.prototype.require); require = performance.timerify(require); // Activate the observer const obs = new PerformanceObserver((list) => { const entries = list.getEntries(); entries.forEach((entry) => { console.log(`require('${entry[0]}')`, entry.duration); }); performance.clearMarks(); performance.clearMeasures(); obs.disconnect(); }); obs.observe({ entryTypes: ['function'] }); require('some-module');
Measuring how long one HTTP round-trip takes#
The following example is used to trace the time spent by HTTP client (OutgoingMessage) and HTTP request (IncomingMessage). For HTTP client, it means the time interval between starting the request and receiving the response, and for HTTP request, it means the time interval between receiving the request and sending the response:
import { PerformanceObserver } from 'node:perf_hooks'; import { createServer, get } from 'node:http'; const obs = new PerformanceObserver((items) => { items.getEntries().forEach((item) => { console.log(item); }); }); obs.observe({ entryTypes: ['http'] }); const PORT = 8080; createServer((req, res) => { res.end('ok'); }).listen(PORT, () => { get(`http://127.0.0.1:${PORT}`); });'use strict'; const { PerformanceObserver } = require('node:perf_hooks'); const http = require('node:http'); const obs = new PerformanceObserver((items) => { items.getEntries().forEach((item) => { console.log(item); }); }); obs.observe({ entryTypes: ['http'] }); const PORT = 8080; http.createServer((req, res) => { res.end('ok'); }).listen(PORT, () => { http.get(`http://127.0.0.1:${PORT}`); });
Measuring how long the net.connect (only for TCP) takes when the connection is successful#
import { PerformanceObserver } from 'node:perf_hooks'; import { connect, createServer } from 'node:net'; const obs = new PerformanceObserver((items) => { items.getEntries().forEach((item) => { console.log(item); }); }); obs.observe({ entryTypes: ['net'] }); const PORT = 8080; createServer((socket) => { socket.destroy(); }).listen(PORT, () => { connect(PORT); });'use strict'; const { PerformanceObserver } = require('node:perf_hooks'); const net = require('node:net'); const obs = new PerformanceObserver((items) => { items.getEntries().forEach((item) => { console.log(item); }); }); obs.observe({ entryTypes: ['net'] }); const PORT = 8080; net.createServer((socket) => { socket.destroy(); }).listen(PORT, () => { net.connect(PORT); });
Measuring how long the DNS takes when the request is successful#
import { PerformanceObserver } from 'node:perf_hooks'; import { lookup, promises } from 'node:dns'; const obs = new PerformanceObserver((items) => { items.getEntries().forEach((item) => { console.log(item); }); }); obs.observe({ entryTypes: ['dns'] }); lookup('localhost', () => {}); promises.resolve('localhost');'use strict'; const { PerformanceObserver } = require('node:perf_hooks'); const dns = require('node:dns'); const obs = new PerformanceObserver((items) => { items.getEntries().forEach((item) => { console.log(item); }); }); obs.observe({ entryTypes: ['dns'] }); dns.lookup('localhost', () => {}); dns.promises.resolve('localhost');
Permissions#
Permissions can be used to control what system resources the Node.js process has access to or what actions the process can take with those resources.
- Process-based permissions control the Node.js process's access to resources. The resource can be entirely allowed or denied, or actions related to it can be controlled. For example, file system reads can be allowed while denying writes. This feature does not protect against malicious code. According to the Node.js Security Policy, Node.js trusts any code it is asked to run.
The permission model implements a "seat belt" approach, which prevents trusted code from unintentionally changing files or using resources that access has not explicitly been granted to. It does not provide security guarantees in the presence of malicious code. Malicious code can bypass the permission model and execute arbitrary code without the restrictions imposed by the permission model.
If you find a potential security vulnerability, please refer to our Security Policy.
Process-based permissions#
Permission Model#
Stability: 2 - Stable
The Node.js Permission Model is a mechanism for restricting access to specific resources during execution. The API exists behind a flag --permission which when enabled, will restrict access to all available permissions.
The available permissions are documented by the --permission flag.
When starting Node.js with --permission, the ability to access the file system through the fs module, access the network, spawn processes, use node:worker_threads, use native addons, use WASI, and enable the runtime inspector will be restricted (the listener for SIGUSR1 won't be created).
$ node --permission index.js
Error: Access to this API has been restricted
at node:internal/main/run_main_module:23:47 {
code: 'ERR_ACCESS_DENIED',
permission: 'FileSystemRead',
resource: '/home/user/index.js'
}
Allowing access to spawning a process and creating worker threads can be done using the --allow-child-process and --allow-worker respectively.
To allow network access, use --allow-net and for allowing native addons when using permission model, use the --allow-addons flag. For WASI, use the --allow-wasi flag.
Runtime API#
When enabling the Permission Model through the --permission flag a new property permission is added to the process object. This property contains one function:
permission.has(scope[, reference])#
API call to check permissions at runtime (permission.has())
process.permission.has('fs.write'); // true
process.permission.has('fs.write', '/home/rafaelgss/protected-folder'); // true
process.permission.has('fs.read'); // true
process.permission.has('fs.read', '/home/rafaelgss/protected-folder'); // false
File System Permissions#
The Permission Model, by default, restricts access to the file system through the node:fs module. It does not guarantee that users will not be able to access the file system through other means, such as through the node:sqlite module.
To allow access to the file system, use the --allow-fs-read and --allow-fs-write flags:
$ node --permission --allow-fs-read=* --allow-fs-write=* index.js
Hello world!
By default the entrypoints of your application are included in the allowed file system read list. For example:
$ node --permission index.js
index.jswill be included in the allowed file system read list
$ node -r /path/to/custom-require.js --permission index.js.
/path/to/custom-require.jswill be included in the allowed file system read list.index.jswill be included in the allowed file system read list.
The valid arguments for both flags are:
*- To allow allFileSystemReadorFileSystemWriteoperations, respectively.- Relative paths to the current working directory.
- Absolute paths.
Example:
--allow-fs-read=*- It will allow allFileSystemReadoperations.--allow-fs-write=*- It will allow allFileSystemWriteoperations.--allow-fs-write=/tmp/- It will allowFileSystemWriteaccess to the/tmp/folder.--allow-fs-read=/tmp/ --allow-fs-read=/home/.gitignore- It allowsFileSystemReadaccess to the/tmp/folder and the/home/.gitignorepath.
Wildcards are supported too:
--allow-fs-read=/home/test*will allow read access to everything that matches the wildcard. e.g:/home/test/file1or/home/test2
After passing a wildcard character (*) all subsequent characters will be ignored. For example: /home/*.js will work similar to /home/*.
When the permission model is initialized, it will automatically add a wildcard (*) if the specified directory exists. For example, if /home/test/files exists, it will be treated as /home/test/files/*. However, if the directory does not exist, the wildcard will not be added, and access will be limited to /home/test/files. If you want to allow access to a folder that does not exist yet, make sure to explicitly include the wildcard: /my-path/folder-do-not-exist/*.
Configuration file support#
In addition to passing permission flags on the command line, they can also be declared in a Node.js configuration file when using the experimental [--experimental-config-file][] flag. Permission options must be placed inside the permission top-level object.
Example node.config.json:
{
"permission": {
"allow-fs-read": ["./foo"],
"allow-fs-write": ["./bar"],
"allow-child-process": true,
"allow-worker": true,
"allow-net": true,
"allow-addons": false
}
}
When the permission namespace is present in the configuration file, Node.js automatically enables the --permission flag. Run with:
$ node --experimental-default-config-file app.js
Using the Permission Model with npx#
If you're using npx to execute a Node.js script, you can enable the Permission Model by passing the --node-options flag. For example:
npx --node-options="--permission" package-name
This sets the NODE_OPTIONS environment variable for all Node.js processes spawned by npx, without affecting the npx process itself.
FileSystemRead Error with npx
The above command will likely throw a FileSystemRead invalid access error because Node.js requires file system read access to locate and execute the package. To avoid this:
Using a Globally Installed Package Grant read access to the global
node_modulesdirectory by running:npx --node-options="--permission --allow-fs-read=$(npm prefix -g)" package-nameUsing the
npxCache If you are installing the package temporarily or relying on thenpxcache, grant read access to the npm cache directory:npx --node-options="--permission --allow-fs-read=$(npm config get cache)" package-name
Any arguments you would normally pass to node (e.g., --allow-* flags) can also be passed through the --node-options flag. This flexibility makes it easy to configure permissions as needed when using npx.
Permission Model constraints#
There are constraints you need to know before using this system:
- The model does not inherit to a worker thread.
- When using the Permission Model the following features will be restricted:
- Native modules
- Network
- Child process
- Worker Threads
- Inspector protocol
- File system access
- WASI
- The Permission Model is initialized after the Node.js environment is set up. However, certain flags such as
--env-fileor--openssl-configare designed to read files before environment initialization. As a result, such flags are not subject to the rules of the Permission Model. The same applies for V8 flags that can be set via runtime throughv8.setFlagsFromString. - OpenSSL engines cannot be requested at runtime when the Permission Model is enabled, affecting the built-in crypto, https, and tls modules.
- Run-Time Loadable Extensions cannot be loaded when the Permission Model is enabled, affecting the sqlite module.
- Using existing file descriptors via the
node:fsmodule bypasses the Permission Model.
Limitations and Known Issues#
- Symbolic links will be followed even to locations outside of the set of paths that access has been granted to. Relative symbolic links may allow access to arbitrary files and directories. When starting applications with the permission model enabled, you must ensure that no paths to which access has been granted contain relative symbolic links.
Timers#
Stability: 2 - Stable
The timer module exposes a global API for scheduling functions to be called at some future period of time. Because the timer functions are globals, there is no need to call require('node:timers') to use the API.
The timer functions within Node.js implement a similar API as the timers API provided by Web Browsers but use a different internal implementation that is built around the Node.js Event Loop.
Class: Immediate#
This object is created internally and is returned from setImmediate(). It can be passed to clearImmediate() in order to cancel the scheduled actions.
By default, when an immediate is scheduled, the Node.js event loop will continue running as long as the immediate is active. The Immediate object returned by setImmediate() exports both immediate.ref() and immediate.unref() functions that can be used to control this default behavior.
immediate.hasRef()#
- Returns:
<boolean>
If true, the Immediate object will keep the Node.js event loop active.
immediate.ref()#
- Returns:
<Immediate>a reference toimmediate
When called, requests that the Node.js event loop not exit so long as the Immediate is active. Calling immediate.ref() multiple times will have no effect.
By default, all Immediate objects are "ref'ed", making it normally unnecessary to call immediate.ref() unless immediate.unref() had been called previously.
immediate.unref()#
- Returns:
<Immediate>a reference toimmediate
When called, the active Immediate object will not require the Node.js event loop to remain active. If there is no other activity keeping the event loop running, the process may exit before the Immediate object's callback is invoked. Calling immediate.unref() multiple times will have no effect.
immediate[Symbol.dispose]()#
Cancels the immediate. This is similar to calling clearImmediate().
Class: Timeout#
This object is created internally and is returned from setTimeout() and setInterval(). It can be passed to either clearTimeout() or clearInterval() in order to cancel the scheduled actions.
By default, when a timer is scheduled using either setTimeout() or setInterval(), the Node.js event loop will continue running as long as the timer is active. Each of the Timeout objects returned by these functions export both timeout.ref() and timeout.unref() functions that can be used to control this default behavior.
timeout.close()#
Stability: 3 - Legacy: Use clearTimeout() instead.
- Returns:
<Timeout>a reference totimeout
Cancels the timeout.
timeout.hasRef()#
- Returns:
<boolean>
If true, the Timeout object will keep the Node.js event loop active.
timeout.ref()#
- Returns:
<Timeout>a reference totimeout
When called, requests that the Node.js event loop not exit so long as the Timeout is active. Calling timeout.ref() multiple times will have no effect.
By default, all Timeout objects are "ref'ed", making it normally unnecessary to call timeout.ref() unless timeout.unref() had been called previously.
timeout.refresh()#
- Returns:
<Timeout>a reference totimeout
Sets the timer's start time to the current time, and reschedules the timer to call its callback at the previously specified duration adjusted to the current time. This is useful for refreshing a timer without allocating a new JavaScript object.
Using this on a timer that has already called its callback will reactivate the timer.
timeout.unref()#
- Returns:
<Timeout>a reference totimeout
When called, the active Timeout object will not require the Node.js event loop to remain active. If there is no other activity keeping the event loop running, the process may exit before the Timeout object's callback is invoked. Calling timeout.unref() multiple times will have no effect.
timeout[Symbol.toPrimitive]()#
- Returns:
<integer>a number that can be used to reference thistimeout
Coerce a Timeout to a primitive. The primitive can be used to clear the Timeout. The primitive can only be used in the same thread where the timeout was created. Therefore, to use it across worker_threads it must first be passed to the correct thread. This allows enhanced compatibility with browser setTimeout() and setInterval() implementations.
timeout[Symbol.dispose]()#
Cancels the timeout.
Scheduling timers#
A timer in Node.js is an internal construct that calls a given function after a certain period of time. When a timer's function is called varies depending on which method was used to create the timer and what other work the Node.js event loop is doing.
setImmediate(callback[, ...args])#
callback<Function>The function to call at the end of this turn of the Node.js Event Loop...args<any>Optional arguments to pass when thecallbackis called.- Returns:
<Immediate>for use withclearImmediate()
Schedules the "immediate" execution of the callback after I/O events' callbacks.
When multiple calls to setImmediate() are made, the callback functions are queued for execution in the order in which they are created. The entire callback queue is processed every event loop iteration. If an immediate timer is queued from inside an executing callback, that timer will not be triggered until the next event loop iteration.
If callback is not a function, a TypeError will be thrown.
This method has a custom variant for promises that is available using timersPromises.setImmediate().
setInterval(callback[, delay[, ...args]])#
callback<Function>The function to call when the timer elapses.delay<number>The number of milliseconds to wait before calling thecallback. Default:1....args<any>Optional arguments to pass when thecallbackis called.- Returns:
<Timeout>for use withclearInterval()
Schedules repeated execution of callback every delay milliseconds.
When delay is larger than 2147483647 or less than 1 or NaN, the delay will be set to 1. Non-integer delays are truncated to an integer.
If callback is not a function, a TypeError will be thrown.
This method has a custom variant for promises that is available using timersPromises.setInterval().
setTimeout(callback[, delay[, ...args]])#
callback<Function>The function to call when the timer elapses.delay<number>The number of milliseconds to wait before calling thecallback. Default:1....args<any>Optional arguments to pass when thecallbackis called.- Returns:
<Timeout>for use withclearTimeout()
Schedules execution of a one-time callback after delay milliseconds.
The callback will likely not be invoked in precisely delay milliseconds. Node.js makes no guarantees about the exact timing of when callbacks will fire, nor of their ordering. The callback will be called as close as possible to the time specified.
When delay is larger than 2147483647 or less than 1 or NaN, the delay will be set to 1. Non-integer delays are truncated to an integer.
If callback is not a function, a TypeError will be thrown.
This method has a custom variant for promises that is available using timersPromises.setTimeout().
Cancelling timers#
The setImmediate(), setInterval(), and setTimeout() methods each return objects that represent the scheduled timers. These can be used to cancel the timer and prevent it from triggering.
For the promisified variants of setImmediate() and setTimeout(), an AbortController may be used to cancel the timer. When canceled, the returned Promises will be rejected with an 'AbortError'.
For setImmediate():
import { setImmediate as setImmediatePromise } from 'node:timers/promises'; const ac = new AbortController(); const signal = ac.signal; // We do not `await` the promise so `ac.abort()` is called concurrently. setImmediatePromise('foobar', { signal }) .then(console.log) .catch((err) => { if (err.name === 'AbortError') console.error('The immediate was aborted'); }); ac.abort();const { setImmediate: setImmediatePromise } = require('node:timers/promises'); const ac = new AbortController(); const signal = ac.signal; setImmediatePromise('foobar', { signal }) .then(console.log) .catch((err) => { if (err.name === 'AbortError') console.error('The immediate was aborted'); }); ac.abort();
For setTimeout():
import { setTimeout as setTimeoutPromise } from 'node:timers/promises'; const ac = new AbortController(); const signal = ac.signal; // We do not `await` the promise so `ac.abort()` is called concurrently. setTimeoutPromise(1000, 'foobar', { signal }) .then(console.log) .catch((err) => { if (err.name === 'AbortError') console.error('The timeout was aborted'); }); ac.abort();const { setTimeout: setTimeoutPromise } = require('node:timers/promises'); const ac = new AbortController(); const signal = ac.signal; setTimeoutPromise(1000, 'foobar', { signal }) .then(console.log) .catch((err) => { if (err.name === 'AbortError') console.error('The timeout was aborted'); }); ac.abort();
clearImmediate(immediate)#
immediate<Immediate>AnImmediateobject as returned bysetImmediate().
Cancels an Immediate object created by setImmediate().
clearInterval(timeout)#
timeout<Timeout>|<string>|<number>ATimeoutobject as returned bysetInterval()or the primitive of theTimeoutobject as a string or a number.
Cancels a Timeout object created by setInterval().
clearTimeout(timeout)#
timeout<Timeout>|<string>|<number>ATimeoutobject as returned bysetTimeout()or the primitive of theTimeoutobject as a string or a number.
Cancels a Timeout object created by setTimeout().
Timers Promises API#
The timers/promises API provides an alternative set of timer functions that return Promise objects. The API is accessible via require('node:timers/promises').
import { setTimeout, setImmediate, setInterval, } from 'node:timers/promises';const { setTimeout, setImmediate, setInterval, } = require('node:timers/promises');
timersPromises.setTimeout([delay[, value[, options]]])#
delay<number>The number of milliseconds to wait before fulfilling the promise. Default:1.value<any>A value with which the promise is fulfilled.options<Object>ref<boolean>Set tofalseto indicate that the scheduledTimeoutshould not require the Node.js event loop to remain active. Default:true.signal<AbortSignal>An optionalAbortSignalthat can be used to cancel the scheduledTimeout.
import { setTimeout, } from 'node:timers/promises'; const res = await setTimeout(100, 'result'); console.log(res); // Prints 'result'const { setTimeout, } = require('node:timers/promises'); setTimeout(100, 'result').then((res) => { console.log(res); // Prints 'result' });
timersPromises.setImmediate([value[, options]])#
value<any>A value with which the promise is fulfilled.options<Object>ref<boolean>Set tofalseto indicate that the scheduledImmediateshould not require the Node.js event loop to remain active. Default:true.signal<AbortSignal>An optionalAbortSignalthat can be used to cancel the scheduledImmediate.
import { setImmediate, } from 'node:timers/promises'; const res = await setImmediate('result'); console.log(res); // Prints 'result'const { setImmediate, } = require('node:timers/promises'); setImmediate('result').then((res) => { console.log(res); // Prints 'result' });
timersPromises.setInterval([delay[, value[, options]]])#
Returns an async iterator that generates values in an interval of delay ms. If ref is true, you need to call next() of async iterator explicitly or implicitly to keep the event loop alive.
delay<number>The number of milliseconds to wait between iterations. Default:1.value<any>A value with which the iterator returns.options<Object>ref<boolean>Set tofalseto indicate that the scheduledTimeoutbetween iterations should not require the Node.js event loop to remain active. Default:true.signal<AbortSignal>An optionalAbortSignalthat can be used to cancel the scheduledTimeoutbetween operations.
import { setInterval, } from 'node:timers/promises'; const interval = 100; for await (const startTime of setInterval(interval, Date.now())) { const now = Date.now(); console.log(now); if ((now - startTime) > 1000) break; } console.log(Date.now());const { setInterval, } = require('node:timers/promises'); const interval = 100; (async function() { for await (const startTime of setInterval(interval, Date.now())) { const now = Date.now(); console.log(now); if ((now - startTime) > 1000) break; } console.log(Date.now()); })();
timersPromises.scheduler.wait(delay[, options])#
Stability: 1 - Experimental
delay<number>The number of milliseconds to wait before resolving the promise.options<Object>ref<boolean>Set tofalseto indicate that the scheduledTimeoutshould not require the Node.js event loop to remain active. Default:true.signal<AbortSignal>An optionalAbortSignalthat can be used to cancel waiting.
- Returns:
<Promise>
An experimental API defined by the Scheduling APIs draft specification being developed as a standard Web Platform API.
Calling timersPromises.scheduler.wait(delay, options) is equivalent to calling timersPromises.setTimeout(delay, undefined, options).
import { scheduler } from 'node:timers/promises';
await scheduler.wait(1000); // Wait one second before continuing
timersPromises.scheduler.yield()#
Stability: 1 - Experimental
- Returns:
<Promise>
An experimental API defined by the Scheduling APIs draft specification being developed as a standard Web Platform API.
Calling timersPromises.scheduler.yield() is equivalent to calling timersPromises.setImmediate() with no arguments.
TLS (SSL)#
Stability: 2 - Stable
The node:tls module provides an implementation of the Transport Layer Security (TLS) and Secure Socket Layer (SSL) protocols that is built on top of OpenSSL. The module can be accessed using:
import tls from 'node:tls';const tls = require('node:tls');
Determining if crypto support is unavailable#
It is possible for Node.js to be built without including support for the node:crypto module. In such cases, attempting to import from tls or calling require('node:tls') will result in an error being thrown.
When using CommonJS, the error thrown can be caught using try/catch:
let tls;
try {
tls = require('node:tls');
} catch (err) {
console.error('tls support is disabled!');
}
When using the lexical ESM import keyword, the error can only be caught if a handler for process.on('uncaughtException') is registered before any attempt to load the module is made (using, for instance, a preload module).
When using ESM, if there is a chance that the code may be run on a build of Node.js where crypto support is not enabled, consider using the import() function instead of the lexical import keyword:
let tls;
try {
tls = await import('node:tls');
} catch (err) {
console.error('tls support is disabled!');
}
TLS/SSL concepts#
TLS/SSL is a set of protocols that rely on a public key infrastructure (PKI) to enable secure communication between a client and a server. For most common cases, each server must have a private key.
Private keys can be generated in multiple ways. The example below illustrates use of the OpenSSL command-line interface to generate a 2048-bit RSA private key:
openssl genrsa -out ryans-key.pem 2048
With TLS/SSL, all servers (and some clients) must have a certificate. Certificates are public keys that correspond to a private key, and that are digitally signed either by a Certificate Authority or by the owner of the private key (such certificates are referred to as "self-signed"). The first step to obtaining a certificate is to create a Certificate Signing Request (CSR) file.
The OpenSSL command-line interface can be used to generate a CSR for a private key:
openssl req -new -sha256 -key ryans-key.pem -out ryans-csr.pem
Once the CSR file is generated, it can either be sent to a Certificate Authority for signing or used to generate a self-signed certificate.
Creating a self-signed certificate using the OpenSSL command-line interface is illustrated in the example below:
openssl x509 -req -in ryans-csr.pem -signkey ryans-key.pem -out ryans-cert.pem
Once the certificate is generated, it can be used to generate a .pfx or .p12 file:
openssl pkcs12 -export -in ryans-cert.pem -inkey ryans-key.pem \
-certfile ca-cert.pem -out ryans.pfx
Where:
in: is the signed certificateinkey: is the associated private keycertfile: is a concatenation of all Certificate Authority (CA) certs into a single file, e.g.cat ca1-cert.pem ca2-cert.pem > ca-cert.pem
Perfect forward secrecy#
The term forward secrecy or perfect forward secrecy describes a feature of key-agreement (i.e., key-exchange) methods. That is, the server and client keys are used to negotiate new temporary keys that are used specifically and only for the current communication session. Practically, this means that even if the server's private key is compromised, communication can only be decrypted by eavesdroppers if the attacker manages to obtain the key-pair specifically generated for the session.
Perfect forward secrecy is achieved by randomly generating a key pair for key-agreement on every TLS/SSL handshake (in contrast to using the same key for all sessions). Methods implementing this technique are called "ephemeral".
Currently two methods are commonly used to achieve perfect forward secrecy (note the character "E" appended to the traditional abbreviations):
- ECDHE: An ephemeral version of the Elliptic Curve Diffie-Hellman key-agreement protocol.
- DHE: An ephemeral version of the Diffie-Hellman key-agreement protocol.
Perfect forward secrecy using ECDHE is enabled by default. The ecdhCurve option can be used when creating a TLS server to customize the list of supported ECDH curves to use. See tls.createServer() for more info.
DHE is disabled by default but can be enabled alongside ECDHE by setting the dhparam option to 'auto'. Custom DHE parameters are also supported but discouraged in favor of automatically selected, well-known parameters.
Perfect forward secrecy was optional up to TLSv1.2. As of TLSv1.3, (EC)DHE is always used (with the exception of PSK-only connections).
ALPN and SNI#
ALPN (Application-Layer Protocol Negotiation Extension) and SNI (Server Name Indication) are TLS handshake extensions:
- ALPN: Allows the use of one TLS server for multiple protocols (HTTP, HTTP/2)
- SNI: Allows the use of one TLS server for multiple hostnames with different certificates.
Pre-shared keys#
TLS-PSK support is available as an alternative to normal certificate-based authentication. It uses a pre-shared key instead of certificates to authenticate a TLS connection, providing mutual authentication. TLS-PSK and public key infrastructure are not mutually exclusive. Clients and servers can accommodate both, choosing either of them during the normal cipher negotiation step.
TLS-PSK is only a good choice where means exist to securely share a key with every connecting machine, so it does not replace the public key infrastructure (PKI) for the majority of TLS uses. The TLS-PSK implementation in OpenSSL has seen many security flaws in recent years, mostly because it is used only by a minority of applications. Please consider all alternative solutions before switching to PSK ciphers. Upon generating PSK it is of critical importance to use sufficient entropy as discussed in RFC 4086. Deriving a shared secret from a password or other low-entropy sources is not secure.
PSK ciphers are disabled by default, and using TLS-PSK thus requires explicitly specifying a cipher suite with the ciphers option. The list of available ciphers can be retrieved via openssl ciphers -v 'PSK'. All TLS 1.3 ciphers are eligible for PSK and can be retrieved via openssl ciphers -v -s -tls1_3 -psk. On the client connection, a custom checkServerIdentity should be passed because the default one will fail in the absence of a certificate.
According to the RFC 4279, PSK identities up to 128 bytes in length and PSKs up to 64 bytes in length must be supported. As of OpenSSL 1.1.0 maximum identity size is 128 bytes, and maximum PSK length is 256 bytes.
The current implementation doesn't support asynchronous PSK callbacks due to the limitations of the underlying OpenSSL API.
To use TLS-PSK, client and server must specify the pskCallback option, a function that returns the PSK to use (which must be compatible with the selected cipher's digest).
It will be called first on the client:
hint<string>optional message sent from the server to help the client decide which identity to use during negotiation. Alwaysnullif TLS 1.3 is used.- Returns:
<Object>in the form{ psk: <Buffer|TypedArray|DataView>, identity: <string> }ornull.
Then on the server:
socket<tls.TLSSocket>the server socket instance, equivalent tothis.identity<string>identity parameter sent from the client.- Returns:
<Buffer>|<TypedArray>|<DataView>the PSK (ornull).
A return value of null stops the negotiation process and sends an unknown_psk_identity alert message to the other party. If the server wishes to hide the fact that the PSK identity was not known, the callback must provide some random data as psk to make the connection fail with decrypt_error before negotiation is finished.
Client-initiated renegotiation attack mitigation#
The TLS protocol allows clients to renegotiate certain aspects of the TLS session. Unfortunately, session renegotiation requires a disproportionate amount of server-side resources, making it a potential vector for denial-of-service attacks.
To mitigate the risk, renegotiation is limited to three times every ten minutes. An 'error' event is emitted on the tls.TLSSocket instance when this threshold is exceeded. The limits are configurable:
tls.CLIENT_RENEG_LIMIT<number>Specifies the number of renegotiation requests. Default:3.tls.CLIENT_RENEG_WINDOW<number>Specifies the time renegotiation window in seconds. Default:600(10 minutes).
The default renegotiation limits should not be modified without a full understanding of the implications and risks.
TLSv1.3 does not support renegotiation.
Session resumption#
Establishing a TLS session can be relatively slow. The process can be sped up by saving and later reusing the session state. There are several mechanisms to do so, discussed here from oldest to newest (and preferred).
Session identifiers#
Servers generate a unique ID for new connections and send it to the client. Clients and servers save the session state. When reconnecting, clients send the ID of their saved session state and if the server also has the state for that ID, it can agree to use it. Otherwise, the server will create a new session. See RFC 2246 for more information, page 23 and 30.
Resumption using session identifiers is supported by most web browsers when making HTTPS requests.
For Node.js, clients wait for the 'session' event to get the session data, and provide the data to the session option of a subsequent tls.connect() to reuse the session. Servers must implement handlers for the 'newSession' and 'resumeSession' events to save and restore the session data using the session ID as the lookup key to reuse sessions. To reuse sessions across load balancers or cluster workers, servers must use a shared session cache (such as Redis) in their session handlers.
Session tickets#
The servers encrypt the entire session state and send it to the client as a "ticket". When reconnecting, the state is sent to the server in the initial connection. This mechanism avoids the need for a server-side session cache. If the server doesn't use the ticket, for any reason (failure to decrypt it, it's too old, etc.), it will create a new session and send a new ticket. See RFC 5077 for more information.
Resumption using session tickets is becoming commonly supported by many web browsers when making HTTPS requests.
For Node.js, clients use the same APIs for resumption with session identifiers as for resumption with session tickets. For debugging, if tls.TLSSocket.getTLSTicket() returns a value, the session data contains a ticket, otherwise it contains client-side session state.
With TLSv1.3, be aware that multiple tickets may be sent by the server, resulting in multiple 'session' events, see 'session' for more information.
Single process servers need no specific implementation to use session tickets. To use session tickets across server restarts or load balancers, servers must all have the same ticket keys. There are three 16-byte keys internally, but the tls API exposes them as a single 48-byte buffer for convenience.
It's possible to get the ticket keys by calling server.getTicketKeys() on one server instance and then distribute them, but it is more reasonable to securely generate 48 bytes of secure random data and set them with the ticketKeys option of tls.createServer(). The keys should be regularly regenerated and server's keys can be reset with server.setTicketKeys().
Session ticket keys are cryptographic keys, and they must be stored securely. With TLS 1.2 and below, if they are compromised all sessions that used tickets encrypted with them can be decrypted. They should not be stored on disk, and they should be regenerated regularly.
If clients advertise support for tickets, the server will send them. The server can disable tickets by supplying require('node:constants').SSL_OP_NO_TICKET in secureOptions.
Both session identifiers and session tickets timeout, causing the server to create new sessions. The timeout can be configured with the sessionTimeout option of tls.createServer().
For all the mechanisms, when resumption fails, servers will create new sessions. Since failing to resume the session does not cause TLS/HTTPS connection failures, it is easy to not notice unnecessarily poor TLS performance. The OpenSSL CLI can be used to verify that servers are resuming sessions. Use the -reconnect option to openssl s_client, for example:
openssl s_client -connect localhost:443 -reconnect
Read through the debug output. The first connection should say "New", for example:
New, TLSv1.2, Cipher is ECDHE-RSA-AES128-GCM-SHA256
Subsequent connections should say "Reused", for example:
Reused, TLSv1.2, Cipher is ECDHE-RSA-AES128-GCM-SHA256
Modifying the default TLS cipher suite#
Node.js is built with a default suite of enabled and disabled TLS ciphers. This default cipher list can be configured when building Node.js to allow distributions to provide their own default list.
The following command can be used to show the default cipher suite:
node -p crypto.constants.defaultCoreCipherList | tr ':' '\n'
TLS_AES_256_GCM_SHA384
TLS_CHACHA20_POLY1305_SHA256
TLS_AES_128_GCM_SHA256
ECDHE-RSA-AES128-GCM-SHA256
ECDHE-ECDSA-AES128-GCM-SHA256
ECDHE-RSA-AES256-GCM-SHA384
ECDHE-ECDSA-AES256-GCM-SHA384
DHE-RSA-AES128-GCM-SHA256
ECDHE-RSA-AES128-SHA256
DHE-RSA-AES128-SHA256
ECDHE-RSA-AES256-SHA384
DHE-RSA-AES256-SHA384
ECDHE-RSA-AES256-SHA256
DHE-RSA-AES256-SHA256
HIGH
!aNULL
!eNULL
!EXPORT
!DES
!RC4
!MD5
!PSK
!SRP
!CAMELLIA
This default can be replaced entirely using the --tls-cipher-list command-line switch (directly, or via the NODE_OPTIONS environment variable). For instance, the following makes ECDHE-RSA-AES128-GCM-SHA256:!RC4 the default TLS cipher suite:
node --tls-cipher-list='ECDHE-RSA-AES128-GCM-SHA256:!RC4' server.js
export NODE_OPTIONS=--tls-cipher-list='ECDHE-RSA-AES128-GCM-SHA256:!RC4'
node server.js
To verify, use the following command to show the set cipher list, note the difference between defaultCoreCipherList and defaultCipherList:
node --tls-cipher-list='ECDHE-RSA-AES128-GCM-SHA256:!RC4' -p crypto.constants.defaultCipherList | tr ':' '\n'
ECDHE-RSA-AES128-GCM-SHA256
!RC4
i.e. the defaultCoreCipherList list is set at compilation time and the defaultCipherList is set at runtime.
To modify the default cipher suites from within the runtime, modify the tls.DEFAULT_CIPHERS variable, this must be performed before listening on any sockets, it will not affect sockets already opened. For example:
// Remove Obsolete CBC Ciphers and RSA Key Exchange based Ciphers as they don't provide Forward Secrecy
tls.DEFAULT_CIPHERS +=
':!ECDHE-RSA-AES128-SHA:!ECDHE-RSA-AES128-SHA256:!ECDHE-RSA-AES256-SHA:!ECDHE-RSA-AES256-SHA384' +
':!ECDHE-ECDSA-AES128-SHA:!ECDHE-ECDSA-AES128-SHA256:!ECDHE-ECDSA-AES256-SHA:!ECDHE-ECDSA-AES256-SHA384' +
':!kRSA';
The default can also be replaced on a per client or server basis using the ciphers option from tls.createSecureContext(), which is also available in tls.createServer(), tls.connect(), and when creating new tls.TLSSockets.
The ciphers list can contain a mixture of TLSv1.3 cipher suite names, the ones that start with 'TLS_', and specifications for TLSv1.2 and below cipher suites. The TLSv1.2 ciphers support a legacy specification format, consult the OpenSSL cipher list format documentation for details, but those specifications do not apply to TLSv1.3 ciphers. The TLSv1.3 suites can only be enabled by including their full name in the cipher list. They cannot, for example, be enabled or disabled by using the legacy TLSv1.2 'EECDH' or '!EECDH' specification.
Despite the relative order of TLSv1.3 and TLSv1.2 cipher suites, the TLSv1.3 protocol is significantly more secure than TLSv1.2, and will always be chosen over TLSv1.2 if the handshake indicates it is supported, and if any TLSv1.3 cipher suites are enabled.
The default cipher suite included within Node.js has been carefully selected to reflect current security best practices and risk mitigation. Changing the default cipher suite can have a significant impact on the security of an application. The --tls-cipher-list switch and ciphers option should by used only if absolutely necessary.
The default cipher suite prefers GCM ciphers for Chrome's 'modern cryptography' setting and also prefers ECDHE and DHE ciphers for perfect forward secrecy, while offering some backward compatibility.
Old clients that rely on insecure and deprecated RC4 or DES-based ciphers (like Internet Explorer 6) cannot complete the handshaking process with the default configuration. If these clients must be supported, the TLS recommendations may offer a compatible cipher suite. For more details on the format, see the OpenSSL cipher list format documentation.
There are only five TLSv1.3 cipher suites:
'TLS_AES_256_GCM_SHA384''TLS_CHACHA20_POLY1305_SHA256''TLS_AES_128_GCM_SHA256''TLS_AES_128_CCM_SHA256''TLS_AES_128_CCM_8_SHA256'
The first three are enabled by default. The two CCM-based suites are supported by TLSv1.3 because they may be more performant on constrained systems, but they are not enabled by default since they offer less security.
OpenSSL security level#
The OpenSSL library enforces security levels to control the minimum acceptable level of security for cryptographic operations. OpenSSL's security levels range from 0 to 5, with each level imposing stricter security requirements. The default security level is 2, which is generally suitable for most modern applications. However, some legacy features and protocols, such as TLSv1, require a lower security level (SECLEVEL=0) to function properly. For more detailed information, please refer to the OpenSSL documentation on security levels.
Setting security levels#
To adjust the security level in your Node.js application, you can include @SECLEVEL=X within a cipher string, where X is the desired security level. For example, to set the security level to 0 while using the default OpenSSL cipher list, you could use:
import { createServer, connect } from 'node:tls'; const port = 443; createServer({ ciphers: 'DEFAULT@SECLEVEL=0', minVersion: 'TLSv1' }, function(socket) { console.log('Client connected with protocol:', socket.getProtocol()); socket.end(); this.close(); }) .listen(port, () => { connect(port, { ciphers: 'DEFAULT@SECLEVEL=0', maxVersion: 'TLSv1' }); });const { createServer, connect } = require('node:tls'); const port = 443; createServer({ ciphers: 'DEFAULT@SECLEVEL=0', minVersion: 'TLSv1' }, function(socket) { console.log('Client connected with protocol:', socket.getProtocol()); socket.end(); this.close(); }) .listen(port, () => { connect(port, { ciphers: 'DEFAULT@SECLEVEL=0', maxVersion: 'TLSv1' }); });
This approach sets the security level to 0, allowing the use of legacy features while still leveraging the default OpenSSL ciphers.
Using --tls-cipher-list#
You can also set the security level and ciphers from the command line using the --tls-cipher-list=DEFAULT@SECLEVEL=X as described in Modifying the default TLS cipher suite. However, it is generally discouraged to use the command line option for setting ciphers and it is preferable to configure the ciphers for individual contexts within your application code, as this approach provides finer control and reduces the risk of globally downgrading the security level.
X509 certificate error codes#
Multiple functions can fail due to certificate errors that are reported by OpenSSL. In such a case, the function provides an <Error> via its callback that has the property code which can take one of the following values:
'UNABLE_TO_GET_ISSUER_CERT': Unable to get issuer certificate.'UNABLE_TO_GET_CRL': Unable to get certificate CRL.'UNABLE_TO_DECRYPT_CERT_SIGNATURE': Unable to decrypt certificate's signature.'UNABLE_TO_DECRYPT_CRL_SIGNATURE': Unable to decrypt CRL's signature.'UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY': Unable to decode issuer public key.'CERT_SIGNATURE_FAILURE': Certificate signature failure.'CRL_SIGNATURE_FAILURE': CRL signature failure.'CERT_NOT_YET_VALID': Certificate is not yet valid.'CERT_HAS_EXPIRED': Certificate has expired.'CRL_NOT_YET_VALID': CRL is not yet valid.'CRL_HAS_EXPIRED': CRL has expired.'ERROR_IN_CERT_NOT_BEFORE_FIELD': Format error in certificate's notBefore field.'ERROR_IN_CERT_NOT_AFTER_FIELD': Format error in certificate's notAfter field.'ERROR_IN_CRL_LAST_UPDATE_FIELD': Format error in CRL's lastUpdate field.'ERROR_IN_CRL_NEXT_UPDATE_FIELD': Format error in CRL's nextUpdate field.'OUT_OF_MEM': Out of memory.'DEPTH_ZERO_SELF_SIGNED_CERT': Self signed certificate.'SELF_SIGNED_CERT_IN_CHAIN': Self signed certificate in certificate chain.'UNABLE_TO_GET_ISSUER_CERT_LOCALLY': Unable to get local issuer certificate.'UNABLE_TO_VERIFY_LEAF_SIGNATURE': Unable to verify the first certificate.'CERT_CHAIN_TOO_LONG': Certificate chain too long.'CERT_REVOKED': Certificate revoked.'INVALID_CA': Invalid CA certificate.'PATH_LENGTH_EXCEEDED': Path length constraint exceeded.'INVALID_PURPOSE': Unsupported certificate purpose.'CERT_UNTRUSTED': Certificate not trusted.'CERT_REJECTED': Certificate rejected.'HOSTNAME_MISMATCH': Hostname mismatch.
When certificate errors like UNABLE_TO_VERIFY_LEAF_SIGNATURE, DEPTH_ZERO_SELF_SIGNED_CERT, or UNABLE_TO_GET_ISSUER_CERT occur, Node.js appends a hint suggesting that if the root CA is installed locally, try running with the --use-system-ca flag to direct developers towards a secure solution, to prevent unsafe workarounds.
Class: tls.Server#
- Extends:
<net.Server>
Accepts encrypted connections using TLS or SSL.
Event: 'connection'#
socket<stream.Duplex>
This event is emitted when a new TCP stream is established, before the TLS handshake begins. socket is typically an object of type net.Socket but will not receive events unlike the socket created from the net.Server 'connection' event. Usually users will not want to access this event.
This event can also be explicitly emitted by users to inject connections into the TLS server. In that case, any Duplex stream can be passed.
Event: 'keylog'#
line<Buffer>Line of ASCII text, in NSSSSLKEYLOGFILEformat.tlsSocket<tls.TLSSocket>Thetls.TLSSocketinstance on which it was generated.
The keylog event is emitted when key material is generated or received by a connection to this server (typically before handshake has completed, but not necessarily). This keying material can be stored for debugging, as it allows captured TLS traffic to be decrypted. It may be emitted multiple times for each socket.
A typical use case is to append received lines to a common text file, which is later used by software (such as Wireshark) to decrypt the traffic:
const logFile = fs.createWriteStream('/tmp/ssl-keys.log', { flags: 'a' });
// ...
server.on('keylog', (line, tlsSocket) => {
if (tlsSocket.remoteAddress !== '...')
return; // Only log keys for a particular IP
logFile.write(line);
});
Event: 'newSession'#
The 'newSession' event is emitted upon creation of a new TLS session. This may be used to store sessions in external storage. The data should be provided to the 'resumeSession' callback.
The listener callback is passed three arguments when called:
sessionId<Buffer>The TLS session identifiersessionData<Buffer>The TLS session datacallback<Function>A callback function taking no arguments that must be invoked in order for data to be sent or received over the secure connection.
Listening for this event will have an effect only on connections established after the addition of the event listener.
Event: 'OCSPRequest'#
The 'OCSPRequest' event is emitted when the client sends a certificate status request. The listener callback is passed three arguments when called:
certificate<Buffer>The server certificateissuer<Buffer>The issuer's certificatecallback<Function>A callback function that must be invoked to provide the results of the OCSP request.
The server's current certificate can be parsed to obtain the OCSP URL and certificate ID; after obtaining an OCSP response, callback(null, resp) is then invoked, where resp is a Buffer instance containing the OCSP response. Both certificate and issuer are Buffer DER-representations of the primary and issuer's certificates. These can be used to obtain the OCSP certificate ID and OCSP endpoint URL.
Alternatively, callback(null, null) may be called, indicating that there was no OCSP response.
Calling callback(err) will result in a socket.destroy(err) call.
The typical flow of an OCSP request is as follows:
- Client connects to the server and sends an
'OCSPRequest'(via the status info extension in ClientHello). - Server receives the request and emits the
'OCSPRequest'event, calling the listener if registered. - Server extracts the OCSP URL from either the
certificateorissuerand performs an OCSP request to the CA. - Server receives
'OCSPResponse'from the CA and sends it back to the client via thecallbackargument - Client validates the response and either destroys the socket or performs a handshake.
The issuer can be null if the certificate is either self-signed or the issuer is not in the root certificates list. (An issuer may be provided via the ca option when establishing the TLS connection.)
Listening for this event will have an effect only on connections established after the addition of the event listener.
An npm module like asn1.js may be used to parse the certificates.
Event: 'resumeSession'#
The 'resumeSession' event is emitted when the client requests to resume a previous TLS session. The listener callback is passed two arguments when called:
sessionId<Buffer>The TLS session identifiercallback<Function>A callback function to be called when the prior session has been recovered:callback([err[, sessionData]])
The event listener should perform a lookup in external storage for the sessionData saved by the 'newSession' event handler using the given sessionId. If found, call callback(null, sessionData) to resume the session. If not found, the session cannot be resumed. callback() must be called without sessionData so that the handshake can continue and a new session can be created. It is possible to call callback(err) to terminate the incoming connection and destroy the socket.
Listening for this event will have an effect only on connections established after the addition of the event listener.
The following illustrates resuming a TLS session:
const tlsSessionStore = {};
server.on('newSession', (id, data, cb) => {
tlsSessionStore[id.toString('hex')] = data;
cb();
});
server.on('resumeSession', (id, cb) => {
cb(null, tlsSessionStore[id.toString('hex')] || null);
});
Event: 'secureConnection'#
The 'secureConnection' event is emitted after the handshaking process for a new connection has successfully completed. The listener callback is passed a single argument when called:
tlsSocket<tls.TLSSocket>The established TLS socket.
The tlsSocket.authorized property is a boolean indicating whether the client has been verified by one of the supplied Certificate Authorities for the server. If tlsSocket.authorized is false, then socket.authorizationError is set to describe how authorization failed. Depending on the settings of the TLS server, unauthorized connections may still be accepted.
The tlsSocket.alpnProtocol property is a string that contains the selected ALPN protocol. When ALPN has no selected protocol because the client or the server did not send an ALPN extension, tlsSocket.alpnProtocol equals false.
The tlsSocket.servername property is a string containing the server name requested via SNI.
Event: 'tlsClientError'#
The 'tlsClientError' event is emitted when an error occurs before a secure connection is established. The listener callback is passed two arguments when called:
exception<Error>TheErrorobject describing the errortlsSocket<tls.TLSSocket>Thetls.TLSSocketinstance from which the error originated.
server.addContext(hostname, context)#
hostname<string>A SNI host name or wildcard (e.g.'*')context<Object>|<tls.SecureContext>An object containing any of the possible properties from thetls.createSecureContext()optionsarguments (e.g.key,cert,ca, etc), or a TLS context object created withtls.createSecureContext()itself.
The server.addContext() method adds a secure context that will be used if the client request's SNI name matches the supplied hostname (or wildcard).
When there are multiple matching contexts, the most recently added one is used.
server.address()#
- Returns:
<Object>
Returns the bound address, the address family name, and port of the server as reported by the operating system. See net.Server.address() for more information.
server.close([callback])#
callback<Function>A listener callback that will be registered to listen for the server instance's'close'event.- Returns:
<tls.Server>
The server.close() method stops the server from accepting new connections.
This function operates asynchronously. The 'close' event will be emitted when the server has no more open connections.
server.getTicketKeys()#
- Returns:
<Buffer>A 48-byte buffer containing the session ticket keys.
Returns the session ticket keys.
See Session Resumption for more information.
server.listen()#
Starts the server listening for encrypted connections. This method is identical to server.listen() from net.Server.
server.setSecureContext(options)#
options<Object>An object containing any of the possible properties from thetls.createSecureContext()optionsarguments (e.g.key,cert,ca, etc).
The server.setSecureContext() method replaces the secure context of an existing server. Existing connections to the server are not interrupted.
server.setTicketKeys(keys)#
keys<Buffer>|<TypedArray>|<DataView>A 48-byte buffer containing the session ticket keys.
Sets the session ticket keys.
Changes to the ticket keys are effective only for future server connections. Existing or currently pending server connections will use the previous keys.
See Session Resumption for more information.
Class: tls.TLSSocket#
- Extends:
<net.Socket>
Performs transparent encryption of written data and all required TLS negotiation.
Instances of tls.TLSSocket implement the duplex Stream interface.
Methods that return TLS connection metadata (e.g. tls.TLSSocket.getPeerCertificate()) will only return data while the connection is open.
new tls.TLSSocket(socket[, options])#
socket<net.Socket>|<stream.Duplex>On the server side, anyDuplexstream. On the client side, any instance ofnet.Socket(for genericDuplexstream support on the client side,tls.connect()must be used).options<Object>enableTrace: Seetls.createServer()isServer: The SSL/TLS protocol is asymmetrical, TLSSockets must know if they are to behave as a server or a client. Iftruethe TLS socket will be instantiated as a server. Default:false.server<net.Server>Anet.Serverinstance.requestCert: Whether to authenticate the remote peer by requesting a certificate. Clients always request a server certificate. Servers (isServeris true) may setrequestCertto true to request a client certificate.rejectUnauthorized: Seetls.createServer()ALPNProtocols: Seetls.createServer()SNICallback: Seetls.createServer()ALPNCallback: Seetls.createServer()session<Buffer>ABufferinstance containing a TLS session.requestOCSP<boolean>Iftrue, specifies that the OCSP status request extension will be added to the client hello and an'OCSPResponse'event will be emitted on the socket before establishing a secure communicationsecureContext: TLS context object created withtls.createSecureContext(). If asecureContextis not provided, one will be created by passing the entireoptionsobject totls.createSecureContext().- ...:
tls.createSecureContext()options that are used if thesecureContextoption is missing. Otherwise, they are ignored.
Construct a new tls.TLSSocket object from an existing TCP socket.
Event: 'keylog'#
line<Buffer>Line of ASCII text, in NSSSSLKEYLOGFILEformat.
The keylog event is emitted on a tls.TLSSocket when key material is generated or received by the socket. This keying material can be stored for debugging, as it allows captured TLS traffic to be decrypted. It may be emitted multiple times, before or after the handshake completes.
A typical use case is to append received lines to a common text file, which is later used by software (such as Wireshark) to decrypt the traffic:
const logFile = fs.createWriteStream('/tmp/ssl-keys.log', { flags: 'a' });
// ...
tlsSocket.on('keylog', (line) => logFile.write(line));
Event: 'OCSPResponse'#
The 'OCSPResponse' event is emitted if the requestOCSP option was set when the tls.TLSSocket was created and an OCSP response has been received. The listener callback is passed a single argument when called:
response<Buffer>The server's OCSP response
Typically, the response is a digitally signed object from the server's CA that contains information about server's certificate revocation status.
Event: 'secure'#
The 'secure' event is emitted after the TLS handshake has successfully completed and a secure connection has been established.
This event is emitted on both client and server <tls.TLSSocket> instances, including sockets created using the new tls.TLSSocket() constructor.
Event: 'secureConnect'#
The 'secureConnect' event is emitted after the handshaking process for a new connection has successfully completed. The listener callback will be called regardless of whether or not the server's certificate has been authorized. It is the client's responsibility to check the tlsSocket.authorized property to determine if the server certificate was signed by one of the specified CAs. If tlsSocket.authorized === false, then the error can be found by examining the tlsSocket.authorizationError property. If ALPN was used, the tlsSocket.alpnProtocol property can be checked to determine the negotiated protocol.
The 'secureConnect' event is not emitted when a <tls.TLSSocket> is created using the new tls.TLSSocket() constructor.
Event: 'session'#
session<Buffer>
The 'session' event is emitted on a client tls.TLSSocket when a new session or TLS ticket is available. This may or may not be before the handshake is complete, depending on the TLS protocol version that was negotiated. The event is not emitted on the server, or if a new session was not created, for example, when the connection was resumed. For some TLS protocol versions the event may be emitted multiple times, in which case all the sessions can be used for resumption.
On the client, the session can be provided to the session option of tls.connect() to resume the connection.
See Session Resumption for more information.
For TLSv1.2 and below, tls.TLSSocket.getSession() can be called once the handshake is complete. For TLSv1.3, only ticket-based resumption is allowed by the protocol, multiple tickets are sent, and the tickets aren't sent until after the handshake completes. So it is necessary to wait for the 'session' event to get a resumable session. Applications should use the 'session' event instead of getSession() to ensure they will work for all TLS versions. Applications that only expect to get or use one session should listen for this event only once:
tlsSocket.once('session', (session) => {
// The session can be used immediately or later.
tls.connect({
session: session,
// Other connect options...
});
});
tlsSocket.address()#
- Returns:
<Object>
Returns the bound address, the address family name, and port of the underlying socket as reported by the operating system: { port: 12346, family: 'IPv4', address: '127.0.0.1' }.
tlsSocket.authorizationError#
Returns the reason why the peer's certificate was not been verified. This property is set only when tlsSocket.authorized === false.
tlsSocket.authorized#
- Type:
<boolean>
This property is true if the peer certificate was signed by one of the CAs specified when creating the tls.TLSSocket instance, otherwise false.
tlsSocket.disableRenegotiation()#
Disables TLS renegotiation for this TLSSocket instance. Once called, attempts to renegotiate will trigger an 'error' event on the TLSSocket.
tlsSocket.enableTrace()#
When enabled, TLS packet trace information is written to stderr. This can be used to debug TLS connection problems.
The format of the output is identical to the output of openssl s_client -trace or openssl s_server -trace. While it is produced by OpenSSL's SSL_trace() function, the format is undocumented, can change without notice, and should not be relied on.
tlsSocket.encrypted#
Always returns true. This may be used to distinguish TLS sockets from regular net.Socket instances.
tlsSocket.exportKeyingMaterial(length, label[, context])#
length<number>number of bytes to retrieve from keying materiallabel<string>an application specific label, typically this will be a value from the IANA Exporter Label Registry.context<Buffer>Optionally provide a context.Returns:
<Buffer>requested bytes of the keying material
Keying material is used for validations to prevent different kind of attacks in network protocols, for example in the specifications of IEEE 802.1X.
Example
const keyingMaterial = tlsSocket.exportKeyingMaterial(
128,
'client finished');
/*
Example return value of keyingMaterial:
<Buffer 76 26 af 99 c5 56 8e 42 09 91 ef 9f 93 cb ad 6c 7b 65 f8 53 f1 d8 d9
12 5a 33 b8 b5 25 df 7b 37 9f e0 e2 4f b8 67 83 a3 2f cd 5d 41 42 4c 91
74 ef 2c ... 78 more bytes>
*/
See the OpenSSL SSL_export_keying_material documentation for more information.
tlsSocket.getCertificate()#
- Returns:
<Object>
Returns an object representing the local certificate. The returned object has some properties corresponding to the fields of the certificate.
See tls.TLSSocket.getPeerCertificate() for an example of the certificate structure.
If there is no local certificate, an empty object will be returned. If the socket has been destroyed, null will be returned.
tlsSocket.getCipher()#
- Returns:
<Object>name<string>OpenSSL name for the cipher suite.standardName<string>IETF name for the cipher suite.version<string>The minimum TLS protocol version supported by this cipher suite. For the actual negotiated protocol, seetls.TLSSocket.getProtocol().
Returns an object containing information on the negotiated cipher suite.
For example, a TLSv1.2 protocol with AES256-SHA cipher:
{
"name": "AES256-SHA",
"standardName": "TLS_RSA_WITH_AES_256_CBC_SHA",
"version": "SSLv3"
}
See SSL_CIPHER_get_name for more information.
tlsSocket.getEphemeralKeyInfo()#
- Returns:
<Object>
Returns an object representing the type, name, and size of parameter of an ephemeral key exchange in perfect forward secrecy on a client connection. It returns an empty object when the key exchange is not ephemeral. As this is only supported on a client socket; null is returned if called on a server socket. The supported types are 'DH' and 'ECDH'. The name property is available only when type is 'ECDH'.
For example: { type: 'ECDH', name: 'prime256v1', size: 256 }.
tlsSocket.getFinished()#
- Returns:
<Buffer>|<undefined>The latestFinishedmessage that has been sent to the socket as part of a SSL/TLS handshake, orundefinedif noFinishedmessage has been sent yet.
As the Finished messages are message digests of the complete handshake (with a total of 192 bits for TLS 1.0 and more for SSL 3.0), they can be used for external authentication procedures when the authentication provided by SSL/TLS is not desired or is not enough.
Corresponds to the SSL_get_finished routine in OpenSSL and may be used to implement the tls-unique channel binding from RFC 5929.
tlsSocket.getPeerCertificate([detailed])#
detailed<boolean>Include the full certificate chain iftrue, otherwise include just the peer's certificate.- Returns:
<Object>A certificate object.
Returns an object representing the peer's certificate. If the peer does not provide a certificate, an empty object will be returned. If the socket has been destroyed, null will be returned.
If the full certificate chain was requested, each certificate will include an issuerCertificate property containing an object representing its issuer's certificate.
Certificate object#
A certificate object has properties corresponding to the fields of the certificate.
ca<boolean>trueif a Certificate Authority (CA),falseotherwise.raw<Buffer>The DER encoded X.509 certificate data.subject<Object>The certificate subject, described in terms of Country (C), StateOrProvince (ST), Locality (L), Organization (O), OrganizationalUnit (OU), and CommonName (CN). The CommonName is typically a DNS name with TLS certificates. Example:{C: 'UK', ST: 'BC', L: 'Metro', O: 'Node Fans', OU: 'Docs', CN: 'example.com'}.issuer<Object>The certificate issuer, described in the same terms as thesubject.valid_from<string>The date-time the certificate is valid from.valid_to<string>The date-time the certificate is valid to.serialNumber<string>The certificate serial number, as a hex string. Example:'B9B0D332A1AA5635'.fingerprint<string>The SHA-1 digest of the DER encoded certificate. It is returned as a:separated hexadecimal string. Example:'2A:7A:C2:DD:...'.fingerprint256<string>The SHA-256 digest of the DER encoded certificate. It is returned as a:separated hexadecimal string. Example:'2A:7A:C2:DD:...'.fingerprint512<string>The SHA-512 digest of the DER encoded certificate. It is returned as a:separated hexadecimal string. Example:'2A:7A:C2:DD:...'.ext_key_usage<Array>(Optional) The extended key usage, a set of OIDs.subjectaltname<string>(Optional) A string containing concatenated names for the subject, an alternative to thesubjectnames.infoAccess<Array>(Optional) An array describing the AuthorityInfoAccess, used with OCSP.issuerCertificate<Object>(Optional) The issuer certificate object. For self-signed certificates, this may be a circular reference.
The certificate may contain information about the public key, depending on the key type.
For RSA keys, the following properties may be defined:
bits<number>The RSA bit size. Example:1024.exponent<string>The RSA exponent, as a string in hexadecimal number notation. Example:'0x010001'.modulus<string>The RSA modulus, as a hexadecimal string. Example:'B56CE45CB7...'.pubkey<Buffer>The public key.
For EC keys, the following properties may be defined:
pubkey<Buffer>The public key.bits<number>The key size in bits. Example:256.asn1Curve<string>(Optional) The ASN.1 name of the OID of the elliptic curve. Well-known curves are identified by an OID. While it is unusual, it is possible that the curve is identified by its mathematical properties, in which case it will not have an OID. Example:'prime256v1'.nistCurve<string>(Optional) The NIST name for the elliptic curve, if it has one (not all well-known curves have been assigned names by NIST). Example:'P-256'.
Example certificate:
{ subject:
{ OU: [ 'Domain Control Validated', 'PositiveSSL Wildcard' ],
CN: '*.nodejs.org' },
issuer:
{ C: 'GB',
ST: 'Greater Manchester',
L: 'Salford',
O: 'COMODO CA Limited',
CN: 'COMODO RSA Domain Validation Secure Server CA' },
subjectaltname: 'DNS:*.nodejs.org, DNS:nodejs.org',
infoAccess:
{ 'CA Issuers - URI':
[ 'http://crt.comodoca.com/COMODORSADomainValidationSecureServerCA.crt' ],
'OCSP - URI': [ 'http://ocsp.comodoca.com' ] },
modulus: 'B56CE45CB740B09A13F64AC543B712FF9EE8E4C284B542A1708A27E82A8D151CA178153E12E6DDA15BF70FFD96CB8A88618641BDFCCA03527E665B70D779C8A349A6F88FD4EF6557180BD4C98192872BCFE3AF56E863C09DDD8BC1EC58DF9D94F914F0369102B2870BECFA1348A0838C9C49BD1C20124B442477572347047506B1FCD658A80D0C44BCC16BC5C5496CFE6E4A8428EF654CD3D8972BF6E5BFAD59C93006830B5EB1056BBB38B53D1464FA6E02BFDF2FF66CD949486F0775EC43034EC2602AEFBF1703AD221DAA2A88353C3B6A688EFE8387811F645CEED7B3FE46E1F8B9F59FAD028F349B9BC14211D5830994D055EEA3D547911E07A0ADDEB8A82B9188E58720D95CD478EEC9AF1F17BE8141BE80906F1A339445A7EB5B285F68039B0F294598A7D1C0005FC22B5271B0752F58CCDEF8C8FD856FB7AE21C80B8A2CE983AE94046E53EDE4CB89F42502D31B5360771C01C80155918637490550E3F555E2EE75CC8C636DDE3633CFEDD62E91BF0F7688273694EEEBA20C2FC9F14A2A435517BC1D7373922463409AB603295CEB0BB53787A334C9CA3CA8B30005C5A62FC0715083462E00719A8FA3ED0A9828C3871360A73F8B04A4FC1E71302844E9BB9940B77E745C9D91F226D71AFCAD4B113AAF68D92B24DDB4A2136B55A1CD1ADF39605B63CB639038ED0F4C987689866743A68769CC55847E4A06D6E2E3F1',
exponent: '0x10001',
pubkey: <Buffer ... >,
valid_from: 'Aug 14 00:00:00 2017 GMT',
valid_to: 'Nov 20 23:59:59 2019 GMT',
fingerprint: '01:02:59:D9:C3:D2:0D:08:F7:82:4E:44:A4:B4:53:C5:E2:3A:87:4D',
fingerprint256: '69:AE:1A:6A:D4:3D:C6:C1:1B:EA:C6:23:DE:BA:2A:14:62:62:93:5C:7A:EA:06:41:9B:0B:BC:87:CE:48:4E:02',
fingerprint512: '19:2B:3E:C3:B3:5B:32:E8:AE:BB:78:97:27:E4:BA:6C:39:C9:92:79:4F:31:46:39:E2:70:E5:5F:89:42:17:C9:E8:64:CA:FF:BB:72:56:73:6E:28:8A:92:7E:A3:2A:15:8B:C2:E0:45:CA:C3:BC:EA:40:52:EC:CA:A2:68:CB:32',
ext_key_usage: [ '1.3.6.1.5.5.7.3.1', '1.3.6.1.5.5.7.3.2' ],
serialNumber: '66593D57F20CBC573E433381B5FEC280',
raw: <Buffer ... > }
tlsSocket.getPeerFinished()#
- Returns:
<Buffer>|<undefined>The latestFinishedmessage that is expected or has actually been received from the socket as part of a SSL/TLS handshake, orundefinedif there is noFinishedmessage so far.
As the Finished messages are message digests of the complete handshake (with a total of 192 bits for TLS 1.0 and more for SSL 3.0), they can be used for external authentication procedures when the authentication provided by SSL/TLS is not desired or is not enough.
Corresponds to the SSL_get_peer_finished routine in OpenSSL and may be used to implement the tls-unique channel binding from RFC 5929.
tlsSocket.getPeerX509Certificate()#
- Returns:
<X509Certificate>
Returns the peer certificate as an <X509Certificate> object.
If there is no peer certificate, or the socket has been destroyed, undefined will be returned.
tlsSocket.getProtocol()#
Returns a string containing the negotiated SSL/TLS protocol version of the current connection. The value 'unknown' will be returned for connected sockets that have not completed the handshaking process. The value null will be returned for server sockets or disconnected client sockets.
Protocol versions are:
'SSLv3''TLSv1''TLSv1.1''TLSv1.2''TLSv1.3'
See the OpenSSL SSL_get_version documentation for more information.
tlsSocket.getSession()#
- Type:
<Buffer>
Returns the TLS session data or undefined if no session was negotiated. On the client, the data can be provided to the session option of tls.connect() to resume the connection. On the server, it may be useful for debugging.
See Session Resumption for more information.
Note: getSession() works only for TLSv1.2 and below. For TLSv1.3, applications must use the 'session' event (it also works for TLSv1.2 and below).
tlsSocket.getSharedSigalgs()#
- Returns:
<Array>List of signature algorithms shared between the server and the client in the order of decreasing preference.
See SSL_get_shared_sigalgs for more information.
tlsSocket.getTLSTicket()#
- Type:
<Buffer>
For a client, returns the TLS session ticket if one is available, or undefined. For a server, always returns undefined.
It may be useful for debugging.
See Session Resumption for more information.
tlsSocket.getX509Certificate()#
- Returns:
<X509Certificate>
Returns the local certificate as an <X509Certificate> object.
If there is no local certificate, or the socket has been destroyed, undefined will be returned.
tlsSocket.isSessionReused()#
- Returns:
<boolean>trueif the session was reused,falseotherwise.
See Session Resumption for more information.
tlsSocket.localAddress#
- Type:
<string>
Returns the string representation of the local IP address.
tlsSocket.localPort#
- Type:
<integer>
Returns the numeric representation of the local port.
tlsSocket.remoteAddress#
- Type:
<string>
Returns the string representation of the remote IP address. For example, '74.125.127.100' or '2001:4860:a005::68'.
tlsSocket.remoteFamily#
- Type:
<string>
Returns the string representation of the remote IP family. 'IPv4' or 'IPv6'.
tlsSocket.remotePort#
- Type:
<integer>
Returns the numeric representation of the remote port. For example, 443.
tlsSocket.renegotiate(options, callback)#
options<Object>rejectUnauthorized<boolean>If notfalse, the server certificate is verified against the list of supplied CAs. An'error'event is emitted if verification fails;err.codecontains the OpenSSL error code. Default:true.requestCert
callback<Function>Ifrenegotiate()returnedtrue, callback is attached once to the'secure'event. Ifrenegotiate()returnedfalse,callbackwill be called in the next tick with an error, unless thetlsSockethas been destroyed, in which casecallbackwill not be called at all.Returns:
<boolean>trueif renegotiation was initiated,falseotherwise.
The tlsSocket.renegotiate() method initiates a TLS renegotiation process. Upon completion, the callback function will be passed a single argument that is either an Error (if the request failed) or null.
This method can be used to request a peer's certificate after the secure connection has been established.
When running as the server, the socket will be destroyed with an error after handshakeTimeout timeout.
For TLSv1.3, renegotiation cannot be initiated, it is not supported by the protocol.
tlsSocket.setKeyCert(context)#
context<Object>|<tls.SecureContext>An object containing at leastkeyandcertproperties from thetls.createSecureContext()options, or a TLS context object created withtls.createSecureContext()itself.
The tlsSocket.setKeyCert() method sets the private key and certificate to use for the socket. This is mainly useful if you wish to select a server certificate from a TLS server's ALPNCallback.
tlsSocket.setMaxSendFragment(size)#
size<number>The maximum TLS fragment size. The maximum value is16384. Default:16384.- Returns:
<boolean>
The tlsSocket.setMaxSendFragment() method sets the maximum TLS fragment size. Returns true if setting the limit succeeded; false otherwise.
Smaller fragment sizes decrease the buffering latency on the client: larger fragments are buffered by the TLS layer until the entire fragment is received and its integrity is verified; large fragments can span multiple roundtrips and their processing can be delayed due to packet loss or reordering. However, smaller fragments add extra TLS framing bytes and CPU overhead, which may decrease overall server throughput.
tls.checkServerIdentity(hostname, cert)#
hostname<string>The host name or IP address to verify the certificate against.cert<Object>A certificate object representing the peer's certificate.- Returns:
<Error>|<undefined>
Verifies the certificate cert is issued to hostname.
Returns <Error> object, populating it with reason, host, and cert on failure. On success, returns <undefined>.
This function is intended to be used in combination with the checkServerIdentity option that can be passed to tls.connect() and as such operates on a certificate object. For other purposes, consider using x509.checkHost() instead.
This function can be overwritten by providing an alternative function as the options.checkServerIdentity option that is passed to tls.connect(). The overwriting function can call tls.checkServerIdentity() of course, to augment the checks done with additional verification.
This function is only called if the certificate passed all other checks, such as being issued by trusted CA (options.ca).
Earlier versions of Node.js incorrectly accepted certificates for a given hostname if a matching uniformResourceIdentifier subject alternative name was present (see CVE-2021-44531). Applications that wish to accept uniformResourceIdentifier subject alternative names can use a custom options.checkServerIdentity function that implements the desired behavior.
tls.connect(options[, callback])#
options<Object>enableTrace: Seetls.createServer()host<string>Host the client should connect to. Default:'localhost'.port<number>Port the client should connect to.path<string>Creates Unix socket connection to path. If this option is specified,hostandportare ignored.socket<stream.Duplex>Establish secure connection on a given socket rather than creating a new socket. Typically, this is an instance ofnet.Socket, but anyDuplexstream is allowed. If this option is specified,path,host, andportare ignored, except for certificate validation. Usually, a socket is already connected when passed totls.connect(), but it can be connected later. Connection/disconnection/destruction ofsocketis the user's responsibility; callingtls.connect()will not causenet.connect()to be called.allowHalfOpen<boolean>If set tofalse, then the socket will automatically end the writable side when the readable side ends. If thesocketoption is set, this option has no effect. See theallowHalfOpenoption ofnet.Socketfor details. Default:false.rejectUnauthorized<boolean>If notfalse, the server certificate is verified against the list of supplied CAs. An'error'event is emitted if verification fails;err.codecontains the OpenSSL error code. Default:true.pskCallback<Function>For TLS-PSK negotiation, see Pre-shared keys.ALPNProtocols<string[]>|<Buffer>|<TypedArray>|<DataView>An array of strings, or a singleBuffer,TypedArray, orDataViewcontaining the supported ALPN protocols. Buffers should have the format[len][name][len][name]...e.g.'\x08http/1.1\x08http/1.0', where thelenbyte is the length of the next protocol name. Passing an array is usually much simpler, e.g.['http/1.1', 'http/1.0']. Protocols earlier in the list have higher preference than those later.servername<string>Server name for the SNI (Server Name Indication) TLS extension. It is the name of the host being connected to, and must be a host name, and not an IP address. It can be used by a multi-homed server to choose the correct certificate to present to the client, see theSNICallbackoption totls.createServer().checkServerIdentity(servername, cert)<Function>A callback function to be used (instead of the builtintls.checkServerIdentity()function) when checking the server's host name (or the providedservernamewhen explicitly set) against the certificate. This should return an<Error>if verification fails. The method should returnundefinedif theservernameandcertare verified.session<Buffer>ABufferinstance, containing TLS session.requestOCSP<boolean>Iftrue, specifies that the OCSP status request extension will be added to the client hello and an'OCSPResponse'event will be emitted on the socket before establishing a secure communication.minDHSize<number>Minimum size of the DH parameter in bits to accept a TLS connection. When a server offers a DH parameter with a size less thanminDHSize, the TLS connection is destroyed and an error is thrown. Default:1024.highWaterMark<number>Consistent with the readable streamhighWaterMarkparameter. Default:16 * 1024.timeout:<number>If set and if a socket is created internally, will callsocket.setTimeout(timeout)after the socket is created, but before it starts the connection.secureContext: TLS context object created withtls.createSecureContext(). If asecureContextis not provided, one will be created by passing the entireoptionsobject totls.createSecureContext().onread<Object>If thesocketoption is missing, incoming data is stored in a singlebufferand passed to the suppliedcallbackwhen data arrives on the socket, otherwise the option is ignored. See theonreadoption ofnet.Socketfor details.- ...:
tls.createSecureContext()options that are used if thesecureContextoption is missing, otherwise they are ignored. - ...: Any
socket.connect()option not already listed.
callback<Function>- Returns:
<tls.TLSSocket>
The callback function, if specified, will be added as a listener for the 'secureConnect' event.
tls.connect() returns a tls.TLSSocket object.
Unlike the https API, tls.connect() does not enable the SNI (Server Name Indication) extension by default, which may cause some servers to return an incorrect certificate or reject the connection altogether. To enable SNI, set the servername option in addition to host.
The following illustrates a client for the echo server example from tls.createServer():
// Assumes an echo server that is listening on port 8000. import { connect } from 'node:tls'; import { readFileSync } from 'node:fs'; import { stdin } from 'node:process'; const options = { // Necessary only if the server requires client certificate authentication. key: readFileSync('client-key.pem'), cert: readFileSync('client-cert.pem'), // Necessary only if the server uses a self-signed certificate. ca: [ readFileSync('server-cert.pem') ], // Necessary only if the server's cert isn't for "localhost". checkServerIdentity: () => { return null; }, }; const socket = connect(8000, options, () => { console.log('client connected', socket.authorized ? 'authorized' : 'unauthorized'); stdin.pipe(socket); stdin.resume(); }); socket.setEncoding('utf8'); socket.on('data', (data) => { console.log(data); }); socket.on('end', () => { console.log('server ends connection'); });// Assumes an echo server that is listening on port 8000. const { connect } = require('node:tls'); const { readFileSync } = require('node:fs'); const options = { // Necessary only if the server requires client certificate authentication. key: readFileSync('client-key.pem'), cert: readFileSync('client-cert.pem'), // Necessary only if the server uses a self-signed certificate. ca: [ readFileSync('server-cert.pem') ], // Necessary only if the server's cert isn't for "localhost". checkServerIdentity: () => { return null; }, }; const socket = connect(8000, options, () => { console.log('client connected', socket.authorized ? 'authorized' : 'unauthorized'); process.stdin.pipe(socket); process.stdin.resume(); }); socket.setEncoding('utf8'); socket.on('data', (data) => { console.log(data); }); socket.on('end', () => { console.log('server ends connection'); });
To generate the certificate and key for this example, run:
openssl req -x509 -newkey rsa:2048 -nodes -sha256 -subj '/CN=localhost' \
-keyout client-key.pem -out client-cert.pem
Then, to generate the server-cert.pem certificate for this example, run:
openssl pkcs12 -certpbe AES-256-CBC -export -out server-cert.pem \
-inkey client-key.pem -in client-cert.pem
tls.connect(path[, options][, callback])#
path<string>Default value foroptions.path.options<Object>Seetls.connect().callback<Function>Seetls.connect().- Returns:
<tls.TLSSocket>
Same as tls.connect() except that path can be provided as an argument instead of an option.
A path option, if specified, will take precedence over the path argument.
tls.connect(port[, host][, options][, callback])#
port<number>Default value foroptions.port.host<string>Default value foroptions.host.options<Object>Seetls.connect().callback<Function>Seetls.connect().- Returns:
<tls.TLSSocket>
Same as tls.connect() except that port and host can be provided as arguments instead of options.
A port or host option, if specified, will take precedence over any port or host argument.
tls.createSecureContext([options])#
options<Object>allowPartialTrustChain<boolean>Treat intermediate (non-self-signed) certificates in the trust CA certificate list as trusted.ca<string>|<string[]>|<Buffer>|<Buffer[]>Optionally override the trusted CA certificates. If not specified, the CA certificates trusted by default are the same as the ones returned bytls.getCACertificates()using thedefaulttype. If specified, the default list would be completely replaced (instead of being concatenated) by the certificates in thecaoption. Users need to concatenate manually if they wish to add additional certificates instead of completely overriding the default. The value can be a string orBuffer, or anArrayof strings and/orBuffers. Any string orBuffercan contain multiple PEM CAs concatenated together. The peer's certificate must be chainable to a CA trusted by the server for the connection to be authenticated. When using certificates that are not chainable to a well-known CA, the certificate's CA must be explicitly specified as a trusted or the connection will fail to authenticate. If the peer uses a certificate that doesn't match or chain to one of the default CAs, use thecaoption to provide a CA certificate that the peer's certificate can match or chain to. For self-signed certificates, the certificate is its own CA, and must be provided. For PEM encoded certificates, supported types are "TRUSTED CERTIFICATE", "X509 CERTIFICATE", and "CERTIFICATE".cert<string>|<string[]>|<Buffer>|<Buffer[]>Cert chains in PEM format. One cert chain should be provided per private key. Each cert chain should consist of the PEM formatted certificate for a provided privatekey, followed by the PEM formatted intermediate certificates (if any), in order, and not including the root CA (the root CA must be pre-known to the peer, seeca). When providing multiple cert chains, they do not have to be in the same order as their private keys inkey. If the intermediate certificates are not provided, the peer will not be able to validate the certificate, and the handshake will fail.sigalgs<string>Colon-separated list of supported signature algorithms. The list can contain digest algorithms (SHA256,MD5etc.), public key algorithms (RSA-PSS,ECDSAetc.), combination of both (e.g 'RSA+SHA384') or TLS v1.3 scheme names (e.g.rsa_pss_pss_sha512). See OpenSSL man pages for more info.ciphers<string>Cipher suite specification, replacing the default. For more information, see Modifying the default TLS cipher suite. Permitted ciphers can be obtained viatls.getCiphers(). Cipher names must be uppercased in order for OpenSSL to accept them.clientCertEngine<string>Name of an OpenSSL engine which can provide the client certificate. Deprecated.crl<string>|<string[]>|<Buffer>|<Buffer[]>PEM formatted CRLs (Certificate Revocation Lists).dhparam<string>|<Buffer>'auto'or custom Diffie-Hellman parameters, required for non-ECDHE perfect forward secrecy. If omitted or invalid, the parameters are silently discarded and DHE ciphers will not be available. ECDHE-based perfect forward secrecy will still be available.ecdhCurve<string>A string describing a named curve or a colon separated list of curve NIDs or names, for exampleP-521:P-384:P-256, to use for ECDH key agreement. Set toautoto select the curve automatically. Usecrypto.getCurves()to obtain a list of available curve names. On recent releases,openssl ecparam -list_curveswill also display the name and description of each available elliptic curve. Default:tls.DEFAULT_ECDH_CURVE.honorCipherOrder<boolean>Attempt to use the server's cipher suite preferences instead of the client's. Whentrue, causesSSL_OP_CIPHER_SERVER_PREFERENCEto be set insecureOptions, see OpenSSL Options for more information.key<string>|<string[]>|<Buffer>|<Buffer[]>|<Object[]>Private keys in PEM format. PEM allows the option of private keys being encrypted. Encrypted keys will be decrypted withoptions.passphrase. Multiple keys using different algorithms can be provided either as an array of unencrypted key strings or buffers, or an array of objects in the form{pem: <string|buffer>[, passphrase: <string>]}. The object form can only occur in an array.object.passphraseis optional. Encrypted keys will be decrypted withobject.passphraseif provided, oroptions.passphraseif it is not.privateKeyEngine<string>Name of an OpenSSL engine to get private key from. Should be used together withprivateKeyIdentifier. Deprecated.privateKeyIdentifier<string>Identifier of a private key managed by an OpenSSL engine. Should be used together withprivateKeyEngine. Should not be set together withkey, because both options define a private key in different ways. Deprecated.maxVersion<string>Optionally set the maximum TLS version to allow. One of'TLSv1.3','TLSv1.2','TLSv1.1', or'TLSv1'. Cannot be specified along with thesecureProtocoloption; use one or the other. Default:tls.DEFAULT_MAX_VERSION.minVersion<string>Optionally set the minimum TLS version to allow. One of'TLSv1.3','TLSv1.2','TLSv1.1', or'TLSv1'. Cannot be specified along with thesecureProtocoloption; use one or the other. Avoid setting to less than TLSv1.2, but it may be required for interoperability. Versions before TLSv1.2 may require downgrading the OpenSSL Security Level. Default:tls.DEFAULT_MIN_VERSION.passphrase<string>Shared passphrase used for a single private key and/or a PFX.pfx<string>|<string[]>|<Buffer>|<Buffer[]>|<Object[]>PFX or PKCS12 encoded private key and certificate chain.pfxis an alternative to providingkeyandcertindividually. PFX is usually encrypted, if it is,passphrasewill be used to decrypt it. Multiple PFX can be provided either as an array of unencrypted PFX buffers, or an array of objects in the form{buf: <string|buffer>[, passphrase: <string>]}. The object form can only occur in an array.object.passphraseis optional. Encrypted PFX will be decrypted withobject.passphraseif provided, oroptions.passphraseif it is not.secureOptions<number>Optionally affect the OpenSSL protocol behavior, which is not usually necessary. This should be used carefully if at all! Value is a numeric bitmask of theSSL_OP_*options from OpenSSL Options.secureProtocol<string>Legacy mechanism to select the TLS protocol version to use, it does not support independent control of the minimum and maximum version, and does not support limiting the protocol to TLSv1.3. UseminVersionandmaxVersioninstead. The possible values are listed as SSL_METHODS, use the function names as strings. For example, use'TLSv1_1_method'to force TLS version 1.1, or'TLS_method'to allow any TLS protocol version up to TLSv1.3. It is not recommended to use TLS versions less than 1.2, but it may be required for interoperability. Default: none, seeminVersion.sessionIdContext<string>Opaque identifier used by servers to ensure session state is not shared between applications. Unused by clients.ticketKeys<Buffer>48-bytes of cryptographically strong pseudorandom data. See Session Resumption for more information.sessionTimeout<number>The number of seconds after which a TLS session created by the server will no longer be resumable. See Session Resumption for more information. Default:300.
tls.createServer() sets the default value of the honorCipherOrder option to true, other APIs that create secure contexts leave it unset.
tls.createServer() uses a 128 bit truncated SHA1 hash value generated from process.argv as the default value of the sessionIdContext option, other APIs that create secure contexts have no default value.
The tls.createSecureContext() method creates a SecureContext object. It is usable as an argument to several tls APIs, such as server.addContext(), but has no public methods. The tls.Server constructor and the tls.createServer() method do not support the secureContext option.
A key is required for ciphers that use certificates. Either key or pfx can be used to provide it.
If the ca option is not given, then Node.js will default to using Mozilla's publicly trusted list of CAs.
Custom DHE parameters are discouraged in favor of the new dhparam: 'auto' option. When set to 'auto', well-known DHE parameters of sufficient strength will be selected automatically. Otherwise, if necessary, openssl dhparam can be used to create custom parameters. The key length must be greater than or equal to 1024 bits or else an error will be thrown. Although 1024 bits is permissible, use 2048 bits or larger for stronger security.
tls.createServer([options][, secureConnectionListener])#
options<Object>ALPNProtocols<string[]>|<Buffer>|<TypedArray>|<DataView>An array of strings, or a singleBuffer,TypedArray, orDataViewcontaining the supported ALPN protocols. Buffers should have the format[len][name][len][name]...e.g.0x05hello0x05world, where the first byte is the length of the next protocol name. Passing an array is usually much simpler, e.g.['hello', 'world']. (Protocols should be ordered by their priority.)ALPNCallback<Function>If set, this will be called when a client opens a connection using the ALPN extension. One argument will be passed to the callback: an object containingservernameandprotocolsfields, respectively containing the server name from the SNI extension (if any) and an array of ALPN protocol name strings. The callback must return either one of the strings listed inprotocols, which will be returned to the client as the selected ALPN protocol, orundefined, to reject the connection with a fatal alert. If a string is returned that does not match one of the client's ALPN protocols, an error will be thrown. This option cannot be used with theALPNProtocolsoption, and setting both options will throw an error.clientCertEngine<string>Name of an OpenSSL engine which can provide the client certificate. Deprecated.enableTrace<boolean>Iftrue,tls.TLSSocket.enableTrace()will be called on new connections. Tracing can be enabled after the secure connection is established, but this option must be used to trace the secure connection setup. Default:false.handshakeTimeout<number>Abort the connection if the SSL/TLS handshake does not finish in the specified number of milliseconds. A'tlsClientError'is emitted on thetls.Serverobject whenever a handshake times out. Default:120000(120 seconds).rejectUnauthorized<boolean>If notfalsethe server will reject any connection which is not authorized with the list of supplied CAs. This option only has an effect ifrequestCertistrue. Default:true.requestCert<boolean>Iftruethe server will request a certificate from clients that connect and attempt to verify that certificate. Default:false.sessionTimeout<number>The number of seconds after which a TLS session created by the server will no longer be resumable. See Session Resumption for more information. Default:300.SNICallback(servername, callback)<Function>A function that will be called if the client supports SNI TLS extension. Two arguments will be passed when called:servernameandcallback.callbackis an error-first callback that takes two optional arguments:errorandctx.ctx, if provided, is aSecureContextinstance.tls.createSecureContext()can be used to get a properSecureContext. Ifcallbackis called with a falsyctxargument, the default secure context of the server will be used. IfSNICallbackwasn't provided the default callback with high-level API will be used (see below).ticketKeys<Buffer>48-bytes of cryptographically strong pseudorandom data. See Session Resumption for more information.pskCallback<Function>For TLS-PSK negotiation, see Pre-shared keys.pskIdentityHint<string>optional hint to send to a client to help with selecting the identity during TLS-PSK negotiation. Will be ignored in TLS 1.3. Upon failing to set pskIdentityHint'tlsClientError'will be emitted with'ERR_TLS_PSK_SET_IDENTITY_HINT_FAILED'code.- ...: Any
tls.createSecureContext()option can be provided. For servers, the identity options (pfx,key/cert, orpskCallback) are usually required. - ...: Any
net.createServer()option can be provided.
secureConnectionListener<Function>- Returns:
<tls.Server>
Creates a new tls.Server. The secureConnectionListener, if provided, is automatically set as a listener for the 'secureConnection' event.
The ticketKeys options is automatically shared between node:cluster module workers.
The following illustrates a simple echo server:
import { createServer } from 'node:tls'; import { readFileSync } from 'node:fs'; const options = { key: readFileSync('server-key.pem'), cert: readFileSync('server-cert.pem'), // This is necessary only if using client certificate authentication. requestCert: true, // This is necessary only if the client uses a self-signed certificate. ca: [ readFileSync('client-cert.pem') ], }; const server = createServer(options, (socket) => { console.log('server connected', socket.authorized ? 'authorized' : 'unauthorized'); socket.write('welcome!\n'); socket.setEncoding('utf8'); socket.pipe(socket); }); server.listen(8000, () => { console.log('server bound'); });const { createServer } = require('node:tls'); const { readFileSync } = require('node:fs'); const options = { key: readFileSync('server-key.pem'), cert: readFileSync('server-cert.pem'), // This is necessary only if using client certificate authentication. requestCert: true, // This is necessary only if the client uses a self-signed certificate. ca: [ readFileSync('client-cert.pem') ], }; const server = createServer(options, (socket) => { console.log('server connected', socket.authorized ? 'authorized' : 'unauthorized'); socket.write('welcome!\n'); socket.setEncoding('utf8'); socket.pipe(socket); }); server.listen(8000, () => { console.log('server bound'); });
To generate the certificate and key for this example, run:
openssl req -x509 -newkey rsa:2048 -nodes -sha256 -subj '/CN=localhost' \
-keyout server-key.pem -out server-cert.pem
Then, to generate the client-cert.pem certificate for this example, run:
openssl pkcs12 -certpbe AES-256-CBC -export -out client-cert.pem \
-inkey server-key.pem -in server-cert.pem
The server can be tested by connecting to it using the example client from tls.connect().
tls.setDefaultCACertificates(certs)#
certs<string[]>|<ArrayBufferView[]>An array of CA certificates in PEM format.
Sets the default CA certificates used by Node.js TLS clients. If the provided certificates are parsed successfully, they will become the default CA certificate list returned by tls.getCACertificates() and used by subsequent TLS connections that don't specify their own CA certificates. The certificates will be deduplicated before being set as the default.
This function only affects the current Node.js thread. Previous sessions cached by the HTTPS agent won't be affected by this change, so this method should be called before any unwanted cachable TLS connections are made.
To use system CA certificates as the default:
const tls = require('node:tls'); tls.setDefaultCACertificates(tls.getCACertificates('system'));import tls from 'node:tls'; tls.setDefaultCACertificates(tls.getCACertificates('system'));
This function completely replaces the default CA certificate list. To add additional certificates to the existing defaults, get the current certificates and append to them:
const tls = require('node:tls'); const currentCerts = tls.getCACertificates('default'); const additionalCerts = ['-----BEGIN CERTIFICATE-----\n...']; tls.setDefaultCACertificates([...currentCerts, ...additionalCerts]);import tls from 'node:tls'; const currentCerts = tls.getCACertificates('default'); const additionalCerts = ['-----BEGIN CERTIFICATE-----\n...']; tls.setDefaultCACertificates([...currentCerts, ...additionalCerts]);
tls.getCACertificates([type])#
type<string>|<undefined>The type of CA certificates that will be returned. Valid values are"default","system","bundled"and"extra". Default:"default".- Returns:
<string[]>An array of PEM-encoded certificates. The array may contain duplicates if the same certificate is repeatedly stored in multiple sources.
Returns an array containing the CA certificates from various sources, depending on type:
"default": return the CA certificates that will be used by the Node.js TLS clients by default.- When
--use-bundled-cais enabled (default), or--use-openssl-cais not enabled, this would include CA certificates from the bundled Mozilla CA store. - When
--use-system-cais enabled, this would also include certificates from the system's trusted store. - When
NODE_EXTRA_CA_CERTSis used, this would also include certificates loaded from the specified file.
- When
"system": return the CA certificates that are loaded from the system's trusted store, according to rules set by--use-system-ca. This can be used to get the certificates from the system when--use-system-cais not enabled."bundled": return the CA certificates from the bundled Mozilla CA store. This would be the same astls.rootCertificates."extra": return the CA certificates loaded fromNODE_EXTRA_CA_CERTS. It's an empty array ifNODE_EXTRA_CA_CERTSis not set.
tls.getCiphers()#
- Returns:
<string[]>
Returns an array with the names of the supported TLS ciphers. The names are lower-case for historical reasons, but must be uppercased to be used in the ciphers option of tls.createSecureContext().
Not all supported ciphers are enabled by default. See Modifying the default TLS cipher suite.
Cipher names that start with 'tls_' are for TLSv1.3, all the others are for TLSv1.2 and below.
console.log(tls.getCiphers()); // ['aes128-gcm-sha256', 'aes128-sha', ...]
tls.rootCertificates#
- Type:
<string[]>
An immutable array of strings representing the root certificates (in PEM format) from the bundled Mozilla CA store as supplied by the current Node.js version.
The bundled CA store, as supplied by Node.js, is a snapshot of Mozilla CA store that is fixed at release time. It is identical on all supported platforms.
To get the actual CA certificates used by the current Node.js instance, which may include certificates loaded from the system store (if --use-system-ca is used) or loaded from a file indicated by NODE_EXTRA_CA_CERTS, use tls.getCACertificates().
tls.DEFAULT_ECDH_CURVE#
The default curve name to use for ECDH key agreement in a tls server. The default value is 'auto'. See tls.createSecureContext() for further information.
tls.DEFAULT_MAX_VERSION#
- Type:
<string>The default value of themaxVersionoption oftls.createSecureContext(). It can be assigned any of the supported TLS protocol versions,'TLSv1.3','TLSv1.2','TLSv1.1', or'TLSv1'. Default:'TLSv1.3', unless changed using CLI options. Using--tls-max-v1.2sets the default to'TLSv1.2'. Using--tls-max-v1.3sets the default to'TLSv1.3'. If multiple of the options are provided, the highest maximum is used.
tls.DEFAULT_MIN_VERSION#
- Type:
<string>The default value of theminVersionoption oftls.createSecureContext(). It can be assigned any of the supported TLS protocol versions,'TLSv1.3','TLSv1.2','TLSv1.1', or'TLSv1'. Versions before TLSv1.2 may require downgrading the OpenSSL Security Level. Default:'TLSv1.2', unless changed using CLI options. Using--tls-min-v1.0sets the default to'TLSv1'. Using--tls-min-v1.1sets the default to'TLSv1.1'. Using--tls-min-v1.3sets the default to'TLSv1.3'. If multiple of the options are provided, the lowest minimum is used.
tls.DEFAULT_CIPHERS#
- Type:
<string>The default value of theciphersoption oftls.createSecureContext(). It can be assigned any of the supported OpenSSL ciphers. Defaults to the content ofcrypto.constants.defaultCoreCipherList, unless changed using CLI options using--tls-default-ciphers.
Trace events#
Stability: 1 - Experimental
The node:trace_events module provides a mechanism to centralize tracing information generated by V8, Node.js core, and userspace code.
Tracing can be enabled with the --trace-event-categories command-line flag or by using the node:trace_events module. The --trace-event-categories flag accepts a list of comma-separated category names.
The available categories are:
node: An empty placeholder.node.async_hooks: Enables capture of detailedasync_hookstrace data. Theasync_hooksevents have a uniqueasyncIdand a specialtriggerIdtriggerAsyncIdproperty.node.bootstrap: Enables capture of Node.js bootstrap milestones.node.console: Enables capture ofconsole.time()andconsole.count()output.node.threadpoolwork.sync: Enables capture of trace data for threadpool synchronous operations, such asblob,zlib,cryptoandnode_api.node.threadpoolwork.async: Enables capture of trace data for threadpool asynchronous operations, such asblob,zlib,cryptoandnode_api.node.dns.native: Enables capture of trace data for DNS queries.node.net.native: Enables capture of trace data for network.node.environment: Enables capture of Node.js Environment milestones.node.fs.sync: Enables capture of trace data for file system sync methods.node.fs_dir.sync: Enables capture of trace data for file system sync directory methods.node.fs.async: Enables capture of trace data for file system async methods.node.fs_dir.async: Enables capture of trace data for file system async directory methods.node.perf: Enables capture of Performance API measurements.node.perf.usertiming: Enables capture of only Performance API User Timing measures and marks.node.perf.timerify: Enables capture of only Performance API timerify measurements.
node.promises.rejections: Enables capture of trace data tracking the number of unhandled Promise rejections and handled-after-rejections.node.vm.script: Enables capture of trace data for thenode:vmmodule'srunInNewContext(),runInContext(), andrunInThisContext()methods.v8: The V8 events are GC, compiling, and execution related.node.http: Enables capture of trace data for http request / response.node.module_timer: Enables capture of trace data for CJS Module loading.
By default the node, node.async_hooks, and v8 categories are enabled.
node --trace-event-categories v8,node,node.async_hooks server.js
Prior versions of Node.js required the use of the --trace-events-enabled flag to enable trace events. This requirement has been removed. However, the --trace-events-enabled flag may still be used and will enable the node, node.async_hooks, and v8 trace event categories by default.
node --trace-events-enabled
# is equivalent to
node --trace-event-categories v8,node,node.async_hooks
Alternatively, trace events may be enabled using the node:trace_events module:
import { createTracing } from 'node:trace_events'; const tracing = createTracing({ categories: ['node.perf'] }); tracing.enable(); // Enable trace event capture for the 'node.perf' category // do work tracing.disable(); // Disable trace event capture for the 'node.perf' categoryconst { createTracing } = require('node:trace_events'); const tracing = createTracing({ categories: ['node.perf'] }); tracing.enable(); // Enable trace event capture for the 'node.perf' category // do work tracing.disable(); // Disable trace event capture for the 'node.perf' category
Running Node.js with tracing enabled will produce log files that can be opened in the chrome://tracing tab of Chrome.
The logging file is by default called node_trace.${rotation}.log, where ${rotation} is an incrementing log-rotation id. The filepath pattern can be specified with --trace-event-file-pattern that accepts a template string that supports ${rotation} and ${pid}:
node --trace-event-categories v8 --trace-event-file-pattern '${pid}-${rotation}.log' server.js
To guarantee that the log file is properly generated after signal events like SIGINT, SIGTERM, or SIGBREAK, make sure to have the appropriate handlers in your code, such as:
process.on('SIGINT', function onSigint() {
console.info('Received SIGINT.');
process.exit(130); // Or applicable exit code depending on OS and signal
});
The tracing system uses the same time source as the one used by process.hrtime(). However the trace-event timestamps are expressed in microseconds, unlike process.hrtime() which returns nanoseconds.
The features from this module are not available in Worker threads.
The node:trace_events module#
Tracing object#
The Tracing object is used to enable or disable tracing for sets of categories. Instances are created using the trace_events.createTracing() method.
When created, the Tracing object is disabled. Calling the tracing.enable() method adds the categories to the set of enabled trace event categories. Calling tracing.disable() will remove the categories from the set of enabled trace event categories.
tracing.categories#
- Type:
<string>
A comma-separated list of the trace event categories covered by this Tracing object.
tracing.disable()#
Disables this Tracing object.
Only trace event categories not covered by other enabled Tracing objects and not specified by the --trace-event-categories flag will be disabled.
import { createTracing, getEnabledCategories } from 'node:trace_events'; const t1 = createTracing({ categories: ['node', 'v8'] }); const t2 = createTracing({ categories: ['node.perf', 'node'] }); t1.enable(); t2.enable(); // Prints 'node,node.perf,v8' console.log(getEnabledCategories()); t2.disable(); // Will only disable emission of the 'node.perf' category // Prints 'node,v8' console.log(getEnabledCategories());const { createTracing, getEnabledCategories } = require('node:trace_events'); const t1 = createTracing({ categories: ['node', 'v8'] }); const t2 = createTracing({ categories: ['node.perf', 'node'] }); t1.enable(); t2.enable(); // Prints 'node,node.perf,v8' console.log(getEnabledCategories()); t2.disable(); // Will only disable emission of the 'node.perf' category // Prints 'node,v8' console.log(getEnabledCategories());
tracing.enable()#
Enables this Tracing object for the set of categories covered by the Tracing object.
tracing.enabled#
- Type:
<boolean>trueonly if theTracingobject has been enabled.
trace_events.createTracing(options)#
options<Object>categories<string[]>An array of trace category names. Values included in the array are coerced to a string when possible. An error will be thrown if the value cannot be coerced.
- Returns:
<Tracing>.
Creates and returns a Tracing object for the given set of categories.
import { createTracing } from 'node:trace_events'; const categories = ['node.perf', 'node.async_hooks']; const tracing = createTracing({ categories }); tracing.enable(); // do stuff tracing.disable();const { createTracing } = require('node:trace_events'); const categories = ['node.perf', 'node.async_hooks']; const tracing = createTracing({ categories }); tracing.enable(); // do stuff tracing.disable();
trace_events.getEnabledCategories()#
- Returns:
<string>
Returns a comma-separated list of all currently-enabled trace event categories. The current set of enabled trace event categories is determined by the union of all currently-enabled Tracing objects and any categories enabled using the --trace-event-categories flag.
Given the file test.js below, the command node --trace-event-categories node.perf test.js will print 'node.async_hooks,node.perf' to the console.
import { createTracing, getEnabledCategories } from 'node:trace_events'; const t1 = createTracing({ categories: ['node.async_hooks'] }); const t2 = createTracing({ categories: ['node.perf'] }); const t3 = createTracing({ categories: ['v8'] }); t1.enable(); t2.enable(); console.log(getEnabledCategories());const { createTracing, getEnabledCategories } = require('node:trace_events'); const t1 = createTracing({ categories: ['node.async_hooks'] }); const t2 = createTracing({ categories: ['node.perf'] }); const t3 = createTracing({ categories: ['v8'] }); t1.enable(); t2.enable(); console.log(getEnabledCategories());
Examples#
Collect trace events data by inspector#
import { Session } from 'node:inspector'; const session = new Session(); session.connect(); function post(message, data) { return new Promise((resolve, reject) => { session.post(message, data, (err, result) => { if (err) reject(new Error(JSON.stringify(err))); else resolve(result); }); }); } async function collect() { const data = []; session.on('NodeTracing.dataCollected', (chunk) => data.push(chunk)); session.on('NodeTracing.tracingComplete', () => { // done }); const traceConfig = { includedCategories: ['v8'] }; await post('NodeTracing.start', { traceConfig }); // do something setTimeout(() => { post('NodeTracing.stop').then(() => { session.disconnect(); console.log(data); }); }, 1000); } collect();'use strict'; const { Session } = require('node:inspector'); const session = new Session(); session.connect(); function post(message, data) { return new Promise((resolve, reject) => { session.post(message, data, (err, result) => { if (err) reject(new Error(JSON.stringify(err))); else resolve(result); }); }); } async function collect() { const data = []; session.on('NodeTracing.dataCollected', (chunk) => data.push(chunk)); session.on('NodeTracing.tracingComplete', () => { // done }); const traceConfig = { includedCategories: ['v8'] }; await post('NodeTracing.start', { traceConfig }); // do something setTimeout(() => { post('NodeTracing.stop').then(() => { session.disconnect(); console.log(data); }); }, 1000); } collect();
TTY#
Stability: 2 - Stable
The node:tty module provides the tty.ReadStream and tty.WriteStream classes. In most cases, it will not be necessary or possible to use this module directly. However, it can be accessed using:
const tty = require('node:tty');
When Node.js detects that it is being run with a text terminal ("TTY") attached, process.stdin will, by default, be initialized as an instance of tty.ReadStream and both process.stdout and process.stderr will, by default, be instances of tty.WriteStream. The preferred method of determining whether Node.js is being run within a TTY context is to check that the value of the process.stdout.isTTY property is true:
$ node -p -e "Boolean(process.stdout.isTTY)"
true
$ node -p -e "Boolean(process.stdout.isTTY)" | cat
false
In most cases, there should be little to no reason for an application to manually create instances of the tty.ReadStream and tty.WriteStream classes.
Class: tty.ReadStream#
- Extends:
<net.Socket>
Represents the readable side of a TTY. In normal circumstances process.stdin will be the only tty.ReadStream instance in a Node.js process and there should be no reason to create additional instances.
readStream.isRaw#
A boolean that is true if the TTY is currently configured to operate as a raw device.
This flag is always false when a process starts, even if the terminal is operating in raw mode. Its value will change with subsequent calls to setRawMode.
readStream.isTTY#
A boolean that is always true for tty.ReadStream instances.
readStream.setRawMode(mode)#
mode<boolean>Iftrue, configures thetty.ReadStreamto operate as a raw device. Iffalse, configures thetty.ReadStreamto operate in its default mode. ThereadStream.isRawproperty will be set to the resulting mode.- Returns:
<this>The read stream instance.
Allows configuration of tty.ReadStream so that it operates as a raw device.
When in raw mode, input is always available character-by-character, not including modifiers. Additionally, all special processing of characters by the terminal is disabled, including echoing input characters. Ctrl+C will no longer cause a SIGINT when in this mode.
Class: tty.WriteStream#
- Extends:
<net.Socket>
Represents the writable side of a TTY. In normal circumstances, process.stdout and process.stderr will be the only tty.WriteStream instances created for a Node.js process and there should be no reason to create additional instances.
new tty.ReadStream(fd[, options])#
fd<number>A file descriptor associated with a TTY.options<Object>Options passed to parentnet.Socket, seeoptionsofnet.Socketconstructor.- Returns:
<tty.ReadStream>
Creates a ReadStream for fd associated with a TTY.
new tty.WriteStream(fd)#
fd<number>A file descriptor associated with a TTY.- Returns:
<tty.WriteStream>
Creates a WriteStream for fd associated with a TTY.
Event: 'resize'#
The 'resize' event is emitted whenever either of the writeStream.columns or writeStream.rows properties have changed. No arguments are passed to the listener callback when called.
process.stdout.on('resize', () => {
console.log('screen size has changed!');
console.log(`${process.stdout.columns}x${process.stdout.rows}`);
});
writeStream.clearLine(dir[, callback])#
dir<number>-1: to the left from cursor1: to the right from cursor0: the entire line
callback<Function>Invoked once the operation completes.- Returns:
<boolean>falseif the stream wishes for the calling code to wait for the'drain'event to be emitted before continuing to write additional data; otherwisetrue.
writeStream.clearLine() clears the current line of this WriteStream in a direction identified by dir.
writeStream.clearScreenDown([callback])#
callback<Function>Invoked once the operation completes.- Returns:
<boolean>falseif the stream wishes for the calling code to wait for the'drain'event to be emitted before continuing to write additional data; otherwisetrue.
writeStream.clearScreenDown() clears this WriteStream from the current cursor down.
writeStream.columns#
A number specifying the number of columns the TTY currently has. This property is updated whenever the 'resize' event is emitted.
writeStream.cursorTo(x[, y][, callback])#
x<number>y<number>callback<Function>Invoked once the operation completes.- Returns:
<boolean>falseif the stream wishes for the calling code to wait for the'drain'event to be emitted before continuing to write additional data; otherwisetrue.
writeStream.cursorTo() moves this WriteStream's cursor to the specified position.
writeStream.getColorDepth([env])#
env<Object>An object containing the environment variables to check. This enables simulating the usage of a specific terminal. Default:process.env.- Returns:
<number>
Returns:
1for 2,4for 16,8for 256,24for 16,777,216 colors supported.
Use this to determine what colors the terminal supports. Due to the nature of colors in terminals it is possible to either have false positives or false negatives. It depends on process information and the environment variables that may lie about what terminal is used. It is possible to pass in an env object to simulate the usage of a specific terminal. This can be useful to check how specific environment settings behave.
To enforce a specific color support, use one of the below environment settings.
- 2 colors:
FORCE_COLOR = 0(Disables colors) - 16 colors:
FORCE_COLOR = 1 - 256 colors:
FORCE_COLOR = 2 - 16,777,216 colors:
FORCE_COLOR = 3
Disabling color support is also possible by using the NO_COLOR and NODE_DISABLE_COLORS environment variables.
writeStream.getWindowSize()#
- Returns:
<number[]>
writeStream.getWindowSize() returns the size of the TTY corresponding to this WriteStream. The array is of the type [numColumns, numRows] where numColumns and numRows represent the number of columns and rows in the corresponding TTY.
writeStream.hasColors([count][, env])#
count<integer>The number of colors that are requested (minimum 2). Default: 16.env<Object>An object containing the environment variables to check. This enables simulating the usage of a specific terminal. Default:process.env.- Returns:
<boolean>
Returns true if the writeStream supports at least as many colors as provided in count. Minimum support is 2 (black and white).
This has the same false positives and negatives as described in writeStream.getColorDepth().
process.stdout.hasColors();
// Returns true or false depending on if `stdout` supports at least 16 colors.
process.stdout.hasColors(256);
// Returns true or false depending on if `stdout` supports at least 256 colors.
process.stdout.hasColors({ TMUX: '1' });
// Returns true.
process.stdout.hasColors(2 ** 24, { TMUX: '1' });
// Returns false (the environment setting pretends to support 2 ** 8 colors).
writeStream.isTTY#
A boolean that is always true.
writeStream.moveCursor(dx, dy[, callback])#
dx<number>dy<number>callback<Function>Invoked once the operation completes.- Returns:
<boolean>falseif the stream wishes for the calling code to wait for the'drain'event to be emitted before continuing to write additional data; otherwisetrue.
writeStream.moveCursor() moves this WriteStream's cursor relative to its current position.
writeStream.rows#
A number specifying the number of rows the TTY currently has. This property is updated whenever the 'resize' event is emitted.
tty.isatty(fd)#
The tty.isatty() method returns true if the given fd is associated with a TTY and false if it is not, including whenever fd is not a non-negative integer.
UDP/datagram sockets#
Stability: 2 - Stable
The node:dgram module provides an implementation of UDP datagram sockets.
import dgram from 'node:dgram';
const server = dgram.createSocket('udp4');
server.on('error', (err) => {
console.error(`server error:\n${err.stack}`);
server.close();