Node.js v26.7.0 documentation
- Node.js v26.7.0
- Table of contents
- 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
- FFI
- Overview
- Type names
- Signature objects
ffi.suffixffi.dlopen(path[, definitions])ffi.dlclose(handle)ffi.dlsym(handle, symbol)- Class:
DynamicLibrarynew DynamicLibrary(path)library.pathlibrary.functionslibrary.symbolslibrary.close()library[Symbol.dispose]()library.getFunction(name, signature)library.getFunctions([definitions])library.getSymbol(name)library.getSymbols()library.registerCallback([signature,] callback)library.unregisterCallback(pointer)library.refCallback(pointer)library.unrefCallback(pointer)
- Calling native functions
- Primitive memory access helpers
ffi.toString(pointer)ffi.toBuffer(pointer, length[, copy])ffi.toArrayBuffer(pointer, length[, copy])ffi.exportString(string, pointer, length[, encoding])ffi.exportBuffer(buffer, pointer, length)ffi.exportArrayBuffer(arrayBuffer, pointer, length)ffi.exportArrayBufferView(arrayBufferView, pointer, length)ffi.getRawPointer(source)ffi.getCurrentEventLoop()- Safety notes
- 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.pull([...transforms][, options])filehandle.pullSync([...transforms][, options])filehandle.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.writer([options])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:
QuotaExceededError - 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- Response ordering with connection reuse
new Agent([options])agent.createConnection(options[, callback])agent.keepSocketAlive(socket)agent.reuseSocket(socket, request)agent.destroy()agent.freeSocketsagent.getName([options])agent.maxFreeSocketsagent.maxSocketsagent.maxTotalSocketsagent.requestsagent.sockets
- 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.writeInformation(statusCode[, headers][, callback])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.signalmessage.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.writeInformation(statusCode[, headers])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
- 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
- Terminology
- Overview
async_hooks.createHook(options)- Class:
AsyncHook - Promise execution tracking
- JavaScript embedder API
- Class:
AsyncLocalStorage
- 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])asyncLocalStorage.withScope(store)- Usage with
async/await - Troubleshooting: Context loss
- Class:
RunScope - 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[, start[, end]][, encoding])buf.indexOf(value[, start[, end]][, encoding])buf.keys()buf.lastIndexOf(value[, start[, end]][, 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-ffi--allow-fs-read--allow-fs-write--allow-inspector--allow-net--allow-openssl-store--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=path,--experimental-config-file--experimental-default-config-file--experimental-eventsource--experimental-ffi--experimental-import-meta-resolve--experimental-import-text--experimental-inspector-network-resource--experimental-loader=module--experimental-network-inspection--experimental-package-map=<path>--experimental-print-required-tla--experimental-quic--experimental-sea-config--experimental-shadow-realm--experimental-storage-inspection--experimental-stream-iter--experimental-test-coverage--experimental-test-module-mocks--experimental-test-tag-filter=<tag>--experimental-vfs--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--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-include-all--test-coverage-lines=threshold--test-force-exit--test-global-setup=module--test-isolation=mode--test-name-pattern--test-only--test-random-seed--test-randomize--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
- 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.Deserializernew Deserializer(buffer)deserializer.readHeader()deserializer.readValue()deserializer.transferArrayBuffer(id, arrayBuffer)deserializer.getWireFormatVersion()deserializer.readUint32()deserializer.readUint64()deserializer.readDouble()deserializer.readRawBytes(length)deserializer._readHostObject()
- Class:
v8.DefaultSerializer - Class:
v8.DefaultDeserializer
- Promise hooks
- Startup Snapshot API
- Class:
v8.GCProfiler - Class:
SyncCPUProfileHandle - Class:
SyncHeapProfileHandle - Class:
CPUProfileHandle - Class:
HeapProfileHandle v8.isStringOneByteRepresentation(content)v8.startCpuProfile([options])v8.startHeapProfile([options])
- Virtual File System
- 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:
- Web Crypto API
- Modern Algorithms in the Web Cryptography API
- Secure Curves in the Web Cryptography API
- Examples
- Algorithm support
- 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, keyUsages)subtle.decrypt(algorithm, key, data)subtle.deriveBits(algorithm, baseKey[, length])subtle.deriveKey(algorithm, baseKey, derivedKeyType, extractable, keyUsages)subtle.digest(algorithm, data)subtle.encapsulateBits(encapsulationAlgorithm, encapsulationKey)subtle.encapsulateKey(encapsulationAlgorithm, encapsulationKey, sharedKeyAlgorithm, extractable, keyUsages)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, unwrapAlgorithm, unwrappedKeyAlgorithm, extractable, keyUsages)subtle.verify(algorithm, key, signature, data)subtle.wrapKey(format, key, wrappingKey, wrapAlgorithm)
- 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:
KangarooTwelveParams - Class:
KmacImportParams - Class:
KmacKeyAlgorithm - Class:
KmacKeyGenParams - Class:
KmacParams - Class:
Pbkdf2Params - Class:
RsaHashedImportParams - Class:
RsaHashedKeyAlgorithm - Class:
RsaHashedKeyGenParams - Class:
RsaOaepParams - Class:
RsaPssParams - Class:
TurboShakeParams
- Class:
- Web Streams API
- Overview
- API
ReadableStreamTee(stream[, cloneForBranch2])- 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
- 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([options])worker.startHeapProfile([options])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])
- Iterable Compression
compressBrotli([options])compressBrotliSync([options])compressDeflate([options])compressDeflateSync([options])compressGzip([options])compressGzipSync([options])compressZstd([options])compressZstdSync([options])decompressBrotli([options])decompressBrotliSync([options])decompressDeflate([options])decompressDeflateSync([options])decompressGzip([options])decompressGzipSync([options])decompressZstd([options])decompressZstdSync([options])
- 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:
ELDHistogram extends Histogram - Class:
RecordableHistogram extends Histogram - Examples
- Permissions
- Process
- Process events
process.abort()process.addUncaughtExceptionCaptureCallback(fn)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.report.compactprocess.report.directoryprocess.report.filenameprocess.report.getReport([err])process.report.reportOnFatalErrorprocess.report.reportOnSignalprocess.report.reportOnUncaughtExceptionprocess.report.excludeEnvprocess.report.signalprocess.report.writeReport([filename][, err])
process.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:
- REPL
- 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
- Type conversion between JavaScript and SQLite
- Class:
DatabaseSyncnew DatabaseSync(path[, options])database.aggregate(name, options)database.close()database.loadExtension(path[, entryPoint])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.serialize([dbName])database.deserialize(buffer[, options])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:
SQLTagStore sqlite.backup(sourceDb, path[, options])sqlite.constants
- Stream
- Organization of this document
- Types of streams
- API for stream consumers
- Writable streams
- Class:
stream.Writable- Event:
'close' - Event:
'drain' - Event:
'error' - Event:
'finish' - Event:
'pipe' - Event:
'unpipe' writable.cork()writable.destroy([error])writable.closedwritable.destroyedwritable.end([chunk[, encoding]][, callback])writable.setDefaultEncoding(encoding)writable.uncork()writable.writablewritable.writableAbortedwritable.writableEndedwritable.writableCorkedwritable.erroredwritable.writableFinishedwritable.writableHighWaterMarkwritable.writableLengthwritable.writableNeedDrainwritable.writableObjectModewritable[Symbol.asyncDispose]()writable.write(chunk[, encoding][, callback])
- Event:
- Class:
- Readable streams
- Two reading modes
- Three states
- Choose one API style
- Class:
stream.Readable- Event:
'close' - Event:
'data' - Event:
'end' - Event:
'error' - Event:
'pause' - Event:
'readable' - Event:
'resume' readable.destroy([error])readable.closedreadable.destroyedreadable.isPaused()readable.pause()readable.pipe(destination[, options])readable.read([size])readable.readablereadable.readableAbortedreadable.readableDidReadreadable.readableEncodingreadable.readableEndedreadable.erroredreadable.readableFlowingreadable.readableHighWaterMarkreadable.readableLengthreadable.readableObjectModereadable.resume()readable.setEncoding(encoding)readable.unpipe([destination])readable.unshift(chunk[, encoding])readable.wrap(stream)readable[Symbol.asyncIterator]()readable[Symbol.for('Stream.toAsyncStreamable')]()readable[Symbol.asyncDispose]()readable.compose(stream[, options])readable.iterator([options])readable.map(fn[, options])readable.filter(fn[, options])readable.forEach(fn[, options])readable.toArray([options])readable.some(fn[, options])readable.find(fn[, options])readable.every(fn[, options])readable.flatMap(fn[, options])readable.drop(limit[, options])readable.take(limit[, options])readable.reduce(fn[, initial[, options]])
- Event:
- Duplex and transform streams
stream.finished(stream[, options], callback)stream.pipeline(source[, ...transforms], destination, callback)stream.pipeline(streams, callback)stream.compose(...streams)stream.isDestroyed(stream)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)
- Writable streams
- API for stream implementers
- Additional notes
- Iterable Streams
- Concepts
- The
stream/itermodule - Sources
- Pipelines
- Push streams
- Duplex channels
- Consumers
- Utilities
- Multi-consumer
- Compression and decompression transforms
- Classic stream interop
- Protocol symbols
- 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
- 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
- Introduction
- Determining module system
- Package entry points
- Dual CommonJS/ES module packages
- Package maps
- Node.js
package.jsonfield definitions
- 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.Socket- Transferring TCP handles to other threads
new 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.serversocket.resetAndDestroy()socket.resume()socket.setEncoding([encoding])socket.setKeepAlive()socket.setNoDelay([noDelay])socket.setTimeout(timeout[, callback])socket.getTypeOfService()socket.setTypeOfService(tos)socket.timeoutsocket.unref()socket.write(data[, encoding][, callback])socket.readyState
- Class:
net.BoundSocket 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_arraybuffernode_api_create_external_sharedarraybuffernapi_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
napi_create_int32napi_create_uint32napi_create_int64napi_create_doublenapi_create_bigint_int64napi_create_bigint_uint64napi_create_bigint_wordsnapi_create_string_latin1node_api_create_external_string_latin1napi_create_string_utf16node_api_create_external_string_utf16napi_create_string_utf8
- 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
- Test runner
- Subtests
- Rerunning failed tests
describe()andit()aliases- Skipping tests
- TODO tests
- Expecting tests to fail
onlytests- Filtering tests by name
- Test tags
- 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:log' - 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:
getTestContext()- Test instrumentation and OpenTelemetry
- Class:
TestContextcontext.before([fn][, options])context.beforeEach([fn][, options])context.after([fn][, options])context.afterEach([fn][, options])context.assertcontext.diagnostic(message)context.log(message[, data])context.filePathcontext.fullNamecontext.namecontext.passedcontext.errorcontext.attemptcontext.tagscontext.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
- 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.alpnProtocoltlsSocket.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.servernametlsSocket.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.getCertificateCompressionAlgorithms()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.bindSync([options])socket.close([callback])socket[Symbol.asyncDispose]()socket.connect(port[, address][, callback])socket.connectSync(port[, address])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(signal)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
- 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.randomUUIDv7([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/spawnwithshelloption - 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 - DEP0203: Passing
CryptoKeytonode:cryptoAPIs - DEP0204:
KeyObject.from()with non-extractableCryptoKey - DEP0205:
module.register() - DEP0206: Calling
digest()on an already-finalizedHmacinstance
- DEP0001:
- Diagnostics Channel
- Public API
- Overview
- Class:
Channel - Class:
RunStoresScope - 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
- Class:
BoundedChannel - Class:
BoundedChannelScope - BoundedChannel Channels
- TracingChannel Channels
- Built-in Channels
- Console
- HTTP
- HTTP/2
- Event:
'http2.client.stream.created' - Event:
'http2.client.stream.start' - Event:
'http2.client.stream.error' - Event:
'http2.client.stream.finish' - Event:
'http2.client.stream.bodyChunkSent' - Event:
'http2.client.stream.bodySent' - Event:
'http2.client.stream.close' - Event:
'http2.server.stream.created' - Event:
'http2.server.stream.start' - Event:
'http2.server.stream.error' - Event:
'http2.server.stream.finish' - Event:
'http2.server.stream.close'
- Event:
- Modules
- NET
- UDP
- Process
- Web Locks
- Worker Thread
- 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:
- Domain
- Errors
- Error propagation and interception
- Class:
Error - Class:
AssertionError - Class:
RangeError - Class:
ReferenceError - Class:
SyntaxError - Class:
SystemError - Class:
TypeError - Exceptions vs. errors
- OpenSSL errors
- Node.js error codes
ABORT_ERRERR_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_FFI_CALL_FAILEDERR_FFI_INVALID_POINTERERR_FFI_LIBRARY_CLOSEDERR_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_TOO_MANY_ORIGINSERR_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_TEMPORALERR_NO_TYPESCRIPTERR_OPERATION_FAILEDERR_OPTIONS_BEFORE_BOOTSTRAPPINGERR_OUT_OF_RANGEERR_PACKAGE_IMPORT_NOT_DEFINEDERR_PACKAGE_MAP_EXTERNAL_FILEERR_PACKAGE_MAP_INVALIDERR_PACKAGE_MAP_KEY_NOT_FOUNDERR_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_STREAM_ABORTEDERR_QUIC_STREAM_RESETERR_QUIC_TRANSPORT_ERRORERR_QUIC_VERSION_NEGOTIATION_ERRORERR_REQUIRE_ASYNC_MODULEERR_REQUIRE_CYCLE_MODULEERR_REQUIRE_ESMERR_REQUIRE_ESM_RACE_CONDITIONERR_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_SOCKET_HANDLE_ADOPTEDERR_SOURCE_MAP_CORRUPTERR_SOURCE_MAP_MISSING_SOURCEERR_SOURCE_PHASE_NOT_DEFINEDERR_SQLITE_ERRORERR_SRI_PARSEERR_STREAM_ALREADY_FINISHEDERR_STREAM_CANNOT_PIPEERR_STREAM_DESTROYEDERR_STREAM_ITER_MISSING_FLAGERR_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_RENEGOTIATION_UNSUPPORTEDERR_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_HANDLE_NOT_TRANSFERABLEERR_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
- Events
- Other versions
- Options
Events#
Stability: 2 - Stable
Much of the Node.js core API is built around an idiomatic asynchronous
event-driven architecture in which certain kinds of objects (called "emitters")
emit named events that cause Function objects ("listeners") to be called.
For instance: a net.Server object emits an event each time a peer
connects to it; a fs.ReadStream emits an event when the file is opened;
a stream emits an event whenever data is available to be read.
All objects that emit events are instances of the EventEmitter class. These
objects expose an eventEmitter.on() function that allows one or more
functions to be attached to named events emitted by the object. Typically,
event names are camel-cased strings but any valid JavaScript property key
can be used.
When the EventEmitter object emits an event, all of the functions attached
to that specific event are called synchronously. Any values returned by the
called listeners are ignored and discarded.
The following example shows a simple EventEmitter instance with a single
listener. The eventEmitter.on() method is used to register listeners, while
the eventEmitter.emit() method is used to trigger the event.
import { EventEmitter } from 'node:events'; class MyEmitter extends EventEmitter {} const myEmitter = new MyEmitter(); myEmitter.on('event', () => { console.log('an event occurred!'); }); myEmitter.emit('event');const EventEmitter = require('node:events'); class MyEmitter extends EventEmitter {} const myEmitter = new MyEmitter(); myEmitter.on('event', () => { console.log('an event occurred!'); }); myEmitter.emit('event');
Passing arguments and this to listeners#
The eventEmitter.emit() method allows an arbitrary set of arguments to be
passed to the listener functions. Keep in mind that when
an ordinary listener function is called, the standard this keyword
is intentionally set to reference the EventEmitter instance to which the
listener is attached.
import { EventEmitter } from 'node:events'; class MyEmitter extends EventEmitter {} const myEmitter = new MyEmitter(); myEmitter.on('event', function(a, b) { console.log(a, b, this, this === myEmitter); // Prints: // a b MyEmitter { // _events: [Object: null prototype] { event: [Function (anonymous)] }, // _eventsCount: 1, // _maxListeners: undefined, // Symbol(shapeMode): false, // Symbol(kCapture): false // } true }); myEmitter.emit('event', 'a', 'b');const EventEmitter = require('node:events'); class MyEmitter extends EventEmitter {} const myEmitter = new MyEmitter(); myEmitter.on('event', function(a, b) { console.log(a, b, this, this === myEmitter); // Prints: // a b MyEmitter { // _events: [Object: null prototype] { event: [Function (anonymous)] }, // _eventsCount: 1, // _maxListeners: undefined, // Symbol(shapeMode): false, // Symbol(kCapture): false // } true }); myEmitter.emit('event', 'a', 'b');
It is possible to use ES6 Arrow Functions as listeners, however, when doing so,
the this keyword will no longer reference the EventEmitter instance:
import { EventEmitter } from 'node:events'; class MyEmitter extends EventEmitter {} const myEmitter = new MyEmitter(); myEmitter.on('event', (a, b) => { console.log(a, b, this); // Prints: a b undefined }); myEmitter.emit('event', 'a', 'b');const EventEmitter = require('node:events'); class MyEmitter extends EventEmitter {} const myEmitter = new MyEmitter(); myEmitter.on('event', (a, b) => { console.log(a, b, this); // Prints: a b {} }); myEmitter.emit('event', 'a', 'b');
Asynchronous vs. synchronous#
The EventEmitter calls all listeners synchronously in the order in which
they were registered. This ensures the proper sequencing of
events and helps avoid race conditions and logic errors. When appropriate,
listener functions can switch to an asynchronous mode of operation using
the setImmediate() or process.nextTick() methods:
import { EventEmitter } from 'node:events'; class MyEmitter extends EventEmitter {} const myEmitter = new MyEmitter(); myEmitter.on('event', (a, b) => { setImmediate(() => { console.log('this happens asynchronously'); }); }); myEmitter.emit('event', 'a', 'b');const EventEmitter = require('node:events'); class MyEmitter extends EventEmitter {} const myEmitter = new MyEmitter(); myEmitter.on('event', (a, b) => { setImmediate(() => { console.log('this happens asynchronously'); }); }); myEmitter.emit('event', 'a', 'b');
Handling events only once#
When a listener is registered using the eventEmitter.on() method, that
listener is invoked every time the named event is emitted.
import { EventEmitter } from 'node:events'; class MyEmitter extends EventEmitter {} const myEmitter = new MyEmitter(); let m = 0; myEmitter.on('event', () => { console.log(++m); }); myEmitter.emit('event'); // Prints: 1 myEmitter.emit('event'); // Prints: 2const EventEmitter = require('node:events'); class MyEmitter extends EventEmitter {} const myEmitter = new MyEmitter(); let m = 0; myEmitter.on('event', () => { console.log(++m); }); myEmitter.emit('event'); // Prints: 1 myEmitter.emit('event'); // Prints: 2
Using the eventEmitter.once() method, it is possible to register a listener
that is called at most once for a particular event. Once the event is emitted,
the listener is unregistered and then called.
import { EventEmitter } from 'node:events'; class MyEmitter extends EventEmitter {} const myEmitter = new MyEmitter(); let m = 0; myEmitter.once('event', () => { console.log(++m); }); myEmitter.emit('event'); // Prints: 1 myEmitter.emit('event'); // Ignoredconst EventEmitter = require('node:events'); class MyEmitter extends EventEmitter {} const myEmitter = new MyEmitter(); let m = 0; myEmitter.once('event', () => { console.log(++m); }); myEmitter.emit('event'); // Prints: 1 myEmitter.emit('event'); // Ignored
Error events#
When an error occurs within an EventEmitter instance, the typical action is
for an 'error' event to be emitted. These are treated as special cases
within Node.js.
If an EventEmitter does not have at least one listener registered for the
'error' event, and an 'error' event is emitted, the error is thrown, a
stack trace is printed, and the Node.js process exits.
import { EventEmitter } from 'node:events'; class MyEmitter extends EventEmitter {} const myEmitter = new MyEmitter(); myEmitter.emit('error', new Error('whoops!')); // Throws and crashes Node.jsconst EventEmitter = require('node:events'); class MyEmitter extends EventEmitter {} const myEmitter = new MyEmitter(); myEmitter.emit('error', new Error('whoops!')); // Throws and crashes Node.js
To guard against crashing the Node.js process the domain module can be
used. (Note, however, that the node:domain module is deprecated.)
As a best practice, listeners should always be added for the 'error' events.
import { EventEmitter } from 'node:events'; class MyEmitter extends EventEmitter {} const myEmitter = new MyEmitter(); myEmitter.on('error', (err) => { console.error('whoops! there was an error'); }); myEmitter.emit('error', new Error('whoops!')); // Prints: whoops! there was an errorconst EventEmitter = require('node:events'); class MyEmitter extends EventEmitter {} const myEmitter = new MyEmitter(); myEmitter.on('error', (err) => { console.error('whoops! there was an error'); }); myEmitter.emit('error', new Error('whoops!')); // Prints: whoops! there was an error
It is possible to monitor 'error' events without consuming the emitted error
by installing a listener using the symbol events.errorMonitor.
import { EventEmitter, errorMonitor } from 'node:events'; const myEmitter = new EventEmitter(); myEmitter.on(errorMonitor, (err) => { MyMonitoringTool.log(err); }); myEmitter.emit('error', new Error('whoops!')); // Still throws and crashes Node.jsconst { EventEmitter, errorMonitor } = require('node:events'); const myEmitter = new EventEmitter(); myEmitter.on(errorMonitor, (err) => { MyMonitoringTool.log(err); }); myEmitter.emit('error', new Error('whoops!')); // Still throws and crashes Node.js
Capture rejections of promises#
Using async functions with event handlers is problematic, because it
can lead to an unhandled rejection in case of a thrown exception:
import { EventEmitter } from 'node:events'; const ee = new EventEmitter(); ee.on('something', async (value) => { throw new Error('kaboom'); });const EventEmitter = require('node:events'); const ee = new EventEmitter(); ee.on('something', async (value) => { throw new Error('kaboom'); });
The captureRejections option in the EventEmitter constructor or the global
setting change this behavior, installing a .then(undefined, handler)
handler on the Promise. This handler routes the exception
asynchronously to the Symbol.for('nodejs.rejection') method
if there is one, or to 'error' event handler if there is none.
import { EventEmitter } from 'node:events'; const ee1 = new EventEmitter({ captureRejections: true }); ee1.on('something', async (value) => { throw new Error('kaboom'); }); ee1.on('error', console.log); const ee2 = new EventEmitter({ captureRejections: true }); ee2.on('something', async (value) => { throw new Error('kaboom'); }); ee2[Symbol.for('nodejs.rejection')] = console.log;const EventEmitter = require('node:events'); const ee1 = new EventEmitter({ captureRejections: true }); ee1.on('something', async (value) => { throw new Error('kaboom'); }); ee1.on('error', console.log); const ee2 = new EventEmitter({ captureRejections: true }); ee2.on('something', async (value) => { throw new Error('kaboom'); }); ee2[Symbol.for('nodejs.rejection')] = console.log;
Setting events.captureRejections = true will change the default for all
new instances of EventEmitter.
import { EventEmitter } from 'node:events'; EventEmitter.captureRejections = true; const ee1 = new EventEmitter(); ee1.on('something', async (value) => { throw new Error('kaboom'); }); ee1.on('error', console.log);const events = require('node:events'); events.captureRejections = true; const ee1 = new events.EventEmitter(); ee1.on('something', async (value) => { throw new Error('kaboom'); }); ee1.on('error', console.log);
The 'error' events that are generated by the captureRejections behavior
do not have a catch handler to avoid infinite error loops: the
recommendation is to not use async functions as 'error' event handlers.
Class: EventEmitter#
The EventEmitter class is defined and exposed by the node:events module:
import { EventEmitter } from 'node:events';const EventEmitter = require('node:events');
All EventEmitters emit the event 'newListener' when new listeners are
added and 'removeListener' when existing listeners are removed.
It supports the following option:
captureRejections<boolean>It enables automatic capturing of promise rejection. Default:false.
Event: 'newListener'#
eventName<string>|<symbol>The name of the event being listened forlistener<Function>The event handler function
The EventEmitter instance will emit its own 'newListener' event before
a listener is added to its internal array of listeners.
Listeners registered for the 'newListener' event are passed the event
name and a reference to the listener being added.
The fact that the event is triggered before adding the listener has a subtle
but important side effect: any additional listeners registered to the same
name within the 'newListener' callback are inserted before the
listener that is in the process of being added.
import { EventEmitter } from 'node:events'; class MyEmitter extends EventEmitter {} const myEmitter = new MyEmitter(); // Only do this once so we don't loop forever myEmitter.once('newListener', (event, listener) => { if (event === 'event') { // Insert a new listener in front myEmitter.on('event', () => { console.log('B'); }); } }); myEmitter.on('event', () => { console.log('A'); }); myEmitter.emit('event'); // Prints: // B // Aconst EventEmitter = require('node:events'); class MyEmitter extends EventEmitter {} const myEmitter = new MyEmitter(); // Only do this once so we don't loop forever myEmitter.once('newListener', (event, listener) => { if (event === 'event') { // Insert a new listener in front myEmitter.on('event', () => { console.log('B'); }); } }); myEmitter.on('event', () => { console.log('A'); }); myEmitter.emit('event'); // Prints: // B // A
Event: 'removeListener'#
eventName<string>|<symbol>The event namelistener<Function>The event handler function
The 'removeListener' event is emitted after the listener is removed.
emitter.addListener(eventName, listener)#
eventName<string>|<symbol>listener<Function>
Alias for emitter.on(eventName, listener).
emitter.emit(eventName[, ...args])#
Synchronously calls each of the listeners registered for the event named
eventName, in the order they were registered, passing the supplied arguments
to each.
Returns true if the event had listeners, false otherwise.
import { EventEmitter } from 'node:events'; const myEmitter = new EventEmitter(); // First listener myEmitter.on('event', function firstListener() { console.log('Helloooo! first listener'); }); // Second listener myEmitter.on('event', function secondListener(arg1, arg2) { console.log(`event with parameters ${arg1}, ${arg2} in second listener`); }); // Third listener myEmitter.on('event', function thirdListener(...args) { const parameters = args.join(', '); console.log(`event with parameters ${parameters} in third listener`); }); console.log(myEmitter.listeners('event')); myEmitter.emit('event', 1, 2, 3, 4, 5); // Prints: // [ // [Function: firstListener], // [Function: secondListener], // [Function: thirdListener] // ] // Helloooo! first listener // event with parameters 1, 2 in second listener // event with parameters 1, 2, 3, 4, 5 in third listenerconst EventEmitter = require('node:events'); const myEmitter = new EventEmitter(); // First listener myEmitter.on('event', function firstListener() { console.log('Helloooo! first listener'); }); // Second listener myEmitter.on('event', function secondListener(arg1, arg2) { console.log(`event with parameters ${arg1}, ${arg2} in second listener`); }); // Third listener myEmitter.on('event', function thirdListener(...args) { const parameters = args.join(', '); console.log(`event with parameters ${parameters} in third listener`); }); console.log(myEmitter.listeners('event')); myEmitter.emit('event', 1, 2, 3, 4, 5); // Prints: // [ // [Function: firstListener], // [Function: secondListener], // [Function: thirdListener] // ] // Helloooo! first listener // event with parameters 1, 2 in second listener // event with parameters 1, 2, 3, 4, 5 in third listener
emitter.eventNames()#
Returns an array listing the events for which the emitter has registered listeners.
import { EventEmitter } from 'node:events'; const myEE = new EventEmitter(); myEE.on('foo', () => {}); myEE.on('bar', () => {}); const sym = Symbol('symbol'); myEE.on(sym, () => {}); console.log(myEE.eventNames()); // Prints: [ 'foo', 'bar', Symbol(symbol) ]const EventEmitter = require('node:events'); const myEE = new EventEmitter(); myEE.on('foo', () => {}); myEE.on('bar', () => {}); const sym = Symbol('symbol'); myEE.on(sym, () => {}); console.log(myEE.eventNames()); // Prints: [ 'foo', 'bar', Symbol(symbol) ]
emitter.getMaxListeners()#
- Returns:
<integer>
Returns the current max listener value for the EventEmitter which is either
set by emitter.setMaxListeners(n) or defaults to
events.defaultMaxListeners.
emitter.listenerCount(eventName[, listener])#
eventName<string>|<symbol>The name of the event being listened forlistener<Function>The event handler function- Returns:
<integer>
Returns the number of listeners listening for the event named eventName.
If listener is provided, it will return how many times the listener is found
in the list of the listeners of the event.
emitter.listeners(eventName)#
eventName<string>|<symbol>- Returns:
<Function>[]
Returns a copy of the array of listeners for the event named eventName.
server.on('connection', (stream) => {
console.log('someone connected!');
});
console.log(util.inspect(server.listeners('connection')));
// Prints: [ [Function] ]
emitter.off(eventName, listener)#
eventName<string>|<symbol>listener<Function>- Returns:
<EventEmitter>
Alias for emitter.removeListener().
emitter.on(eventName, listener)#
eventName<string>|<symbol>The name of the event.listener<Function>The callback function- Returns:
<EventEmitter>
Adds the listener function to the end of the listeners array for the
event named eventName. No checks are made to see if the listener has
already been added. Multiple calls passing the same combination of eventName
and listener will result in the listener being added, and called, multiple
times.
server.on('connection', (stream) => {
console.log('someone connected!');
});
Returns a reference to the EventEmitter, so that calls can be chained.
By default, event listeners are invoked in the order they are added. The
emitter.prependListener() method can be used as an alternative to add the
event listener to the beginning of the listeners array.
import { EventEmitter } from 'node:events'; const myEE = new EventEmitter(); myEE.on('foo', () => console.log('a')); myEE.prependListener('foo', () => console.log('b')); myEE.emit('foo'); // Prints: // b // aconst EventEmitter = require('node:events'); const myEE = new EventEmitter(); myEE.on('foo', () => console.log('a')); myEE.prependListener('foo', () => console.log('b')); myEE.emit('foo'); // Prints: // b // a
emitter.once(eventName, listener)#
eventName<string>|<symbol>The name of the event.listener<Function>The callback function- Returns:
<EventEmitter>
Adds a one-time listener function for the event named eventName. The
next time eventName is triggered, this listener is removed and then invoked.
server.once('connection', (stream) => {
console.log('Ah, we have our first user!');
});
Returns a reference to the EventEmitter, so that calls can be chained.
By default, event listeners are invoked in the order they are added. The
emitter.prependOnceListener() method can be used as an alternative to add the
event listener to the beginning of the listeners array.
import { EventEmitter } from 'node:events'; const myEE = new EventEmitter(); myEE.once('foo', () => console.log('a')); myEE.prependOnceListener('foo', () => console.log('b')); myEE.emit('foo'); // Prints: // b // aconst EventEmitter = require('node:events'); const myEE = new EventEmitter(); myEE.once('foo', () => console.log('a')); myEE.prependOnceListener('foo', () => console.log('b')); myEE.emit('foo'); // Prints: // b // a
emitter.prependListener(eventName, listener)#
eventName<string>|<symbol>The name of the event.listener<Function>The callback function- Returns:
<EventEmitter>
Adds the listener function to the beginning of the listeners array for the
event named eventName. No checks are made to see if the listener has
already been added. Multiple calls passing the same combination of eventName
and listener will result in the listener being added, and called, multiple
times.
server.prependListener('connection', (stream) => {
console.log('someone connected!');
});
Returns a reference to the EventEmitter, so that calls can be chained.
emitter.prependOnceListener(eventName, listener)#
eventName<string>|<symbol>The name of the event.listener<Function>The callback function- Returns:
<EventEmitter>
Adds a one-time listener function for the event named eventName to the
beginning of the listeners array. The next time eventName is triggered, this
listener is removed, and then invoked.
server.prependOnceListener('connection', (stream) => {
console.log('Ah, we have our first user!');
});
Returns a reference to the EventEmitter, so that calls can be chained.
emitter.removeAllListeners([eventName])#
eventName<string>|<symbol>- Returns:
<EventEmitter>
Removes all listeners, or those of the specified eventName.
It is bad practice to remove listeners added elsewhere in the code,
particularly when the EventEmitter instance was created by some other
component or module (e.g. sockets or file streams).
Returns a reference to the EventEmitter, so that calls can be chained.
emitter.removeListener(eventName, listener)#
eventName<string>|<symbol>listener<Function>- Returns:
<EventEmitter>
Removes the specified listener from the listener array for the event named
eventName.
const callback = (stream) => {
console.log('someone connected!');
};
server.on('connection', callback);
// ...
server.removeListener('connection', callback);
removeListener() will remove, at most, one instance of a listener from the
listener array. If any single listener has been added multiple times to the
listener array for the specified eventName, then removeListener() must be
called multiple times to remove each instance.
Once an event is emitted, all listeners attached to it at the
time of emitting are called in order. This implies that any
removeListener() or removeAllListeners() calls after emitting and
before the last listener finishes execution will not remove them from
emit() in progress. Subsequent events behave as expected.
import { EventEmitter } from 'node:events'; class MyEmitter extends EventEmitter {} const myEmitter = new MyEmitter(); const callbackA = () => { console.log('A'); myEmitter.removeListener('event', callbackB); }; const callbackB = () => { console.log('B'); }; myEmitter.on('event', callbackA); myEmitter.on('event', callbackB); // callbackA removes listener callbackB but it will still be called. // Internal listener array at time of emit [callbackA, callbackB] myEmitter.emit('event'); // Prints: // A // B // callbackB is now removed. // Internal listener array [callbackA] myEmitter.emit('event'); // Prints: // Aconst EventEmitter = require('node:events'); class MyEmitter extends EventEmitter {} const myEmitter = new MyEmitter(); const callbackA = () => { console.log('A'); myEmitter.removeListener('event', callbackB); }; const callbackB = () => { console.log('B'); }; myEmitter.on('event', callbackA); myEmitter.on('event', callbackB); // callbackA removes listener callbackB but it will still be called. // Internal listener array at time of emit [callbackA, callbackB] myEmitter.emit('event'); // Prints: // A // B // callbackB is now removed. // Internal listener array [callbackA] myEmitter.emit('event'); // Prints: // A
Because listeners are managed using an internal array, calling this will
change the position indexes of any listener registered after the listener
being removed. This will not impact the order in which listeners are called,
but it means that any copies of the listener array as returned by
the emitter.listeners() method will need to be recreated.
When a single function has been added as a handler multiple times for a single
event (as in the example below), removeListener() will remove the most
recently added instance. In the example the once('ping')
listener is removed:
import { EventEmitter } from 'node:events'; const ee = new EventEmitter(); function pong() { console.log('pong'); } ee.on('ping', pong); ee.once('ping', pong); ee.removeListener('ping', pong); ee.emit('ping'); ee.emit('ping');const EventEmitter = require('node:events'); const ee = new EventEmitter(); function pong() { console.log('pong'); } ee.on('ping', pong); ee.once('ping', pong); ee.removeListener('ping', pong); ee.emit('ping'); ee.emit('ping');
Returns a reference to the EventEmitter, so that calls can be chained.
emitter.setMaxListeners(n)#
n<integer>- Returns:
<EventEmitter>
By default EventEmitters will print a warning if more than 10 listeners are
added for a particular event. This is a useful default that helps finding
memory leaks. The emitter.setMaxListeners() method allows the limit to be
modified for this specific EventEmitter instance. The value can be set to
Infinity (or 0) to indicate an unlimited number of listeners.
Returns a reference to the EventEmitter, so that calls can be chained.
emitter.rawListeners(eventName)#
eventName<string>|<symbol>- Returns:
<Function>[]
Returns a copy of the array of listeners for the event named eventName,
including any wrappers (such as those created by .once()).
import { EventEmitter } from 'node:events'; const emitter = new EventEmitter(); emitter.once('log', () => console.log('log once')); // Returns a new Array with a function `onceWrapper` which has a property // `listener` which contains the original listener bound above const listeners = emitter.rawListeners('log'); const logFnWrapper = listeners[0]; // Logs "log once" to the console and does not unbind the `once` event logFnWrapper.listener(); // Logs "log once" to the console and removes the listener logFnWrapper(); emitter.on('log', () => console.log('log persistently')); // Will return a new Array with a single function bound by `.on()` above const newListeners = emitter.rawListeners('log'); // Logs "log persistently" twice newListeners[0](); emitter.emit('log');const EventEmitter = require('node:events'); const emitter = new EventEmitter(); emitter.once('log', () => console.log('log once')); // Returns a new Array with a function `onceWrapper` which has a property // `listener` which contains the original listener bound above const listeners = emitter.rawListeners('log'); const logFnWrapper = listeners[0]; // Logs "log once" to the console and does not unbind the `once` event logFnWrapper.listener(); // Logs "log once" to the console and removes the listener logFnWrapper(); emitter.on('log', () => console.log('log persistently')); // Will return a new Array with a single function bound by `.on()` above const newListeners = emitter.rawListeners('log'); // Logs "log persistently" twice newListeners[0](); emitter.emit('log');
emitter[Symbol.for('nodejs.rejection')](err, eventName[, ...args])#
The Symbol.for('nodejs.rejection') method is called in case a
promise rejection happens when emitting an event and
captureRejections is enabled on the emitter.
It is possible to use events.captureRejectionSymbol in
place of Symbol.for('nodejs.rejection').
import { EventEmitter, captureRejectionSymbol } from 'node:events'; class MyClass extends EventEmitter { constructor() { super({ captureRejections: true }); } [captureRejectionSymbol](err, event, ...args) { console.log('rejection happened for', event, 'with', err, ...args); this.destroy(err); } destroy(err) { // Tear the resource down here. } }const { EventEmitter, captureRejectionSymbol } = require('node:events'); class MyClass extends EventEmitter { constructor() { super({ captureRejections: true }); } [captureRejectionSymbol](err, event, ...args) { console.log('rejection happened for', event, 'with', err, ...args); this.destroy(err); } destroy(err) { // Tear the resource down here. } }
events.defaultMaxListeners#
By default, a maximum of 10 listeners can be registered for any single
event. This limit can be changed for individual EventEmitter instances
using the emitter.setMaxListeners(n) method. To change the default
for all EventEmitter instances, the events.defaultMaxListeners
property can be used. If this value is not a positive number, a RangeError
is thrown.
Take caution when setting the events.defaultMaxListeners because the
change affects all EventEmitter instances, including those created before
the change is made. However, calling emitter.setMaxListeners(n) still has
precedence over events.defaultMaxListeners.
This is not a hard limit. The EventEmitter instance will allow
more listeners to be added but will output a trace warning to stderr indicating
that a "possible EventEmitter memory leak" has been detected. For any single
EventEmitter, the emitter.getMaxListeners() and emitter.setMaxListeners()
methods can be used to temporarily avoid this warning:
defaultMaxListeners has no effect on AbortSignal instances. While it is
still possible to use emitter.setMaxListeners(n) to set a warning limit
for individual AbortSignal instances, per default AbortSignal instances will not warn.
import { EventEmitter } from 'node:events'; const emitter = new EventEmitter(); emitter.setMaxListeners(emitter.getMaxListeners() + 1); emitter.once('event', () => { // do stuff emitter.setMaxListeners(Math.max(emitter.getMaxListeners() - 1, 0)); });const EventEmitter = require('node:events'); const emitter = new EventEmitter(); emitter.setMaxListeners(emitter.getMaxListeners() + 1); emitter.once('event', () => { // do stuff emitter.setMaxListeners(Math.max(emitter.getMaxListeners() - 1, 0)); });
The --trace-warnings command-line flag can be used to display the
stack trace for such warnings.
The emitted warning can be inspected with process.on('warning') and will
have the additional emitter, type, and count properties, referring to
the event emitter instance, the event's name and the number of attached
listeners, respectively.
Its name property is set to 'MaxListenersExceededWarning'.
events.errorMonitor#
This symbol shall be used to install a listener for only monitoring 'error'
events. Listeners installed using this symbol are called before the regular
'error' listeners are called.
Installing a listener using this symbol does not change the behavior once an
'error' event is emitted. Therefore, the process will still crash if no
regular 'error' listener is installed.
events.getEventListeners(emitterOrTarget, eventName)#
emitterOrTarget<EventEmitter>|<EventTarget>eventName<string>|<symbol>- Returns:
<Function>[]
Returns a copy of the array of listeners for the event named eventName.
For EventEmitters this behaves exactly the same as calling .listeners on
the emitter.
For EventTargets this is the only way to get the event listeners for the
event target. This is useful for debugging and diagnostic purposes.
import { getEventListeners, EventEmitter } from 'node:events'; { const ee = new EventEmitter(); const listener = () => console.log('Events are fun'); ee.on('foo', listener); console.log(getEventListeners(ee, 'foo')); // [ [Function: listener] ] } { const et = new EventTarget(); const listener = () => console.log('Events are fun'); et.addEventListener('foo', listener); console.log(getEventListeners(et, 'foo')); // [ [Function: listener] ] }const { getEventListeners, EventEmitter } = require('node:events'); { const ee = new EventEmitter(); const listener = () => console.log('Events are fun'); ee.on('foo', listener); console.log(getEventListeners(ee, 'foo')); // [ [Function: listener] ] } { const et = new EventTarget(); const listener = () => console.log('Events are fun'); et.addEventListener('foo', listener); console.log(getEventListeners(et, 'foo')); // [ [Function: listener] ] }
events.getMaxListeners(emitterOrTarget)#
emitterOrTarget<EventEmitter>|<EventTarget>- Returns:
<number>
Returns the currently set max amount of listeners.
For EventEmitters this behaves exactly the same as calling .getMaxListeners on
the emitter.
For EventTargets this is the only way to get the max event listeners for the
event target. If the number of event handlers on a single EventTarget exceeds
the max set, the EventTarget will print a warning.
import { getMaxListeners, setMaxListeners, EventEmitter } from 'node:events'; { const ee = new EventEmitter(); console.log(getMaxListeners(ee)); // 10 setMaxListeners(11, ee); console.log(getMaxListeners(ee)); // 11 } { const et = new EventTarget(); console.log(getMaxListeners(et)); // 10 setMaxListeners(11, et); console.log(getMaxListeners(et)); // 11 }const { getMaxListeners, setMaxListeners, EventEmitter } = require('node:events'); { const ee = new EventEmitter(); console.log(getMaxListeners(ee)); // 10 setMaxListeners(11, ee); console.log(getMaxListeners(ee)); // 11 } { const et = new EventTarget(); console.log(getMaxListeners(et)); // 10 setMaxListeners(11, et); console.log(getMaxListeners(et)); // 11 }
events.once(emitter, name[, options])#
emitter<EventEmitter>name<string>|<symbol>options<Object>signal<AbortSignal>Can be used to cancel waiting for the event.
- Returns:
<Promise>
Creates a Promise that is fulfilled when the EventEmitter emits the given
event or that is rejected if the EventEmitter emits 'error' while waiting.
The Promise will resolve with an array of all the arguments emitted to the
given event.
This method is intentionally generic and works with the web platform
EventTarget interface, which has no special
'error' event semantics and does not listen to the 'error' event.
import { once, EventEmitter } from 'node:events'; import process from 'node:process'; const ee = new EventEmitter(); process.nextTick(() => { ee.emit('myevent', 42); }); const [value] = await once(ee, 'myevent'); console.log(value); const err = new Error('kaboom'); process.nextTick(() => { ee.emit('error', err); }); try { await once(ee, 'myevent'); } catch (err) { console.error('error happened', err); }const { once, EventEmitter } = require('node:events'); async function run() { const ee = new EventEmitter(); process.nextTick(() => { ee.emit('myevent', 42); }); const [value] = await once(ee, 'myevent'); console.log(value); const err = new Error('kaboom'); process.nextTick(() => { ee.emit('error', err); }); try { await once(ee, 'myevent'); } catch (err) { console.error('error happened', err); } } run();
The special handling of the 'error' event is only used when events.once()
is used to wait for another event. If events.once() is used to wait for the
'error' event itself, then it is treated as any other kind of event without
special handling:
import { EventEmitter, once } from 'node:events'; const ee = new EventEmitter(); once(ee, 'error') .then(([err]) => console.log('ok', err.message)) .catch((err) => console.error('error', err.message)); ee.emit('error', new Error('boom')); // Prints: ok boomconst { EventEmitter, once } = require('node:events'); const ee = new EventEmitter(); once(ee, 'error') .then(([err]) => console.log('ok', err.message)) .catch((err) => console.error('error', err.message)); ee.emit('error', new Error('boom')); // Prints: ok boom
An <AbortSignal> can be used to cancel waiting for the event:
import { EventEmitter, once } from 'node:events'; const ee = new EventEmitter(); const ac = new AbortController(); async function foo(emitter, event, signal) { try { await once(emitter, event, { signal }); console.log('event emitted!'); } catch (error) { if (error.name === 'AbortError') { console.error('Waiting for the event was canceled!'); } else { console.error('There was an error', error.message); } } } foo(ee, 'foo', ac.signal); ac.abort(); // Prints: Waiting for the event was canceled!const { EventEmitter, once } = require('node:events'); const ee = new EventEmitter(); const ac = new AbortController(); async function foo(emitter, event, signal) { try { await once(emitter, event, { signal }); console.log('event emitted!'); } catch (error) { if (error.name === 'AbortError') { console.error('Waiting for the event was canceled!'); } else { console.error('There was an error', error.message); } } } foo(ee, 'foo', ac.signal); ac.abort(); // Prints: Waiting for the event was canceled!
Caveats when awaiting multiple events#
It is important to be aware of execution order when using the events.once()
method to await multiple events.
Conventional event listeners are called synchronously when the event is emitted. This guarantees that execution will not proceed beyond the emitted event until all listeners have finished executing.
The same is not true when awaiting Promises returned by events.once().
Promise tasks are not handled until after the current execution stack runs to
completion, which means that multiple events could be emitted before
asynchronous execution continues from the relevant await statement.
As a result, events can be "missed" if a series of await events.once()
statements is used to listen to multiple events, since there might be times
where more than one event is emitted during the same phase of the event loop.
(The same is true when using process.nextTick() to emit events, because the
tasks queued by process.nextTick() are executed before Promise tasks.)
import { EventEmitter, once } from 'node:events'; import process from 'node:process'; const myEE = new EventEmitter(); async function listen() { await once(myEE, 'foo'); console.log('foo'); // This Promise will never resolve, because the 'bar' event will // have already been emitted before the next line is executed. await once(myEE, 'bar'); console.log('bar'); } process.nextTick(() => { myEE.emit('foo'); myEE.emit('bar'); }); listen().then(() => console.log('done'));const { EventEmitter, once } = require('node:events'); const myEE = new EventEmitter(); async function listen() { await once(myEE, 'foo'); console.log('foo'); // This Promise will never resolve, because the 'bar' event will // have already been emitted before the next line is executed. await once(myEE, 'bar'); console.log('bar'); } process.nextTick(() => { myEE.emit('foo'); myEE.emit('bar'); }); listen().then(() => console.log('done'));
To catch multiple events, create all of the Promises before awaiting any of
them. This is usually made easier by using Promise.all(), Promise.race(),
or Promise.allSettled():
import { EventEmitter, once } from 'node:events'; import process from 'node:process'; const myEE = new EventEmitter(); async function listen() { await Promise.all([ once(myEE, 'foo'), once(myEE, 'bar'), ]); console.log('foo', 'bar'); } process.nextTick(() => { myEE.emit('foo'); myEE.emit('bar'); }); listen().then(() => console.log('done'));const { EventEmitter, once } = require('node:events'); const myEE = new EventEmitter(); async function listen() { await Promise.all([ once(myEE, 'bar'), once(myEE, 'foo'), ]); console.log('foo', 'bar'); } process.nextTick(() => { myEE.emit('foo'); myEE.emit('bar'); }); listen().then(() => console.log('done'));
events.captureRejections#
- Type:
<boolean>
Change the default captureRejections option on all new EventEmitter objects.
events.captureRejectionSymbol#
- Type:
<symbol>Symbol.for('nodejs.rejection')
See how to write a custom rejection handler.
events.listenerCount(emitterOrTarget, eventName)#
emitterOrTarget<EventEmitter>|<EventTarget>eventName<string>|<symbol>- Returns:
<integer>
Returns the number of registered listeners for the event named eventName.
For EventEmitters this behaves exactly the same as calling .listenerCount
on the emitter.
For EventTargets this is the only way to obtain the listener count. This can
be useful for debugging and diagnostic purposes.
import { EventEmitter, listenerCount } from 'node:events'; { const ee = new EventEmitter(); ee.on('event', () => {}); ee.on('event', () => {}); console.log(listenerCount(ee, 'event')); // 2 } { const et = new EventTarget(); et.addEventListener('event', () => {}); et.addEventListener('event', () => {}); console.log(listenerCount(et, 'event')); // 2 }const { EventEmitter, listenerCount } = require('node:events'); { const ee = new EventEmitter(); ee.on('event', () => {}); ee.on('event', () => {}); console.log(listenerCount(ee, 'event')); // 2 } { const et = new EventTarget(); et.addEventListener('event', () => {}); et.addEventListener('event', () => {}); console.log(listenerCount(et, 'event')); // 2 }
events.on(emitter, eventName[, options])#
emitter<EventEmitter>eventName<string>|<symbol>The name of the event being listened foroptions<Object>signal<AbortSignal>Can be used to cancel awaiting events.close<string>[] Names of events that will end the iteration.highWaterMark<integer>Default:Number.MAX_SAFE_INTEGERThe high watermark. The emitter is paused every time the size of events being buffered is higher than it. Supported only on emitters implementingpause()andresume()methods.lowWaterMark<integer>Default:1The low watermark. The emitter is resumed every time the size of events being buffered is lower than it. Supported only on emitters implementingpause()andresume()methods.
- Returns:
<AsyncIterator>that iterateseventNameevents emitted by theemitter
import { on, EventEmitter } from 'node:events'; import process from 'node:process'; const ee = new EventEmitter(); // Emit later on process.nextTick(() => { ee.emit('foo', 'bar'); ee.emit('foo', 42); }); for await (const event of on(ee, 'foo')) { // The execution of this inner block is synchronous and it // processes one event at a time (even with await). Do not use // if concurrent execution is required. console.log(event); // prints ['bar'] [42] } // Unreachable hereconst { on, EventEmitter } = require('node:events'); (async () => { const ee = new EventEmitter(); // Emit later on process.nextTick(() => { ee.emit('foo', 'bar'); ee.emit('foo', 42); }); for await (const event of on(ee, 'foo')) { // The execution of this inner block is synchronous and it // processes one event at a time (even with await). Do not use // if concurrent execution is required. console.log(event); // prints ['bar'] [42] } // Unreachable here })();
Returns an AsyncIterator that iterates eventName events. It will throw
if the EventEmitter emits 'error'. It removes all listeners when
exiting the loop. The value returned by each iteration is an array
composed of the emitted event arguments.
An <AbortSignal> can be used to cancel waiting on events:
import { on, EventEmitter } from 'node:events'; import process from 'node:process'; const ac = new AbortController(); (async () => { const ee = new EventEmitter(); // Emit later on process.nextTick(() => { ee.emit('foo', 'bar'); ee.emit('foo', 42); }); for await (const event of on(ee, 'foo', { signal: ac.signal })) { // The execution of this inner block is synchronous and it // processes one event at a time (even with await). Do not use // if concurrent execution is required. console.log(event); // prints ['bar'] [42] } // Unreachable here })(); process.nextTick(() => ac.abort());const { on, EventEmitter } = require('node:events'); const ac = new AbortController(); (async () => { const ee = new EventEmitter(); // Emit later on process.nextTick(() => { ee.emit('foo', 'bar'); ee.emit('foo', 42); }); for await (const event of on(ee, 'foo', { signal: ac.signal })) { // The execution of this inner block is synchronous and it // processes one event at a time (even with await). Do not use // if concurrent execution is required. console.log(event); // prints ['bar'] [42] } // Unreachable here })(); process.nextTick(() => ac.abort());
events.setMaxListeners(n[, ...eventTargets])#
n<number>A non-negative number. The maximum number of listeners perEventTargetevent....eventsTargets<EventTarget>[] |<EventEmitter>[] Zero or more<EventTarget>or<EventEmitter>instances. If none are specified,nis set as the default max for all newly created<EventTarget>and<EventEmitter>objects.
import { setMaxListeners, EventEmitter } from 'node:events'; const target = new EventTarget(); const emitter = new EventEmitter(); setMaxListeners(5, target, emitter);const { setMaxListeners, EventEmitter, } = require('node:events'); const target = new EventTarget(); const emitter = new EventEmitter(); setMaxListeners(5, target, emitter);
events.addAbortListener(signal, listener)#
signal<AbortSignal>listener<Function>|<EventListener>- Returns:
<Disposable>A Disposable that removes theabortlistener.
Listens once to the abort event on the provided signal.
Listening to the abort event on abort signals is unsafe and may
lead to resource leaks since another third party with the signal can
call e.stopImmediatePropagation(). Unfortunately Node.js cannot change
this since it would violate the web standard. Additionally, the original
API makes it easy to forget to remove listeners.
This API allows safely using AbortSignals in Node.js APIs by solving these
two issues by listening to the event such that stopImmediatePropagation does
not prevent the listener from running.
Returns a disposable so that it may be unsubscribed from more easily.
const { addAbortListener } = require('node:events'); function example(signal) { signal.addEventListener('abort', (e) => e.stopImmediatePropagation()); // addAbortListener() returns a disposable, so the `using` keyword ensures // the abort listener is automatically removed when this scope exits. using _ = addAbortListener(signal, (e) => { // Do something when signal is aborted. }); }import { addAbortListener } from 'node:events'; function example(signal) { signal.addEventListener('abort', (e) => e.stopImmediatePropagation()); // addAbortListener() returns a disposable, so the `using` keyword ensures // the abort listener is automatically removed when this scope exits. using _ = addAbortListener(signal, (e) => { // Do something when signal is aborted. }); }
Class: events.EventEmitterAsyncResource extends EventEmitter#
Integrates EventEmitter with <AsyncResource> for EventEmitters that
require manual async tracking. Specifically, all events emitted by instances
of events.EventEmitterAsyncResource will run within its async context.
import { EventEmitterAsyncResource, EventEmitter } from 'node:events'; import { notStrictEqual, strictEqual } from 'node:assert'; import { executionAsyncId, triggerAsyncId } from 'node:async_hooks'; // Async tracking tooling will identify this as 'Q'. const ee1 = new EventEmitterAsyncResource({ name: 'Q' }); // 'foo' listeners will run in the EventEmitters async context. ee1.on('foo', () => { strictEqual(executionAsyncId(), ee1.asyncId); strictEqual(triggerAsyncId(), ee1.triggerAsyncId); }); const ee2 = new EventEmitter(); // 'foo' listeners on ordinary EventEmitters that do not track async // context, however, run in the same async context as the emit(). ee2.on('foo', () => { notStrictEqual(executionAsyncId(), ee2.asyncId); notStrictEqual(triggerAsyncId(), ee2.triggerAsyncId); }); Promise.resolve().then(() => { ee1.emit('foo'); ee2.emit('foo'); });const { EventEmitterAsyncResource, EventEmitter } = require('node:events'); const { notStrictEqual, strictEqual } = require('node:assert'); const { executionAsyncId, triggerAsyncId } = require('node:async_hooks'); // Async tracking tooling will identify this as 'Q'. const ee1 = new EventEmitterAsyncResource({ name: 'Q' }); // 'foo' listeners will run in the EventEmitters async context. ee1.on('foo', () => { strictEqual(executionAsyncId(), ee1.asyncId); strictEqual(triggerAsyncId(), ee1.triggerAsyncId); }); const ee2 = new EventEmitter(); // 'foo' listeners on ordinary EventEmitters that do not track async // context, however, run in the same async context as the emit(). ee2.on('foo', () => { notStrictEqual(executionAsyncId(), ee2.asyncId); notStrictEqual(triggerAsyncId(), ee2.triggerAsyncId); }); Promise.resolve().then(() => { ee1.emit('foo'); ee2.emit('foo'); });
The EventEmitterAsyncResource class has the same methods and takes the
same options as EventEmitter and AsyncResource themselves.
new events.EventEmitterAsyncResource([options])#
options<Object>captureRejections<boolean>It enables automatic capturing of promise rejection. Default:false.name<string>The type of async event. Default:new.target.name.triggerAsyncId<number>The ID of the execution context that created this async event. Default:executionAsyncId().requireManualDestroy<boolean>If set totrue, disablesemitDestroywhen the object is garbage collected. This usually does not need to be set (even ifemitDestroyis called manually), unless the resource'sasyncIdis retrieved and the sensitive API'semitDestroyis called with it. When set tofalse, theemitDestroycall on garbage collection will only take place if there is at least one activedestroyhook. Default:false.
eventemitterasyncresource.asyncId#
- Type:
<number>The uniqueasyncIdassigned to the resource.
eventemitterasyncresource.asyncResource#
- Type:
<AsyncResource>The underlying<AsyncResource>.
The returned AsyncResource object has an additional eventEmitter property
that provides a reference to this EventEmitterAsyncResource.
eventemitterasyncresource.emitDestroy()#
Call all destroy hooks. This should only ever be called once. An error will
be thrown if it is called more than once. This must be manually called. If
the resource is left to be collected by the GC then the destroy hooks will
never be called.
eventemitterasyncresource.triggerAsyncId#
- Type:
<number>The sametriggerAsyncIdthat is passed to theAsyncResourceconstructor.
EventTarget and Event API#
The EventTarget and Event objects are a Node.js-specific implementation
of the EventTarget Web API that are exposed by some Node.js core APIs.
const target = new EventTarget();
target.addEventListener('foo', (event) => {
console.log('foo event happened!');
});
Node.js EventTarget vs. DOM EventTarget#
There are two key differences between the Node.js EventTarget and the
EventTarget Web API:
- Whereas DOM
EventTargetinstances may be hierarchical, there is no concept of hierarchy and event propagation in Node.js. That is, an event dispatched to anEventTargetdoes not propagate through a hierarchy of nested target objects that may each have their own set of handlers for the event. - In the Node.js
EventTarget, if an event listener is an async function or returns aPromise, and the returnedPromiserejects, the rejection is automatically captured and handled the same way as a listener that throws synchronously (seeEventTargeterror handling for details).
NodeEventTarget vs. EventEmitter#
The NodeEventTarget object implements a modified subset of the
EventEmitter API that allows it to closely emulate an EventEmitter in
certain situations. A NodeEventTarget is not an instance of EventEmitter
and cannot be used in place of an EventEmitter in most cases.
- Unlike
EventEmitter, any givenlistenercan be registered at most once per eventtype. Attempts to register alistenermultiple times are ignored. - The
NodeEventTargetdoes not emulate the fullEventEmitterAPI. Specifically theprependListener(),prependOnceListener(),rawListeners(), anderrorMonitorAPIs are not emulated. The'newListener'and'removeListener'events will also not be emitted. - The
NodeEventTargetdoes not implement any special default behavior for events with type'error'. - The
NodeEventTargetsupportsEventListenerobjects as well as functions as handlers for all event types.
Event listener#
Event listeners registered for an event type may either be JavaScript
functions or objects with a handleEvent property whose value is a function.
In either case, the handler function is invoked with the event argument
passed to the eventTarget.dispatchEvent() function.
Async functions may be used as event listeners. If an async handler function
rejects, the rejection is captured and handled as described in
EventTarget error handling.
An error thrown by one handler function does not prevent the other handlers from being invoked.
The return value of a handler function is ignored.
Handlers are always invoked in the order they were added.
Handler functions may mutate the event object.
function handler1(event) {
console.log(event.type); // Prints 'foo'
event.a = 1;
}
async function handler2(event) {
console.log(event.type); // Prints 'foo'
console.log(event.a); // Prints 1
}
const handler3 = {
handleEvent(event) {
console.log(event.type); // Prints 'foo'
},
};
const handler4 = {
async handleEvent(event) {
console.log(event.type); // Prints 'foo'
},
};
const target = new EventTarget();
target.addEventListener('foo', handler1);
target.addEventListener('foo', handler2);
target.addEventListener('foo', handler3);
target.addEventListener('foo', handler4, { once: true });
EventTarget error handling#
When a registered event listener throws (or returns a Promise that rejects),
by default the error is treated as an uncaught exception on
process.nextTick(). This means uncaught exceptions in EventTargets will
terminate the Node.js process by default.
Throwing within an event listener will not stop the other registered handlers from being invoked.
The EventTarget does not implement any special default handling for 'error'
type events like EventEmitter.
Currently errors are first forwarded to the process.on('error') event
before reaching process.on('uncaughtException'). This behavior is
deprecated and will change in a future release to align EventTarget with
other Node.js APIs. Any code relying on the process.on('error') event should
be aligned with the new behavior.
Class: Event#
The Event object is an adaptation of the Event Web API. Instances
are created internally by Node.js.
event.bubbles#
- Type:
<boolean>Always returnsfalse.
This is not used in Node.js and is provided purely for completeness.
event.cancelBubble#
Stability: 3 - Legacy: Use event.stopPropagation() instead.
- Type:
<boolean>
Alias for event.stopPropagation() if set to true. This is not used
in Node.js and is provided purely for completeness.
event.cancelable#
- Type:
<boolean>True if the event was created with thecancelableoption.
event.composed#
- Type:
<boolean>Always returnsfalse.
This is not used in Node.js and is provided purely for completeness.
event.composedPath()#
Returns an array containing the current EventTarget as the only entry or
empty if the event is not being dispatched. This is not used in
Node.js and is provided purely for completeness.
event.currentTarget#
- Type:
<EventTarget>TheEventTargetdispatching the event.
Alias for event.target.
event.defaultPrevented#
- Type:
<boolean>
Is true if cancelable is true and event.preventDefault() has been
called.
event.eventPhase#
- Type:
<number>Returns0while an event is not being dispatched,2while it is being dispatched.
This is not used in Node.js and is provided purely for completeness.
event.initEvent(type[, bubbles[, cancelable]])#
Stability: 3 - Legacy: The WHATWG spec considers it deprecated and users shouldn't use it at all.
Redundant with event constructors and incapable of setting composed.
This is not used in Node.js and is provided purely for completeness.
event.isTrusted#
- Type:
<boolean>
The <AbortSignal> "abort" event is emitted with isTrusted set to true. The
value is false in all other cases.
event.preventDefault()#
Sets the defaultPrevented property to true if cancelable is true.
event.returnValue#
Stability: 3 - Legacy: Use event.defaultPrevented instead.
- Type:
<boolean>True if the event has not been canceled.
The value of event.returnValue is always the opposite of event.defaultPrevented.
This is not used in Node.js and is provided purely for completeness.
event.srcElement#
Stability: 3 - Legacy: Use event.target instead.
- Type:
<EventTarget>TheEventTargetdispatching the event.
Alias for event.target.
event.stopImmediatePropagation()#
Stops the invocation of event listeners after the current one completes.
event.stopPropagation()#
This is not used in Node.js and is provided purely for completeness.
event.target#
- Type:
<EventTarget>TheEventTargetdispatching the event.
event.timeStamp#
- Type:
<number>
The millisecond timestamp when the Event object was created.
event.type#
- Type:
<string>
The event type identifier.
Class: EventTarget#
eventTarget.addEventListener(type, listener[, options])#
type<string>listener<Function>|<EventListener>options<Object>once<boolean>Whentrue, the listener is automatically removed when it is first invoked. Default:false.passive<boolean>Whentrue, serves as a hint that the listener will not call theEventobject'spreventDefault()method. Default:false.capture<boolean>Not directly used by Node.js. Added for API completeness. Default:false.signal<AbortSignal>The listener will be removed when the given AbortSignal object'sabort()method is called.
Adds a new handler for the type event. Any given listener is added
only once per type and per capture option value.
If the once option is true, the listener is removed after the
next time a type event is dispatched.
The capture option is not used by Node.js in any functional way other than
tracking registered event listeners per the EventTarget specification.
Specifically, the capture option is used as part of the key when registering
a listener. Any individual listener may be added once with
capture = false, and once with capture = true.
function handler(event) {}
const target = new EventTarget();
target.addEventListener('foo', handler, { capture: true }); // first
target.addEventListener('foo', handler, { capture: false }); // second
// Removes the second instance of handler
target.removeEventListener('foo', handler);
// Removes the first instance of handler
target.removeEventListener('foo', handler, { capture: true });
eventTarget.dispatchEvent(event)#
event<Event>- Returns:
<boolean>trueif either event'scancelableattribute value is false or itspreventDefault()method was not invoked, otherwisefalse.
Dispatches the event to the list of handlers for event.type.
The registered event listeners is synchronously invoked in the order they were registered.
eventTarget.removeEventListener(type, listener[, options])#
type<string>listener<Function>|<EventListener>options<Object>capture<boolean>
Removes the listener from the list of handlers for event type.
Class: CustomEvent#
- Extends:
<Event>
The CustomEvent object is an adaptation of the CustomEvent Web API.
Instances are created internally by Node.js.
event.detail#
- Type:
<any>Returns custom data passed when initializing.
Read-only.
Class: NodeEventTarget#
- Extends:
<EventTarget>
The NodeEventTarget is a Node.js-specific extension to EventTarget
that emulates a subset of the EventEmitter API.
nodeEventTarget.addListener(type, listener)#
-
type<string> -
listener<Function>|<EventListener> -
Returns:
<EventTarget>this
Node.js-specific extension to the EventTarget class that emulates the
equivalent EventEmitter API. The only difference between addListener() and
addEventListener() is that addListener() will return a reference to the
EventTarget.
nodeEventTarget.emit(type, arg)#
type<string>arg<any>- Returns:
<boolean>trueif event listeners registered for thetypeexist, otherwisefalse.
Node.js-specific extension to the EventTarget class that dispatches the
arg to the list of handlers for type.
nodeEventTarget.eventNames()#
- Returns:
<string>[]
Node.js-specific extension to the EventTarget class that returns an array
of event type names for which event listeners are registered.
nodeEventTarget.listenerCount(type)#
Node.js-specific extension to the EventTarget class that returns the number
of event listeners registered for the type.
nodeEventTarget.setMaxListeners(n)#
n<number>
Node.js-specific extension to the EventTarget class that sets the number
of max event listeners as n.
nodeEventTarget.getMaxListeners()#
- Returns:
<number>
Node.js-specific extension to the EventTarget class that returns the number
of max event listeners.
nodeEventTarget.off(type, listener[, options])#
-
type<string> -
listener<Function>|<EventListener> -
options<Object>capture<boolean>
-
Returns:
<EventTarget>this
Node.js-specific alias for eventTarget.removeEventListener().
nodeEventTarget.on(type, listener)#
-
type<string> -
listener<Function>|<EventListener> -
Returns:
<EventTarget>this
Node.js-specific alias for eventTarget.addEventListener().
nodeEventTarget.once(type, listener)#
-
type<string> -
listener<Function>|<EventListener> -
Returns:
<EventTarget>this
Node.js-specific extension to the EventTarget class that adds a once
listener for the given event type. This is equivalent to calling on
with the once option set to true.
nodeEventTarget.removeAllListeners([type])#
-
type<string> -
Returns:
<EventTarget>this
Node.js-specific extension to the EventTarget class. If type is specified,
removes all registered listeners for type, otherwise removes all registered
listeners.
nodeEventTarget.removeListener(type, listener[, options])#
-
type<string> -
listener<Function>|<EventListener> -
options<Object>capture<boolean>
-
Returns:
<EventTarget>this
Node.js-specific extension to the EventTarget class that removes the
listener for the given type. The only difference between removeListener()
and removeEventListener() is that removeListener() will return a reference
to the EventTarget.
FFI#
Stability: 1 - Experimental
The node:ffi module provides an experimental foreign function interface for
loading dynamic libraries and calling native symbols from JavaScript.
This API is unsafe. Passing invalid pointers, using an incorrect symbol signature, or accessing memory after it has been freed can crash the process or corrupt memory.
To access it:
import ffi from 'node:ffi';const ffi = require('node:ffi');
This module is only available under the node: scheme in builds with FFI
support and is gated by the --experimental-ffi flag.
Building Node.js with node:ffi support is available via the bundled libffi on
platforms where libffi provides a compatible static backend, or via a
shared libffi using the --shared-ffi configure flag.
The unofficial GN build does not support node:ffi.
The following targets are not supported by bundled libffi:
s390x.mips,mipsel, andmips64elon targets other than FreeBSD, Linux, and OpenBSD.ppc64on Android, CloudABI, iOS, OpenHarmony, OS/400, Solaris, and Windows.
When using the Permission Model, FFI APIs are
restricted unless the --allow-ffi flag is provided.
Overview#
The node:ffi module exposes two groups of APIs:
- Dynamic library APIs for loading libraries, resolving symbols, and creating callable JavaScript wrappers.
- Raw memory helpers for reading and writing primitive values through pointers,
converting pointers to JavaScript strings,
Bufferinstances, andArrayBufferinstances, and for copying data back into native memory.
Type names#
FFI signatures use string type names.
Supported type names:
voidchari8,int8u8,uint8,booli16,int16u16,uint16i32,int32u32,uint32i64,int64u64,uint64f32,float,float32f64,double,float64pointer,ptrstring,strbufferarraybufferfunction
These type names are also exposed as constants on ffi.types:
ffi.types.VOID='void'ffi.types.POINTER='pointer'ffi.types.BUFFER='buffer'ffi.types.ARRAY_BUFFER='arraybuffer'ffi.types.FUNCTION='function'ffi.types.BOOL='bool'ffi.types.CHAR='char'ffi.types.STRING='string'ffi.types.FLOAT='float'ffi.types.DOUBLE='double'ffi.types.INT_8='int8'ffi.types.UINT_8='uint8'ffi.types.INT_16='int16'ffi.types.UINT_16='uint16'ffi.types.INT_32='int32'ffi.types.UINT_32='uint32'ffi.types.INT_64='int64'ffi.types.UINT_64='uint64'ffi.types.FLOAT_32='float32'ffi.types.FLOAT_64='float64'
Pointer-like types (pointer, string, buffer, arraybuffer, and
function) are all passed through the native layer as pointers.
When Buffer, ArrayBuffer, or typed array values are passed as pointer-like
arguments, Node.js borrows a raw pointer to their backing memory for the
duration of the native call. The caller must ensure that backing store remains
valid and stable for the entire call.
It is unsupported and dangerous to resize, transfer, detach, or otherwise invalidate that backing store while the native call is active, including through reentrant JavaScript such as FFI callbacks. Doing so may crash the process, produce incorrect output, or corrupt memory.
The char type follows the platform C ABI. On platforms where plain C char
is signed it behaves like i8; otherwise it behaves like u8.
The bool type is marshaled as an 8-bit unsigned integer. Pass numeric values
such as 0 and 1; JavaScript true and false are not accepted.
On optimized Fast FFI calls, pointer, ptr, and function parameters accept
raw pointer bigint values. For pointer-like parameters, null, undefined,
strings, Buffer, typed array, DataView, and ArrayBuffer values are
converted on the JavaScript side before calling the optimized native wrapper.
Optimized Fast FFI calls support at most 8 function arguments, but the exact limit depends on the architecture and on the argument types, because each argument must fit in the registers used by the platform trampoline. Integer and pointer arguments are limited to 7 on AArch64 and to 6 on x86-64, while floating-point arguments can use up to 8 on both. Functions that exceed these limits, including any function with more than 8 arguments, use the generic FFI call path instead.
Signature objects#
Functions and callbacks are described with signature objects.
Signature objects may contain the following properties, both of which are optional:
return<string>A type name specifying the return type of the function or callback. Default:'void'.arguments<string>[] An array of type names specifying the argument type list of the function or callback. Default:[].
const signature = {
return: 'i32',
arguments: ['i32', 'i32'],
};
ffi.suffix#
The native shared library suffix for the current platform:
'dylib'on macOS'so'on Unix-like platforms'dll'on Windows
This can be used to build portable library paths:
const { suffix } = require('node:ffi');
const path = `libsqlite3.${suffix}`;
ffi.dlopen(path[, definitions])#
path<string>|<null>Path to a dynamic library, ornullto resolve symbols from the current process image.definitions<Object>Symbol definitions to resolve immediately.- Returns:
<Object>
Loads a dynamic library and resolves the requested function definitions.
On Windows passing null is not supported.
When definitions is omitted, functions is returned as an empty object until
symbols are resolved explicitly.
The returned object contains:
lib<DynamicLibrary>The loaded library handle.functions<Object>Callable wrappers for the requested symbols.
The returned object also implements the explicit resource management protocol,
so it can be used with the using declaration. Disposing the returned
object closes the library handle.
import { dlopen, suffix } from 'node:ffi';
{
using handle = dlopen(`./mylib.${suffix}`, {
add_i32: { arguments: ['i32', 'i32'], return: 'i32' },
});
console.log(handle.functions.add_i32(20, 22));
} // handle.lib.close() is invoked automatically here.
import { dlopen, suffix } from 'node:ffi'; const { lib, functions } = dlopen(`./mylib.${suffix}`, { add_i32: { arguments: ['i32', 'i32'], return: 'i32' }, string_length: { arguments: ['pointer'], return: 'u64' }, }); console.log(functions.add_i32(20, 22));const { dlopen, suffix } = require('node:ffi'); const { lib, functions } = dlopen(`./mylib.${suffix}`, { add_i32: { arguments: ['i32', 'i32'], return: 'i32' }, string_length: { arguments: ['pointer'], return: 'u64' }, }); console.log(functions.add_i32(20, 22));
ffi.dlclose(handle)#
handle<DynamicLibrary>
Closes a dynamic library.
This is equivalent to calling handle.close().
ffi.dlsym(handle, symbol)#
handle<DynamicLibrary>symbol<string>- Returns:
<bigint>
Resolves a symbol address from a loaded library.
This is equivalent to calling handle.getSymbol(symbol).
Class: DynamicLibrary#
Represents a loaded dynamic library.
new DynamicLibrary(path)#
path<string>|<null>Path to a dynamic library, ornullto resolve symbols from the current process image.
Loads the dynamic library without resolving any functions eagerly.
On Windows passing null is not supported.
const { DynamicLibrary, suffix } = require('node:ffi');
const lib = new DynamicLibrary(`./mylib.${suffix}`);
library.path#
The path used to load the library.
library.functions#
An object containing previously resolved function wrappers.
library.symbols#
An object containing previously resolved symbol addresses as bigint values.
library.close()#
Closes the library handle.
DynamicLibrary implements the explicit resource management protocol, so a
library instance can be managed with the using declaration. Leaving the
enclosing scope invokes library.close() automatically.
import { DynamicLibrary, suffix } from 'node:ffi';
{
using lib = new DynamicLibrary(`./mylib.${suffix}`);
// Use `lib` here; `lib.close()` is called when the block exits.
}
Calling library.close() (or disposing the library) more than once is a no-op.
After a library has been closed:
- Resolved function wrappers become invalid.
- Further symbol and function resolution throws.
- Registered callbacks are invalidated.
Closing a library does not make previously exported callback pointers safe to reuse. Node.js does not track or revoke callback pointers that have already been handed to native code.
If native code still holds a callback pointer after library.close() or after
library.unregisterCallback(pointer), invoking that pointer has undefined
behavior, is not allowed, and is dangerous: it can crash the process, produce
incorrect output, or corrupt memory. Native code must stop using callback
addresses before the library is closed or before the callback is unregistered.
Calling library.close() from one of the library's active callbacks is
unsupported and dangerous. The callback must return before the library is
closed.
library[Symbol.dispose]()#
Calls library.close(). This allows DynamicLibrary instances to be used with
the using declaration for automatic cleanup when the enclosing scope
exits. It is a no-op on a library that has already been closed.
library.getFunction(name, signature)#
name<string>signature<Object>- Returns:
<Function>
Resolves a symbol and returns a callable JavaScript wrapper.
The returned function has a .pointer property containing the native function
address as a bigint.
If the same symbol has already been resolved, requesting it again with a different signature throws.
const { DynamicLibrary, suffix } = require('node:ffi');
const lib = new DynamicLibrary(`./mylib.${suffix}`);
const add = lib.getFunction('add_i32', {
arguments: ['i32', 'i32'],
return: 'i32',
});
console.log(add(20, 22));
console.log(add.pointer);
library.getFunctions([definitions])#
When definitions is provided, resolves each named symbol and returns an
object containing callable wrappers.
When definitions is omitted, returns wrappers for all functions that have
already been resolved on the library.
library.getSymbol(name)#
Resolves a symbol and returns its native address as a bigint.
library.getSymbols()#
- Returns:
<Object>
Returns an object containing all previously resolved symbol addresses.
library.registerCallback([signature,] callback)#
signature<Object>callback<Function>- Returns:
<bigint>
Creates a native callback pointer backed by a JavaScript function.
When signature is omitted, the callback uses a default void () signature.
The return value is the callback pointer address as a bigint. It can be
passed to native functions expecting a callback pointer.
const { DynamicLibrary, suffix } = require('node:ffi');
const lib = new DynamicLibrary(`./mylib.${suffix}`);
const callback = lib.registerCallback(
{ arguments: ['i32'], return: 'i32' },
(value) => value * 2,
);
Callbacks are subject to the following restrictions:
- They must be invoked on the same system thread where they were created.
- They must not throw exceptions.
- They must not return promises.
- They must return a value compatible with the declared return type.
- They must not call
library.close()on their owning library while running. - They must not unregister themselves while running.
Closing the owning library or unregistering the currently executing callback from inside the callback is unsupported and dangerous. Doing so may crash the process, produce incorrect output, or corrupt memory.
library.unregisterCallback(pointer)#
pointer<bigint>
Releases a callback previously created with library.registerCallback().
Calling library.unregisterCallback(pointer) for a callback that is currently
executing is unsupported and dangerous. The callback must return before it is
unregistered.
After library.unregisterCallback(pointer) returns, invoking that callback
pointer from native code has undefined behavior, is not allowed, and is
dangerous: it can crash the process, produce incorrect output, or corrupt
memory.
library.refCallback(pointer)#
pointer<bigint>
Keeps the callback strongly referenced by JavaScript.
Throws ERR_INVALID_ARG_VALUE if the callback function has already been
garbage collected after a previous library.unrefCallback(pointer) call, since
a collected function cannot be referenced again.
library.unrefCallback(pointer)#
pointer<bigint>
Allows the callback to become weakly referenced by JavaScript.
If the callback function is later garbage collected, subsequent native invocations become a no-op. Non-void return values are zero-initialized before returning to native code.
Throws ERR_INVALID_ARG_VALUE if the callback function has already been
garbage collected.
Calling native functions#
Argument conversion depends on the declared FFI type.
For 8-, 16-, and 32-bit integer types and for floating-point types, pass
JavaScript number values that match the declared type.
For 64-bit integer types (i64 and u64), pass JavaScript bigint values.
For pointer-like arguments:
nullandundefinedare passed as null pointers.stringvalues are copied to temporary NUL-terminated UTF-8 strings for the duration of the call.Buffer, typed arrays, andDataViewinstances pass a pointer to their backing memory.ArrayBufferpasses a pointer to its backing memory.bigintvalues are passed as raw pointer addresses.
Pointer return values are exposed as bigint addresses.
Primitive memory access helpers#
The following helpers read and write primitive values at a native pointer, optionally with a byte offset:
ffi.getInt8(pointer[, offset])ffi.getUint8(pointer[, offset])ffi.getInt16(pointer[, offset])ffi.getUint16(pointer[, offset])ffi.getInt32(pointer[, offset])ffi.getUint32(pointer[, offset])ffi.getInt64(pointer[, offset])ffi.getUint64(pointer[, offset])ffi.getFloat32(pointer[, offset])ffi.getFloat64(pointer[, offset])ffi.setInt8(pointer, offset, value)ffi.setUint8(pointer, offset, value)ffi.setInt16(pointer, offset, value)ffi.setUint16(pointer, offset, value)ffi.setInt32(pointer, offset, value)ffi.setUint32(pointer, offset, value)ffi.setInt64(pointer, offset, value)ffi.setUint64(pointer, offset, value)ffi.setFloat32(pointer, offset, value)ffi.setFloat64(pointer, offset, value)
These helpers perform direct memory reads and writes. pointer must be a
bigint referring to valid readable or writable native memory. offset, when
provided, is interpreted as a byte offset from pointer.
The getter helpers return JavaScript number values for 8-, 16-, and 32-bit
integer types and for floating-point types. They return bigint values for
64-bit integer types.
The setter helpers require an explicit byte offset and validate the supplied
JavaScript value against the target native type before writing it into memory.
For setInt64() and setUint64(), bigint values are accepted directly;
numeric inputs must be integers within JavaScript's safe integer range.
const {
getInt32,
setInt32,
} = require('node:ffi');
setInt32(ptr, 0, 42);
console.log(getInt32(ptr, 0));
Like the other raw memory helpers in this module, these APIs do not track ownership, bounds, or lifetime. Passing an invalid pointer, using the wrong offset, or writing through a stale pointer can corrupt memory or crash the process.
ffi.toString(pointer)#
Reads a NUL-terminated UTF-8 string from native memory.
If pointer is 0n, null is returned.
This function does not validate that pointer refers to readable memory or
that the pointed-to data is terminated with \0. Passing an invalid pointer,
a pointer to freed memory, or a pointer to bytes without a terminating NUL can
read unrelated memory, crash the process, or produce truncated or garbled
output.
const { toString } = require('node:ffi');
const value = toString(ptr);
ffi.toBuffer(pointer, length[, copy])#
pointer<bigint>length<number>copy<boolean>Whenfalse, creates a zero-copy view. Default:true.- Returns:
<Buffer>
Creates a Buffer from native memory.
When copy is true, the returned Buffer owns its own copied memory.
When copy is false, the returned Buffer references the original native
memory directly.
Using copy: false is a zero-copy escape hatch. The returned Buffer is a
writable view onto foreign memory, so writes in JavaScript update the original
native memory directly. The caller must guarantee that:
pointerremains valid for the entire lifetime of the returnedBuffer.lengthstays within the allocated native region.- no native code frees or repurposes that memory while JavaScript still uses
the
Buffer. - Memory protection is observed. For example, read-only memory pages must not be written to.
If these guarantees are not met, reading or writing the Buffer can corrupt
memory or crash the process.
ffi.toArrayBuffer(pointer, length[, copy])#
pointer<bigint>length<number>copy<boolean>Whenfalse, creates a zero-copy view. Default:true.- Returns:
<ArrayBuffer>
Creates an ArrayBuffer from native memory.
When copy is true, the returned ArrayBuffer contains copied bytes.
When copy is false, the returned ArrayBuffer references the original
native memory directly.
The same lifetime and bounds requirements described for
ffi.toBuffer(pointer, length, copy) apply
here. With copy: false, the
returned ArrayBuffer is a zero-copy view of foreign memory and is only safe
while that memory remains allocated, unchanged in layout, and valid for the
entire exposed range.
ffi.exportString(string, pointer, length[, encoding])#
Copies a JavaScript string into native memory and appends a trailing NUL terminator.
length must be large enough to hold the full encoded string plus the trailing
NUL terminator. For UTF-16 and UCS-2 encodings, the trailing terminator uses
two zero bytes.
pointer must refer to writable native memory with at least length bytes of
available storage. This function does not allocate memory on its own.
string must be a JavaScript string. encoding must be a string.
ffi.exportBuffer(buffer, pointer, length)#
Copies bytes from a Buffer into native memory.
length must be at least buffer.length.
pointer must refer to writable native memory with at least length bytes of
available storage. This function does not allocate memory on its own.
buffer must be a Node.js Buffer.
ffi.exportArrayBuffer(arrayBuffer, pointer, length)#
arrayBuffer<ArrayBuffer>pointer<bigint>length<number>
Copies bytes from an ArrayBuffer into native memory.
length must be at least arrayBuffer.byteLength.
pointer must refer to writable native memory with at least length bytes of
available storage. This function does not allocate memory on its own.
ffi.exportArrayBufferView(arrayBufferView, pointer, length)#
arrayBufferView<ArrayBufferView>pointer<bigint>length<number>
Copies bytes from an ArrayBufferView into native memory.
length must be at least arrayBufferView.byteLength.
pointer must refer to writable native memory with at least length bytes of
available storage. This function does not allocate memory on its own.
ffi.getRawPointer(source)#
source<Buffer>|<ArrayBuffer>|<ArrayBufferView>- Returns:
<bigint>
Returns the raw memory address of JavaScript-managed byte storage.
This is unsafe and dangerous. The returned pointer can become invalid if the underlying memory is detached, resized, transferred, or otherwise invalidated. Using stale pointers can cause memory corruption or process crashes.
ffi.getCurrentEventLoop()#
- Returns:
<bigint>
Returns the address of the current thread's uv_loop_t as a bigint.
The returned address is for the current Node.js environment. In the main thread, this is the main thread event loop. In a worker thread, this is that worker's event loop.
This is unsafe and dangerous. The returned pointer is only valid for the lifetime of the current environment. Using it after the environment exits, or from native code that assumes a different thread or lifetime, can crash the process or corrupt memory.
Safety notes#
The node:ffi module does not track pointer validity, memory ownership, or
native object lifetimes.
In particular:
- Do not read from or write to freed memory.
- Do not use zero-copy views after the native memory has been released.
- Do not declare incorrect signatures for native symbols.
- Do not unregister callbacks while native code may still call them.
- Do not call callback pointers after
library.close()orlibrary.unregisterCallback(pointer). - Assume undefined callback behavior can crash the process, produce incorrect output, or corrupt memory.
- Do not assume pointer return values imply ownership; whether the caller must free the returned address depends entirely on the native API.
As a general rule, prefer copied values unless zero-copy access is required, and keep callback and pointer lifetimes explicit on the native side.
File system#
Stability: 2 - Stable
The node:fs module enables interacting with the file system in a
way modeled on standard POSIX functions.
To use the promise-based APIs:
import * as fs from 'node:fs/promises';const fs = require('node:fs/promises');
To use the callback and sync APIs:
import * as fs from 'node:fs';const fs = require('node:fs');
All file system operations have synchronous, callback, and promise-based forms, and are accessible using both CommonJS syntax and ES6 Modules (ESM).
Promise example#
Promise-based operations return a promise that is fulfilled when the asynchronous operation is complete.
import { unlink } from 'node:fs/promises'; try { await unlink('/tmp/hello'); console.log('successfully deleted /tmp/hello'); } catch (error) { console.error('there was an error:', error.message); }const { unlink } = require('node:fs/promises'); (async function(path) { try { await unlink(path); console.log(`successfully deleted ${path}`); } catch (error) { console.error('there was an error:', error.message); } })('/tmp/hello');
Callback example#
The callback form takes a completion callback function as its last
argument and invokes the operation asynchronously. The arguments passed to
the completion callback depend on the method, but the first argument is always
reserved for an exception. If the operation is completed successfully, then
the first argument is null or undefined.
import { unlink } from 'node:fs'; unlink('/tmp/hello', (err) => { if (err) throw err; console.log('successfully deleted /tmp/hello'); });const { unlink } = require('node:fs'); unlink('/tmp/hello', (err) => { if (err) throw err; console.log('successfully deleted /tmp/hello'); });
The callback-based versions of the node:fs module APIs are preferable over
the use of the promise APIs when maximal performance (both in terms of
execution time and memory allocation) is required.
Synchronous example#
The synchronous APIs block the Node.js event loop and further JavaScript
execution until the operation is complete. Exceptions are thrown immediately
and can be handled using try…catch, or can be allowed to bubble up.
import { unlinkSync } from 'node:fs'; try { unlinkSync('/tmp/hello'); console.log('successfully deleted /tmp/hello'); } catch (err) { // handle the error }const { unlinkSync } = require('node:fs'); try { unlinkSync('/tmp/hello'); console.log('successfully deleted /tmp/hello'); } catch (err) { // handle the error }
Promises API#
The fs/promises API provides asynchronous file system methods that return
promises.
The promise APIs use the underlying Node.js threadpool to perform file system operations off the event loop thread. These operations are not synchronized or threadsafe. Care must be taken when performing multiple concurrent modifications on the same file or data corruption may occur.
Class: FileHandle#
A <FileHandle> object is an object wrapper for a numeric file descriptor.
Instances of the <FileHandle> object are created by the fsPromises.open()
method.
All <FileHandle> objects are <EventEmitter>s.
If a <FileHandle> is not closed using the filehandle.close() method, it will
try to automatically close the file descriptor and emit a process warning,
helping to prevent memory leaks. Please do not rely on this behavior because
it can be unreliable and the file may not be closed. Instead, always explicitly
close <FileHandle>s. Node.js may change this behavior in the future.
Event: 'close'#
The 'close' event is emitted when the <FileHandle> has been closed and can no
longer be used.
filehandle.appendFile(data[, options])#
data<string>|<Buffer>|<TypedArray>|<DataView>|<AsyncIterable>|<Iterable>options<Object>|<string>encoding<string>|<null>Default:'utf8'signal<AbortSignal>|<undefined>allows aborting an in-progress writeFile. Default:undefined
- Returns:
<Promise>Fulfills withundefinedupon success.
Alias of filehandle.writeFile().
When operating on file handles, the mode cannot be changed from what it was set
to with fsPromises.open(). Therefore, this is equivalent to
filehandle.writeFile().
filehandle.chmod(mode)#
Modifies the permissions on the file. See chmod(2).
filehandle.chown(uid, gid)#
uid<integer>The file's new owner's user id.gid<integer>The file's new group's group id.- Returns:
<Promise>Fulfills withundefinedupon success.
Changes the ownership of the file. A wrapper for chown(2).
filehandle.close()#
- Returns:
<Promise>Fulfills withundefinedupon success.
Closes the file handle after waiting for any pending operation on the handle to complete.
import { open } from 'node:fs/promises';
let filehandle;
try {
filehandle = await open('thefile.txt', 'r');
} finally {
await filehandle?.close();
}
filehandle.createReadStream([options])#
options<Object>encoding<string>Default:nullautoClose<boolean>Default:trueemitClose<boolean>Default:truestart<integer>end<integer>Default:InfinityhighWaterMark<integer>Default:64 * 1024signal<AbortSignal>|<undefined>Default:undefined
- Returns:
<fs.ReadStream>
options can include start and end values to read a range of bytes from
the file instead of the entire file. Both start and end are inclusive and
start counting at 0, allowed values are in the
[0, Number.MAX_SAFE_INTEGER] range. If start is
omitted or undefined, filehandle.createReadStream() reads sequentially from
the current file position. The encoding can be any one of those accepted by
<Buffer>.
If the FileHandle points to a character device that only supports blocking
reads (such as keyboard or sound card), read operations do not finish until data
is available. This can prevent the process from exiting and the stream from
closing naturally.
By default, the stream will emit a 'close' event after it has been
destroyed. Set the emitClose option to false to change this behavior.
import { open } from 'node:fs/promises';
const fd = await open('/dev/input/event0');
// Create a stream from some character device.
const stream = fd.createReadStream();
setTimeout(() => {
stream.close(); // This may not close the stream.
// Artificially marking end-of-stream, as if the underlying resource had
// indicated end-of-file by itself, allows the stream to close.
// This does not cancel pending read operations, and if there is such an
// operation, the process may still not be able to exit successfully
// until it finishes.
stream.push(null);
stream.read(0);
}, 100);
If autoClose is false, then the file descriptor won't be closed, even if
there's an error. It is the application's responsibility to close it and make
sure there's no file descriptor leak. If autoClose is set to true (default
behavior), on 'error' or 'end' the file descriptor will be closed
automatically.
An example to read the last 10 bytes of a file which is 100 bytes long:
import { open } from 'node:fs/promises';
const fd = await open('sample.txt');
fd.createReadStream({ start: 90, end: 99 });
filehandle.createWriteStream([options])#
options<Object>- Returns:
<fs.WriteStream>
options may also include a start option to allow writing data at some
position past the beginning of the file, allowed values are in the
[0, Number.MAX_SAFE_INTEGER] range. Modifying a file rather than
replacing it may require the flags open option to be set to r+ rather than
the default r. The encoding can be any one of those accepted by <Buffer>.
If autoClose is set to true (default behavior) on 'error' or 'finish'
the file descriptor will be closed automatically. If autoClose is false,
then the file descriptor won't be closed, even if there's an error.
It is the application's responsibility to close it and make sure there's no
file descriptor leak.
By default, the stream will emit a 'close' event after it has been
destroyed. Set the emitClose option to false to change this behavior.
filehandle.datasync()#
- Returns:
<Promise>Fulfills withundefinedupon success.
Forces all currently queued I/O operations associated with the file to the
operating system's synchronized I/O completion state. Refer to the POSIX
fdatasync(2) documentation for details.
Unlike filehandle.sync this method does not flush modified metadata.
filehandle.fd#
- Type:
<number>The numeric file descriptor managed by the<FileHandle>object.
filehandle.pull([...transforms][, options])#
Stability: 1 - Experimental
...transforms<Function>|<Object>Optional transforms to apply viastream/iter pull().options<Object>signal<AbortSignal>autoClose<boolean>Close the file handle when the stream ends. Default:false.start<number>Byte offset to begin reading from. When specified, reads use explicit positioning (preadsemantics). Default: current file position.limit<number>Maximum number of bytes to read before ending the iterator. Reads stop whenlimitbytes have been delivered or EOF is reached, whichever comes first. Default: read until EOF.chunkSize<number>Size in bytes of the buffer allocated for each read operation. Default:131072(128 KB).
- Returns:
<AsyncIterable>whose chunks fulfill with<Uint8Array>[]
Return the file contents as an async iterable using the
node:stream/iter pull model. Reads are performed in chunkSize-byte
chunks (default 128 KB). If transforms are provided, they are applied
via stream/iter pull().
The file handle is locked while the iterable is being consumed and unlocked when iteration completes, an error occurs, or the consumer breaks.
This function is only available when the --experimental-stream-iter flag is
enabled.
import { open } from 'node:fs/promises'; import { text } from 'node:stream/iter'; import { compressGzip } from 'node:zlib/iter'; const fh = await open('input.txt', 'r'); // Read as text console.log(await text(fh.pull({ autoClose: true }))); // Read 1 KB starting at byte 100 const fh2 = await open('input.txt', 'r'); console.log(await text(fh2.pull({ start: 100, limit: 1024, autoClose: true }))); // Read with compression const fh3 = await open('input.txt', 'r'); const compressed = fh3.pull(compressGzip(), { autoClose: true });const { open } = require('node:fs/promises'); const { text } = require('node:stream/iter'); const { compressGzip } = require('node:zlib/iter'); async function run() { const fh = await open('input.txt', 'r'); // Read as text console.log(await text(fh.pull({ autoClose: true }))); // Read 1 KB starting at byte 100 const fh2 = await open('input.txt', 'r'); console.log(await text(fh2.pull({ start: 100, limit: 1024, autoClose: true }))); // Read with compression const fh3 = await open('input.txt', 'r'); const compressed = fh3.pull(compressGzip(), { autoClose: true }); } run().catch(console.error);
filehandle.pullSync([...transforms][, options])#
Stability: 1 - Experimental
...transforms<Function>|<Object>Optional transforms to apply viastream/iter pullSync().options<Object>autoClose<boolean>Close the file handle when the stream ends. Default:false.start<number>Byte offset to begin reading from. When specified, reads use explicit positioning. Default: current file position.limit<number>Maximum number of bytes to read before ending the iterator. Default: read until EOF.chunkSize<number>Size in bytes of the buffer allocated for each read operation. Default:131072(128 KB).
- Returns:
<Iterable>whose chunks return<Uint8Array>[]
Synchronous counterpart of filehandle.pull(). Returns a sync iterable
that reads the file using synchronous I/O on the main thread. Reads are
performed in chunkSize-byte chunks (default 128 KB).
The file handle is locked while the iterable is being consumed. Unlike the
async pull(), this method does not support AbortSignal since all
operations are synchronous.
This function is only available when the --experimental-stream-iter flag is
enabled.
import { open } from 'node:fs/promises'; import { textSync, pipeToSync } from 'node:stream/iter'; import { compressGzipSync, decompressGzipSync } from 'node:zlib/iter'; const fh = await open('input.txt', 'r'); // Read as text (sync) console.log(textSync(fh.pullSync({ autoClose: true }))); // Sync compress pipeline: file -> gzip -> file const src = await open('input.txt', 'r'); const dst = await open('output.gz', 'w'); pipeToSync(src.pullSync(compressGzipSync(), { autoClose: true }), dst.writer({ autoClose: true }));const { open } = require('node:fs/promises'); const { textSync, pipeToSync } = require('node:stream/iter'); const { compressGzipSync, decompressGzipSync } = require('node:zlib/iter'); async function run() { const fh = await open('input.txt', 'r'); // Read as text (sync) console.log(textSync(fh.pullSync({ autoClose: true }))); // Sync compress pipeline: file -> gzip -> file const src = await open('input.txt', 'r'); const dst = await open('output.gz', 'w'); pipeToSync( src.pullSync(compressGzipSync(), { autoClose: true }), dst.writer({ autoClose: true }), ); } run().catch(console.error);
filehandle.read(buffer, offset, length, position)#
buffer<Buffer>|<TypedArray>|<DataView>A buffer that will be filled with the file data read.offset<integer>The location in the buffer at which to start filling. Default:0length<integer>The number of bytes to read. Default:buffer.byteLength - offsetposition<integer>|<bigint>|<null>The location where to begin reading data from the file. Ifnullor-1, data will be read from the current file position, and the position will be updated. Ifpositionis a non-negative integer, the current file position will remain unchanged. Default:null- Returns:
<Promise>Fulfills upon success with an object with two properties:bytesRead<integer>The number of bytes readbuffer<Buffer>|<TypedArray>|<DataView>A reference to the passed inbufferargument.
Reads data from the file and stores that in the given buffer.
If the file is not modified concurrently, the end-of-file is reached when the number of bytes read is zero.
filehandle.read([options])#
options<Object>buffer<Buffer>|<TypedArray>|<DataView>A buffer that will be filled with the file data read. Default:Buffer.alloc(16384)offset<integer>The location in the buffer at which to start filling. Default:0length<integer>The number of bytes to read. Default:buffer.byteLength - offsetposition<integer>|<bigint>|<null>The location where to begin reading data from the file. Ifnullor-1, data will be read from the current file position, and the position will be updated. Ifpositionis a non-negative integer, the current file position will remain unchanged. Default::null
- Returns:
<Promise>Fulfills upon success with an object with two properties:bytesRead<integer>The number of bytes readbuffer<Buffer>|<TypedArray>|<DataView>A reference to the passed inbufferargument.
Reads data from the file and stores that in the given buffer.
If the file is not modified concurrently, the end-of-file is reached when the number of bytes read is zero.
filehandle.read(buffer[, options])#
buffer<Buffer>|<TypedArray>|<DataView>A buffer that will be filled with the file data read.options<Object>offset<integer>The location in the buffer at which to start filling. Default:0length<integer>The number of bytes to read. Default:buffer.byteLength - offsetposition<integer>|<bigint>|<null>The location where to begin reading data from the file. Ifnullor-1, data will be read from the current file position, and the position will be updated. Ifpositionis a non-negative integer, the current file position will remain unchanged. Default::null
- Returns:
<Promise>Fulfills upon success with an object with two properties:bytesRead<integer>The number of bytes readbuffer<Buffer>|<TypedArray>|<DataView>A reference to the passed inbufferargument.
Reads data from the file and stores that in the given buffer.
If the file is not modified concurrently, the end-of-file is reached when the number of bytes read is zero.
filehandle.readableWebStream([options])#
options<Object>autoClose<boolean>When true, causes the<FileHandle>to be closed when the stream is closed. Default:false
- Returns:
<ReadableStream>
Returns a byte-oriented ReadableStream that may be used to read the file's
contents.
An error will be thrown if this method is called more than once or is called
after the FileHandle is closed or closing.
import { open, } from 'node:fs/promises'; const file = await open('./some/file/to/read'); for await (const chunk of file.readableWebStream()) console.log(chunk); await file.close();const { open, } = require('node:fs/promises'); (async () => { const file = await open('./some/file/to/read'); for await (const chunk of file.readableWebStream()) console.log(chunk); await file.close(); })();
While the ReadableStream will read the file to completion, it will not
close the FileHandle automatically. User code must still call the
fileHandle.close() method unless the autoClose option is set to true.
filehandle.readFile(options)#
options<Object>|<string>encoding<string>|<null>Default:nullsignal<AbortSignal>allows aborting an in-progress readFilebuffer<Buffer>|<TypedArray>|<DataView>|<Function>A buffer to read into, or a function called with the file size that returns the buffer.
- Returns:
<Promise>Fulfills upon a successful read with the contents of the file. If no encoding is specified (usingoptions.encoding), the data is returned as a<Buffer>object. Otherwise, the data will be a string.
Asynchronously reads the entire contents of a file.
If options is a string, then it specifies the encoding.
If buffer is provided and no encoding is specified, the returned <Buffer> is
a view over the supplied buffer containing only the bytes read. If the
supplied buffer is too small to contain the entire file, the operation will
fail.
The <FileHandle> has to support reading.
If one or more filehandle.read() calls are made on a file handle and then a
filehandle.readFile() call is made, the data will be read from the current
position till the end of the file. It doesn't always read from the beginning
of the file.
An example using the buffer option with a pre-allocated buffer:
import { Buffer } from 'node:buffer';
import { open } from 'node:fs/promises';
const file = await open('./some/file/to/read');
try {
const buf = Buffer.alloc(16384);
const contents = await file.readFile({ buffer: buf });
console.log(contents); // A view over `buf` containing only the bytes read
} finally {
await file.close();
}
An example using the buffer option with a function returning a buffer:
import { Buffer } from 'node:buffer';
import { open } from 'node:fs/promises';
const file = await open('./some/file/to/read');
try {
const contents = await file.readFile({
buffer: (size) => Buffer.alloc(size),
});
console.log(contents);
} finally {
await file.close();
}
filehandle.readLines([options])#
options<Object>- Returns:
<readline.InterfaceConstructor>
Convenience method to create a readline interface and stream over the file.
See filehandle.createReadStream() for the options.
import { open } from 'node:fs/promises'; const file = await open('./some/file/to/read'); for await (const line of file.readLines()) { console.log(line); }const { open } = require('node:fs/promises'); (async () => { const file = await open('./some/file/to/read'); for await (const line of file.readLines()) { console.log(line); } })();
filehandle.readv(buffers[, position])#
buffers<Buffer>[] |<TypedArray>[] |<DataView>[]position<integer>|<null>The offset from the beginning of the file where the data should be read from. Ifpositionis not anumber, the data will be read from the current position. Default:null- Returns:
<Promise>Fulfills upon success an object containing two properties:bytesRead<integer>the number of bytes readbuffers<Buffer>[] |<TypedArray>[] |<DataView>[] property containing a reference to thebuffersinput.
Read from a file and write to an array of <ArrayBufferView>s
filehandle.stat([options])#
options<Object>bigint<boolean>Whether the numeric values in the returned<fs.Stats>object should bebigint. Default:false.signal<AbortSignal>An AbortSignal to cancel the operation. Default:undefined.
- Returns:
<Promise>Fulfills with an<fs.Stats>for the file.
filehandle.sync()#
- Returns:
<Promise>Fulfills withundefinedupon success.
Request that all data for the open file descriptor is flushed to the storage
device. The specific implementation is operating system and device specific.
Refer to the POSIX fsync(2) documentation for more detail.
filehandle.truncate(len)#
Truncates the file.
If the file was larger than len bytes, only the first len bytes will be
retained in the file.
The following example retains only the first four bytes of the file:
import { open } from 'node:fs/promises';
let filehandle = null;
try {
filehandle = await open('temp.txt', 'r+');
await filehandle.truncate(4);
} finally {
await filehandle?.close();
}
If the file previously was shorter than len bytes, it is extended, and the
extended part is filled with null bytes ('\0'):
If len is negative then 0 will be used.
filehandle.utimes(atime, mtime)#
Change the file system timestamps of the object referenced by the <FileHandle>
then fulfills the promise with no arguments upon success.
filehandle.write(buffer, offset[, length[, position]])#
buffer<Buffer>|<TypedArray>|<DataView>offset<integer>The start position from withinbufferwhere the data to write begins.length<integer>The number of bytes frombufferto write. Default:buffer.byteLength - offsetposition<integer>|<null>The offset from the beginning of the file where the data frombuffershould be written. Ifpositionis not anumber, the data will be written at the current position. See the POSIXpwrite(2)documentation for more detail. Default:null- Returns:
<Promise>
Write buffer to the file.
The promise is fulfilled with an object containing two properties:
bytesWritten<integer>the number of bytes writtenbuffer<Buffer>|<TypedArray>|<DataView>a reference to thebufferwritten.
It is unsafe to use filehandle.write() multiple times on the same file
without waiting for the promise to be fulfilled (or rejected). For this
scenario, use filehandle.createWriteStream().
On Linux, positional writes do not work when the file is opened in append mode. The kernel ignores the position argument and always appends the data to the end of the file.
filehandle.write(buffer[, options])#
buffer<Buffer>|<TypedArray>|<DataView>options<Object>- Returns:
<Promise>
Write buffer to the file.
Similar to the above filehandle.write function, this version takes an
optional options object. If no options object is specified, it will
default with the above values.
filehandle.write(string[, position[, encoding]])#
string<string>position<integer>|<null>The offset from the beginning of the file where the data fromstringshould be written. Ifpositionis not anumberthe data will be written at the current position. See the POSIXpwrite(2)documentation for more detail. Default:nullencoding<string>The expected string encoding. Default:'utf8'- Returns:
<Promise>
Write string to the file. If string is not a string, the promise is
rejected with an error.
The promise is fulfilled with an object containing two properties:
bytesWritten<integer>the number of bytes writtenbuffer<string>a reference to thestringwritten.
It is unsafe to use filehandle.write() multiple times on the same file
without waiting for the promise to be fulfilled (or rejected). For this
scenario, use filehandle.createWriteStream().
On Linux, positional writes do not work when the file is opened in append mode. The kernel ignores the position argument and always appends the data to the end of the file.
filehandle.writeFile(data, options)#
data<string>|<Buffer>|<TypedArray>|<DataView>|<AsyncIterable>|<Iterable>options<Object>|<string>encoding<string>|<null>The expected character encoding whendatais a string. Default:'utf8'signal<AbortSignal>|<undefined>allows aborting an in-progress writeFile. Default:undefined
- Returns:
<Promise>
Asynchronously writes data to a file, replacing the file if it already exists.
data can be a string, a buffer, an <AsyncIterable>, or an <Iterable> object.
The promise is fulfilled with no arguments upon success.
If options is a string, then it specifies the encoding.
The <FileHandle> has to support writing.
It is unsafe to use filehandle.writeFile() multiple times on the same file
without waiting for the promise to be fulfilled (or rejected).
If one or more filehandle.write() calls are made on a file handle and then a
filehandle.writeFile() call is made, the data will be written from the
current position till the end of the file. It doesn't always write from the
beginning of the file.
filehandle.writev(buffers[, position])#
buffers<Buffer>[] |<TypedArray>[] |<DataView>[]position<integer>|<null>The offset from the beginning of the file where the data frombuffersshould be written. Ifpositionis not anumber, the data will be written at the current position. Default:null- Returns:
<Promise>
Write an array of <ArrayBufferView>s to the file.
The promise is fulfilled with an object containing a two properties:
bytesWritten<integer>the number of bytes writtenbuffers<Buffer>[] |<TypedArray>[] |<DataView>[] a reference to thebuffersinput.
It is unsafe to call writev() multiple times on the same file without waiting
for the promise to be fulfilled (or rejected).
On Linux, positional writes don't work when the file is opened in append mode. The kernel ignores the position argument and always appends the data to the end of the file.
filehandle.writer([options])#
Stability: 1 - Experimental
options<Object>autoClose<boolean>Close the file handle when the writer ends or fails. Default:false.start<number>Byte offset to start writing at. When specified, writes use explicit positioning. Default: current file position.limit<number>Maximum number of bytes the writer will accept. Async writes (write(),writev()) that would exceed the limit reject withERR_OUT_OF_RANGE. Sync writes (writeSync(),writevSync()) returnfalse. Default: no limit.chunkSize<number>Maximum chunk size in bytes for synchronous write operations. Writes larger than this threshold fall back to async I/O. Set this to match the reader'schunkSizefor optimalpipeTo()performance. Default:131072(128 KB).
- Returns:
<Object>write(chunk[, options])<Function>Returns<Promise>. AcceptsUint8Array,Buffer, or string (UTF-8 encoded).chunk<Buffer>|<TypedArray>|<DataView>|<string>options<Object>signal<AbortSignal>If the signal is already aborted, the write rejects withAbortErrorwithout performing I/O.
writev(chunks[, options])<Function>Returns<Promise>. Uses scatter/gather I/O via a singlewritev()syscall. Accepts mixedUint8Array/string arrays.chunks<Buffer>[] |<TypedArray>[] |<DataView>[] |<string>[]options<Object>signal<AbortSignal>If the signal is already aborted, the write rejects withAbortErrorwithout performing I/O.
writeSync(chunk)<Function>Returns<boolean>. Attempts a synchronous write. Returnstrueif the write succeeded,falseif the caller should fall back to asyncwrite(). Returnsfalsewhen: the writer is closed/errored, an async operation is in flight, the chunk exceedschunkSize, or the write would exceedlimit.chunk<Buffer>|<TypedArray>|<DataView>|<string>
writevSync(chunks)<Function>Returns<boolean>. Synchronous batch write. Same fallback semantics aswriteSync().chunks<Buffer>[] |<TypedArray>[] |<DataView>[] |<string>[]
end([options])<Function>Returns<Promise>, fulfills with the total number of bytes written. Idempotent: returnstotalBytesWrittenif already closed, returns the pending promise if already closing. Rejects if the writer is in an errored state.options<Object>signal<AbortSignal>If the signal is already aborted,end()rejects withAbortErrorand the writer remains open.
endSync()<Function>Returns<number>|<number>total bytes written on success,-1if the writer is errored or an async operation is in flight. Idempotent when already closed.fail(reason)<Function>Puts the writer into a terminal error state. Synchronous. If the writer is already closed or errored, this is a no-op. IfautoCloseis true, closes the file handle synchronously.
Return a node:stream/iter writer backed by this file handle.
The writer supports both Symbol.asyncDispose and Symbol.dispose:
await using w = fh.writer()— if the writer is still open (noend()called),asyncDisposecallsfail(). Ifend()is pending, it waits for it to complete.using w = fh.writer()— callsfail()unconditionally.
The writeSync() and writevSync() methods enable the try-sync fast path
used by stream/iter pipeTo(). When the reader's chunk size matches the
writer's chunkSize, all writes in a pipeTo() pipeline complete
synchronously with zero promise overhead.
This function is only available when the --experimental-stream-iter flag is
enabled.
import { open } from 'node:fs/promises'; import { from, pipeTo } from 'node:stream/iter'; import { compressGzip } from 'node:zlib/iter'; // Async pipeline const fh = await open('output.gz', 'w'); await pipeTo(from('Hello!'), compressGzip(), fh.writer({ autoClose: true })); // Sync pipeline with limit const src = await open('input.txt', 'r'); const dst = await open('output.txt', 'w'); const w = dst.writer({ limit: 1024 * 1024 }); // Max 1 MB await pipeTo(src.pull({ autoClose: true }), w); await w.end(); await dst.close();const { open } = require('node:fs/promises'); const { from, pipeTo } = require('node:stream/iter'); const { compressGzip } = require('node:zlib/iter'); async function run() { // Async pipeline const fh = await open('output.gz', 'w'); await pipeTo(from('Hello!'), compressGzip(), fh.writer({ autoClose: true })); // Sync pipeline with limit const src = await open('input.txt', 'r'); const dst = await open('output.txt', 'w'); const w = dst.writer({ limit: 1024 * 1024 }); // Max 1 MB await pipeTo(src.pull({ autoClose: true }), w); await w.end(); await dst.close(); } run().catch(console.error);
filehandle[Symbol.asyncDispose]()#
Calls filehandle.close() and returns a promise that fulfills when the
filehandle is closed.
This method enables the filehandle to be used with await using, which
will automatically close the file when the scope exits. For more information,
see the MDN documentation on using statements.
fsPromises.access(path[, mode])#
path<string>|<Buffer>|<URL>mode<integer>Default:fs.constants.F_OK- Returns:
<Promise>Fulfills withundefinedupon success.
Tests a user's permissions for the file or directory specified by path.
The mode argument is an optional integer that specifies the accessibility
checks to be performed. mode should be either the value fs.constants.F_OK
or a mask consisting of the bitwise OR of any of fs.constants.R_OK,
fs.constants.W_OK, and fs.constants.X_OK (e.g.
fs.constants.W_OK | fs.constants.R_OK). Check File access constants for
possible values of mode.
If the accessibility check is successful, the promise is fulfilled with no
value. If any of the accessibility checks fail, the promise is rejected
with an <Error> object. The following example checks if the file /etc/passwd can be read and written by the current process.
import { access, constants } from 'node:fs/promises';
try {
await access('/etc/passwd', constants.R_OK | constants.W_OK);
console.log('can access');
} catch {
console.error('cannot access');
}
Using fsPromises.access() to check for the accessibility of a file before
calling fsPromises.open() is not recommended. Doing so introduces a race
condition, since other processes may change the file's state between the two
calls. Instead, user code should open/read/write the file directly and handle
the error raised if the file is not accessible.
fsPromises.appendFile(path, data[, options])#
path<string>|<Buffer>|<URL>|<FileHandle>filename or<FileHandle>data<string>|<Buffer>|<TypedArray>|<DataView>|<AsyncIterable>|<Iterable>options<Object>|<string>- Returns:
<Promise>Fulfills withundefinedupon success.
Asynchronously append data to a file, creating the file if it does not yet
data can be a string, a buffer, an <AsyncIterable>, or an <Iterable> object.
If options is a string, then it specifies the encoding.
The mode option only affects the newly created file. See fs.open()
for more details.
The path may be specified as a <FileHandle> that has been opened
for appending (using fsPromises.open()).
fsPromises.chmod(path, mode)#
path<string>|<Buffer>|<URL>mode<string>|<integer>- Returns:
<Promise>Fulfills withundefinedupon success.
Changes the permissions of a file.
fsPromises.chown(path, uid, gid)#
path<string>|<Buffer>|<URL>uid<integer>gid<integer>- Returns:
<Promise>Fulfills withundefinedupon success.
Changes the ownership of a file.
fsPromises.copyFile(src, dest[, mode])#
src<string>|<Buffer>|<URL>source filename to copydest<string>|<Buffer>|<URL>destination filename of the copy operationmode<integer>Optional modifiers that specify the behavior of the copy operation. It is possible to create a mask consisting of the bitwise OR of two or more values (e.g.fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE) Default:0.fs.constants.COPYFILE_EXCL: The copy operation will fail ifdestalready exists.fs.constants.COPYFILE_FICLONE: The copy operation will attempt to create a copy-on-write reflink. If the platform does not support copy-on-write, then a fallback copy mechanism is used.fs.constants.COPYFILE_FICLONE_FORCE: The copy operation will attempt to create a copy-on-write reflink. If the platform does not support copy-on-write, then the operation will fail.
- Returns:
<Promise>Fulfills withundefinedupon success.
Asynchronously copies src to dest. By default, dest is overwritten if it
already exists.
No guarantees are made about the atomicity of the copy operation. If an error occurs after the destination file has been opened for writing, an attempt will be made to remove the destination.
import { copyFile, constants } from 'node:fs/promises';
try {
await copyFile('source.txt', 'destination.txt');
console.log('source.txt was copied to destination.txt');
} catch {
console.error('The file could not be copied');
}
// By using COPYFILE_EXCL, the operation will fail if destination.txt exists.
try {
await copyFile('source.txt', 'destination.txt', constants.COPYFILE_EXCL);
console.log('source.txt was copied to destination.txt');
} catch {
console.error('The file could not be copied');
}
fsPromises.cp(src, dest[, options])#
src<string>|<URL>source path to copy.dest<string>|<URL>destination path to copy to.options<Object>dereference<boolean>dereference symlinks. Default:false.errorOnExist<boolean>whenforceisfalse, and the destination exists, throw an error. Default:false.filter<Function>Function to filter copied files/directories. Returntrueto copy the item,falseto ignore it. When ignoring a directory, all of its contents will be skipped as well. Can also return aPromisethat resolves totrueorfalseDefault:undefined.force<boolean>overwrite existing file or directory. The copy operation will ignore errors if you set this to false and the destination exists. Use theerrorOnExistoption to change this behavior. Default:true.mode<integer>modifiers for copy operation. Default:0. Seemodeflag offsPromises.copyFile().preserveTimestamps<boolean>Whentruetimestamps fromsrcwill be preserved. Default:false.recursive<boolean>copy directories recursively Default:falseverbatimSymlinks<boolean>Whentrue, path resolution for symlinks will be skipped. Default:false
- Returns:
<Promise>Fulfills withundefinedupon success.
Asynchronously copies the entire directory structure from src to dest,
including subdirectories and files.
When copying a directory to another directory, globs are not supported and
behavior is similar to cp dir1/ dir2/.
fsPromises.glob(pattern[, options])#
pattern<string>|<string>[]options<Object>cwd<string>|<URL>current working directory. Default:process.cwd()exclude<Function>|<string>[] Function to filter out files/directories or a list of glob patterns to be excluded. If a function is provided, returntrueto exclude the item,falseto include it. Default:undefined. If a string array is provided, each string should be a glob pattern that specifies paths to exclude. Note: Negation patterns (e.g., '!foo.js') are not supported.followSymlinks<boolean>Whentrue, symbolic links to directories are followed while expanding**patterns. Default:false.withFileTypes<boolean>trueif the glob should return paths as Dirents,falseotherwise. Default:false.
- Returns:
<AsyncIterator>An AsyncIterator that yields the paths of files that match the pattern.
When followSymlinks is enabled, detected symbolic link cycles are not
traversed recursively.
import { glob } from 'node:fs/promises'; for await (const entry of glob('**/*.js')) console.log(entry);const { glob } = require('node:fs/promises'); (async () => { for await (const entry of glob('**/*.js')) console.log(entry); })();
fsPromises.lchmod(path, mode)#
Stability: 0 - Deprecated
path<string>|<Buffer>|<URL>mode<integer>- Returns:
<Promise>Fulfills withundefinedupon success.
Changes the permissions on a symbolic link.
This method is only implemented on macOS.
fsPromises.lchown(path, uid, gid)#
path<string>|<Buffer>|<URL>uid<integer>gid<integer>- Returns:
<Promise>Fulfills withundefinedupon success.
Changes the ownership on a symbolic link.
fsPromises.lutimes(path, atime, mtime)#
path<string>|<Buffer>|<URL>atime<number>|<string>|<Date>mtime<number>|<string>|<Date>- Returns:
<Promise>Fulfills withundefinedupon success.
Changes the access and modification times of a file in the same way as
fsPromises.utimes(), with the difference that if the path refers to a
symbolic link, then the link is not dereferenced: instead, the timestamps of
the symbolic link itself are changed.
fsPromises.link(existingPath, newPath)#
existingPath<string>|<Buffer>|<URL>newPath<string>|<Buffer>|<URL>- Returns:
<Promise>Fulfills withundefinedupon success.
Creates a new link from the existingPath to the newPath. See the POSIX
link(2) documentation for more detail.
fsPromises.lstat(path[, options])#
path<string>|<Buffer>|<URL>options<Object>bigint<boolean>Whether the numeric values in the returned<fs.Stats>object should bebigint. Default:false.
- Returns:
<Promise>Fulfills with the<fs.Stats>object for the given symbolic linkpath.
Equivalent to fsPromises.stat() unless path refers to a symbolic link,
in which case the link itself is stat-ed, not the file that it refers to.
Refer to the POSIX lstat(2) document for more detail.
fsPromises.mkdir(path[, options])#
path<string>|<Buffer>|<URL>options<Object>|<integer>recursive<boolean>Default:falsemode<string>|<integer>Not supported on Windows. See File modes for more details. Default:0o777.
- Returns:
<Promise>Upon success, fulfills withundefinedifrecursiveisfalse, or the first directory path created ifrecursiveistrue.
Asynchronously creates a directory.
The optional options argument can be an integer specifying mode (permission
and sticky bits), or an object with a mode property and a recursive
property indicating whether parent directories should be created. Calling
fsPromises.mkdir() when path is a directory that exists results in a
rejection only when recursive is false.
import { mkdir } from 'node:fs/promises'; try { const projectFolder = new URL('./test/project/', import.meta.url); const createDir = await mkdir(projectFolder, { recursive: true }); console.log(`created ${createDir}`); } catch (err) { console.error(err.message); }const { mkdir } = require('node:fs/promises'); const { join } = require('node:path'); async function makeDirectory() { const projectFolder = join(__dirname, 'test', 'project'); const dirCreation = await mkdir(projectFolder, { recursive: true }); console.log(dirCreation); return dirCreation; } makeDirectory().catch(console.error);
fsPromises.mkdtemp(prefix[, options])#
prefix<string>|<Buffer>|<URL>options<string>|<Object>encoding<string>Default:'utf8'
- Returns:
<Promise>Fulfills with a string containing the file system path of the newly created temporary directory.
Creates a unique temporary directory. A unique directory name is generated by
appending six random characters to the end of the provided prefix. Due to
platform inconsistencies, avoid trailing X characters in prefix. Some
platforms, notably the BSDs, can return more than six random characters, and
replace trailing X characters in prefix with random characters.
The optional options argument can be a string specifying an encoding, or an
object with an encoding property specifying the character encoding to use.
import { mkdtemp } from 'node:fs/promises';
import { join } from 'node:path';
import { tmpdir } from 'node:os';
try {
await mkdtemp(join(tmpdir(), 'foo-'));
} catch (err) {
console.error(err);
}
The fsPromises.mkdtemp() method will append the six randomly selected
characters directly to the prefix string. For instance, given a directory
/tmp, if the intention is to create a temporary directory within /tmp, the
prefix must end with a trailing platform-specific path separator
(require('node:path').sep).
fsPromises.mkdtempDisposable(prefix[, options])#
prefix<string>|<Buffer>|<URL>options<string>|<Object>encoding<string>Default:'utf8'
- Returns:
<Promise>Fulfills with a Promise for an async-disposable Object:path<string>The path of the created directory.remove<AsyncFunction>A function which removes the created directory.[Symbol.asyncDispose]<AsyncFunction>The same asremove.
The resulting Promise holds an async-disposable object whose path property
holds the created directory path. When the object is disposed, the directory
and its contents will be removed asynchronously if it still exists. If the
directory cannot be deleted, disposal will throw an error. The object has an
async remove() method which will perform the same task.
Both this function and the disposal function on the resulting object are
async, so it should be used with await + await using as in
await using dir = await fsPromises.mkdtempDisposable('prefix').
See the MDN documentation on using statements for more information about
explicit resource management.
For detailed information, see the documentation of fsPromises.mkdtemp().
The optional options argument can be a string specifying an encoding, or an
object with an encoding property specifying the character encoding to use.
fsPromises.open(path, flags[, mode])#
path<string>|<Buffer>|<URL>flags<string>|<number>See support of file systemflags. Default:'r'.mode<string>|<integer>Sets the file mode (permission and sticky bits) if the file is created. See File modes for more details. Default:0o666(readable and writable)- Returns:
<Promise>Fulfills with a<FileHandle>object.
Opens a <FileHandle>.
Refer to the POSIX open(2) documentation for more detail.
Some characters (< > : " / \ | ? *) are reserved under Windows as documented
by Naming Files, Paths, and Namespaces. Under NTFS, if the filename contains
a colon, Node.js will open a file system stream, as described by
this MSDN page.
fsPromises.opendir(path[, options])#
path<string>|<Buffer>|<URL>options<Object>encoding<string>|<null>Default:'utf8'bufferSize<number>Number of directory entries that are buffered internally when reading from the directory. Higher values lead to better performance but higher memory usage. Default:32recursive<boolean>ResolvedDirwill be an<AsyncIterable>containing all sub files and directories. Default:false
- Returns:
<Promise>Fulfills with an<fs.Dir>.
Asynchronously open a directory for iterative scanning. See the POSIX
opendir(3) documentation for more detail.
Creates an <fs.Dir>, which contains all further functions for reading from
and cleaning up the directory.
The encoding option sets the encoding for the path while opening the
directory and subsequent read operations.
Example using async iteration:
import { opendir } from 'node:fs/promises';
try {
const dir = await opendir('./');
for await (const dirent of dir)
console.log(dirent.name);
} catch (err) {
console.error(err);
}
When using the async iterator, the <fs.Dir> object will be automatically
closed after the iterator exits.
fsPromises.readdir(path[, options])#
path<string>|<Buffer>|<URL>options<string>|<Object>- Returns:
<Promise>Fulfills with an array of the names of the files in the directory excluding'.'and'..'.
Reads the contents of a directory.
The optional options argument can be a string specifying an encoding, or an
object with an encoding property specifying the character encoding to use for
the filenames. If the encoding is set to 'buffer', the filenames returned
will be passed as <Buffer> objects.
If options.withFileTypes is set to true, the returned array will contain
<fs.Dirent> objects.
import { readdir } from 'node:fs/promises';
try {
const files = await readdir(path);
for (const file of files)
console.log(file);
} catch (err) {
console.error(err);
}
fsPromises.readFile(path[, options])#
path<string>|<Buffer>|<URL>|<FileHandle>filename orFileHandleoptions<Object>|<string>encoding<string>|<null>Default:nullflag<string>See support of file systemflags. Default:'r'.signal<AbortSignal>allows aborting an in-progress readFilebuffer<Buffer>|<TypedArray>|<DataView>|<Function>A buffer to read into, or a function called with the file size that returns the buffer.
- Returns:
<Promise>Fulfills with the contents of the file.
Asynchronously reads the entire contents of a file.
If no encoding is specified (using options.encoding), the data is returned
as a <Buffer> object. Otherwise, the data will be a string.
If options is a string, then it specifies the encoding.
If buffer is provided and no encoding is specified, the returned <Buffer> is
a view over the supplied buffer containing only the bytes read. If the
supplied buffer is too small to contain the entire file, the promise will be
rejected.
When the path is a directory, the behavior of fsPromises.readFile() is
platform-specific. On macOS, Linux, and Windows, the promise will be rejected
with an error. On FreeBSD, a representation of the directory's contents will be
returned.
An example of reading a package.json file located in the same directory of the
running code:
import { readFile } from 'node:fs/promises'; try { const filePath = new URL('./package.json', import.meta.url); const contents = await readFile(filePath, { encoding: 'utf8' }); console.log(contents); } catch (err) { console.error(err.message); }const { readFile } = require('node:fs/promises'); const { resolve } = require('node:path'); async function logFile() { try { const filePath = resolve('./package.json'); const contents = await readFile(filePath, { encoding: 'utf8' }); console.log(contents); } catch (err) { console.error(err.message); } } logFile();
It is possible to abort an ongoing readFile using an <AbortSignal>. If a
request is aborted the promise returned is rejected with an AbortError:
import { readFile } from 'node:fs/promises';
try {
const controller = new AbortController();
const { signal } = controller;
const promise = readFile(fileName, { signal });
// Abort the request before the promise settles.
controller.abort();
await promise;
} catch (err) {
// When a request is aborted - err is an AbortError
console.error(err);
}
Aborting an ongoing request does not abort individual operating
system requests but rather the internal buffering fs.readFile performs.
Any specified <FileHandle> has to support reading.
An example using the buffer option with a pre-allocated buffer:
import { Buffer } from 'node:buffer';
import { readFile } from 'node:fs/promises';
const buf = Buffer.alloc(16384);
const contents = await readFile('/path/to/file', { buffer: buf });
console.log(contents); // A view over `buf` containing only the bytes read
An example using the buffer option with a function returning a buffer:
import { Buffer } from 'node:buffer';
import { readFile } from 'node:fs/promises';
const contents = await readFile('/path/to/file', {
buffer: (size) => Buffer.alloc(size),
});
console.log(contents);
fsPromises.readlink(path[, options])#
path<string>|<Buffer>|<URL>options<string>|<Object>encoding<string>Default:'utf8'
- Returns:
<Promise>Fulfills with thelinkStringupon success.
Reads the contents of the symbolic link referred to by path. See the POSIX
readlink(2) documentation for more detail. The promise is fulfilled with the linkString upon success.
The optional options argument can be a string specifying an encoding, or an
object with an encoding property specifying the character encoding to use for
the link path returned. If the encoding is set to 'buffer', the link path
returned will be passed as a <Buffer> object.
fsPromises.realpath(path[, options])#
path<string>|<Buffer>|<URL>options<string>|<Object>encoding<string>Default:'utf8'
- Returns:
<Promise>Fulfills with the resolved path upon success.
Determines the actual location of path using the same semantics as the
fs.realpath.native() function.
Only paths that can be converted to UTF8 strings are supported.
The optional options argument can be a string specifying an encoding, or an
object with an encoding property specifying the character encoding to use for
the path. If the encoding is set to 'buffer', the path returned will be
passed as a <Buffer> object.
On Linux, when Node.js is linked against musl libc, the procfs file system must
be mounted on /proc in order for this function to work. Glibc does not have
this restriction.
fsPromises.rename(oldPath, newPath)#
oldPath<string>|<Buffer>|<URL>newPath<string>|<Buffer>|<URL>- Returns:
<Promise>Fulfills withundefinedupon success.
Renames oldPath to newPath.
fsPromises.rmdir(path[, options])#
path<string>|<Buffer>|<URL>options<Object>There are currently no options exposed. There used to be options forrecursive,maxBusyTries, andemfileWaitbut they were deprecated and removed. Theoptionsargument is still accepted for backwards compatibility but it is not used.- Returns:
<Promise>Fulfills withundefinedupon success.
Removes the directory identified by path.
Using fsPromises.rmdir() on a file (not a directory) results in the
promise being rejected with an ENOENT error on Windows and an ENOTDIR
error on POSIX.
To get a behavior similar to the rm -rf Unix command, use
fsPromises.rm() with options { recursive: true, force: true }.
fsPromises.rm(path[, options])#
path<string>|<Buffer>|<URL>options<Object>force<boolean>Whentrue, exceptions will be ignored ifpathdoes not exist. Default:false.maxRetries<integer>If anEBUSY,EMFILE,ENFILE,ENOTEMPTY, orEPERMerror is encountered, Node.js will retry the operation with a linear backoff wait ofretryDelaymilliseconds longer on each try. This option represents the number of retries. This option is ignored if therecursiveoption is nottrue. Default:0.recursive<boolean>Iftrue, perform a recursive directory removal. In recursive mode operations are retried on failure. Default:false.retryDelay<integer>The amount of time in milliseconds to wait between retries. This option is ignored if therecursiveoption is nottrue. Default:100.
- Returns:
<Promise>Fulfills withundefinedupon success.
Removes files and directories (modeled on the standard POSIX rm utility).
fsPromises.stat(path[, options])#
path<string>|<Buffer>|<URL>options<Object>bigint<boolean>Whether the numeric values in the returned<fs.Stats>object should bebigint. Default:false.throwIfNoEntry<boolean>Whether an exception will be thrown if no file system entry exists, rather than returningundefined. Default:true.
- Returns:
<Promise>Fulfills with the<fs.Stats>object for the givenpath.
fsPromises.statfs(path[, options])#
path<string>|<Buffer>|<URL>options<Object>bigint<boolean>Whether the numeric values in the returned<fs.StatFs>object should bebigint. Default:false.
- Returns:
<Promise>Fulfills with the<fs.StatFs>object for the givenpath.
fsPromises.symlink(target, path[, type])#
target<string>|<Buffer>|<URL>path<string>|<Buffer>|<URL>type<string>|<null>Default:null- Returns:
<Promise>Fulfills withundefinedupon success.
Creates a symbolic link.
The type argument is only used on Windows platforms and can be one of 'dir',
'file', or 'junction'. If the type argument is null, Node.js will
autodetect target type and use 'file' or 'dir'. If the target does not
exist, 'file' will be used. Windows junction points require the destination
path to be absolute. When using 'junction', the target argument will
automatically be normalized to absolute path. Junction points on NTFS volumes
can only point to directories.
fsPromises.truncate(path[, len])#
path<string>|<Buffer>|<URL>len<integer>Default:0- Returns:
<Promise>Fulfills withundefinedupon success.
Truncates (shortens or extends the length) of the content at path to len
bytes.
fsPromises.unlink(path)#
If path refers to a symbolic link, then the link is removed without affecting
the file or directory to which that link refers. If the path refers to a file
path that is not a symbolic link, the file is deleted. See the POSIX unlink(2)
documentation for more detail.
fsPromises.utimes(path, atime, mtime)#
path<string>|<Buffer>|<URL>atime<number>|<string>|<Date>mtime<number>|<string>|<Date>- Returns:
<Promise>Fulfills withundefinedupon success.
Change the file system timestamps of the object referenced by path.
The atime and mtime arguments follow these rules:
- Values can be either numbers representing Unix epoch time,
Dates, or a numeric string like'123456789.0'. - If the value can not be converted to a number, or is
NaN,Infinity, or-Infinity, anErrorwill be thrown.
fsPromises.watch(filename[, options])#
filename<string>|<Buffer>|<URL>options<string>|<Object>persistent<boolean>Indicates whether the process should continue to run as long as files are being watched. Default:true.recursive<boolean>Indicates whether all subdirectories should be watched, or only the current directory. This applies when a directory is specified, and only on supported platforms (See caveats). Default:false.encoding<string>Specifies the character encoding to be used for the filename passed to the listener. Default:'utf8'.signal<AbortSignal>An<AbortSignal>used to signal when the watcher should stop.maxQueue<number>Specifies the number of events to queue between iterations of the<AsyncIterator>returned. Default:2048.overflow<string>Either'ignore'or'throw'when there are more events to be queued thanmaxQueueallows.'ignore'means overflow events are dropped and a warning is emitted, while'throw'means to throw an exception. Default:'ignore'.ignore<string>|<RegExp>|<Function>|<Array>Pattern(s) to ignore. Strings are glob patterns (usingminimatch), RegExp patterns are tested against the filename, and functions receive the filename and returntrueto ignore. Default:undefined.
- Returns:
<AsyncIterator>of objects with the properties:
Returns an async iterator that watches for changes on filename, where filename
is either a file or a directory.
const { watch } = require('node:fs/promises');
const ac = new AbortController();
const { signal } = ac;
setTimeout(() => ac.abort(), 10000);
(async () => {
try {
const watcher = watch(__filename, { signal });
for await (const event of watcher)
console.log(event);
} catch (err) {
if (err.name === 'AbortError')
return;
throw err;
}
})();
On most platforms, 'rename' is emitted whenever a filename appears or
disappears in the directory.
All the caveats for fs.watch() also apply to fsPromises.watch().
fsPromises.writeFile(file, data[, options])#
file<string>|<Buffer>|<URL>|<FileHandle>filename orFileHandledata<string>|<Buffer>|<TypedArray>|<DataView>|<AsyncIterable>|<Iterable>options<Object>|<string>encoding<string>|<null>Default:'utf8'mode<integer>Default:0o666flag<string>See support of file systemflags. Default:'w'.flush<boolean>If all data is successfully written to the file, andflushistrue,filehandle.sync()is used to flush the data. Default:false.signal<AbortSignal>allows aborting an in-progress writeFile
- Returns:
<Promise>Fulfills withundefinedupon success.
Asynchronously writes data to a file, replacing the file if it already exists.
data can be a string, a buffer, an <AsyncIterable>, or an <Iterable> object.
The encoding option is ignored if data is a buffer.
If options is a string, then it specifies the encoding.
The mode option only affects the newly created file. See fs.open()
for more details.
Any specified <FileHandle> has to support writing.
It is unsafe to use fsPromises.writeFile() multiple times on the same file
without waiting for the promise to be settled.
Similarly to fsPromises.readFile - fsPromises.writeFile is a convenience
method that performs multiple write calls internally to write the buffer
passed to it. For performance sensitive code consider using
fs.createWriteStream() or filehandle.createWriteStream().
It is possible to use an <AbortSignal> to cancel an fsPromises.writeFile().
Cancelation is "best effort", and some amount of data is likely still
to be written.
import { writeFile } from 'node:fs/promises';
import { Buffer } from 'node:buffer';
try {
const controller = new AbortController();
const { signal } = controller;
const data = new Uint8Array(Buffer.from('Hello Node.js'));
const promise = writeFile('message.txt', data, { signal });
// Abort the request before the promise settles.
controller.abort();
await promise;
} catch (err) {
// When a request is aborted - err is an AbortError
console.error(err);
}
Aborting an ongoing request does not abort individual operating
system requests but rather the internal buffering fs.writeFile performs.
fsPromises.constants#
- Type:
<Object>
Returns an object containing commonly used constants for file system
operations. The object is the same as fs.constants. See FS constants
for more details.
Callback API#
The callback APIs perform all operations asynchronously, without blocking the event loop, then invoke a callback function upon completion or error.
The callback APIs use the underlying Node.js threadpool to perform file system operations off the event loop thread. These operations are not synchronized or threadsafe. Care must be taken when performing multiple concurrent modifications on the same file or data corruption may occur.
fs.access(path[, mode], callback)#
path<string>|<Buffer>|<URL>mode<integer>Default:fs.constants.F_OKcallback<Function>err<Error>
Tests a user's permissions for the file or directory specified by path.
The mode argument is an optional integer that specifies the accessibility
checks to be performed. mode should be either the value fs.constants.F_OK
or a mask consisting of the bitwise OR of any of fs.constants.R_OK,
fs.constants.W_OK, and fs.constants.X_OK (e.g.
fs.constants.W_OK | fs.constants.R_OK). Check File access constants for
possible values of mode.
The final argument, callback, is a callback function that is invoked with
a possible error argument. If any of the accessibility checks fail, the error
argument will be an Error object. The following examples check if
package.json exists, and if it is readable or writable.
import { access, constants } from 'node:fs';
const file = 'package.json';
// Check if the file exists in the current directory.
access(file, constants.F_OK, (err) => {
console.log(`${file} ${err ? 'does not exist' : 'exists'}`);
});
// Check if the file is readable.
access(file, constants.R_OK, (err) => {
console.log(`${file} ${err ? 'is not readable' : 'is readable'}`);
});
// Check if the file is writable.
access(file, constants.W_OK, (err) => {
console.log(`${file} ${err ? 'is not writable' : 'is writable'}`);
});
// Check if the file is readable and writable.
access(file, constants.R_OK | constants.W_OK, (err) => {
console.log(`${file} ${err ? 'is not' : 'is'} readable and writable`);
});
Do not use fs.access() to check for the accessibility of a file before calling
fs.open(), fs.readFile(), or fs.writeFile(). Doing
so introduces a race condition, since other processes may change the file's
state between the two calls. Instead, user code should open/read/write the
file directly and handle the error raised if the file is not accessible.
write (NOT RECOMMENDED)
import { access, open, close } from 'node:fs';
access('myfile', (err) => {
if (!err) {
console.error('myfile already exists');
return;
}
open('myfile', 'wx', (err, fd) => {
if (err) throw err;
try {
writeMyData(fd);
} finally {
close(fd, (err) => {
if (err) throw err;
});
}
});
});
write (RECOMMENDED)
import { open, close } from 'node:fs';
open('myfile', 'wx', (err, fd) => {
if (err) {
if (err.code === 'EEXIST') {
console.error('myfile already exists');
return;
}
throw err;
}
try {
writeMyData(fd);
} finally {
close(fd, (err) => {
if (err) throw err;
});
}
});
read (NOT RECOMMENDED)
import { access, open, close } from 'node:fs';
access('myfile', (err) => {
if (err) {
if (err.code === 'ENOENT') {
console.error('myfile does not exist');
return;
}
throw err;
}
open('myfile', 'r', (err, fd) => {
if (err) throw err;
try {
readMyData(fd);
} finally {
close(fd, (err) => {
if (err) throw err;
});
}
});
});
read (RECOMMENDED)
import { open, close } from 'node:fs';
open('myfile', 'r', (err, fd) => {
if (err) {
if (err.code === 'ENOENT') {
console.error('myfile does not exist');
return;
}
throw err;
}
try {
readMyData(fd);
} finally {
close(fd, (err) => {
if (err) throw err;
});
}
});
The "not recommended" examples above check for accessibility and then use the file; the "recommended" examples are better because they use the file directly and handle the error, if any.
In general, check for the accessibility of a file only if the file will not be used directly, for example when its accessibility is a signal from another process.
On Windows, access-control policies (ACLs) on a directory may limit access to
a file or directory. The fs.access() function, however, does not check the
ACL and therefore may report that a path is accessible even if the ACL restricts
the user from reading or writing to it.
fs.appendFile(path, data[, options], callback)#
path<string>|<Buffer>|<URL>|<number>filename or file descriptordata<string>|<Buffer>options<Object>|<string>callback<Function>err<Error>
Asynchronously append data to a file, creating the file if it does not yet
exist. data can be a string or a <Buffer>.
The mode option only affects the newly created file. See fs.open()
for more details.
import { appendFile } from 'node:fs';
appendFile('message.txt', 'data to append', (err) => {
if (err) throw err;
console.log('The "data to append" was appended to file!');
});
If options is a string, then it specifies the encoding:
import { appendFile } from 'node:fs';
appendFile('message.txt', 'data to append', 'utf8', callback);
The path may be specified as a numeric file descriptor that has been opened
for appending (using fs.open() or fs.openSync()). The file descriptor will
not be closed automatically.
import { open, close, appendFile } from 'node:fs';
function closeFd(fd) {
close(fd, (err) => {
if (err) throw err;
});
}
open('message.txt', 'a', (err, fd) => {
if (err) throw err;
try {
appendFile(fd, 'data to append', 'utf8', (err) => {
closeFd(fd);
if (err) throw err;
});
} catch (err) {
closeFd(fd);
throw err;
}
});
fs.chmod(path, mode, callback)#
Asynchronously changes the permissions of a file. No arguments other than a possible exception are given to the completion callback.
See the POSIX chmod(2) documentation for more detail.
import { chmod } from 'node:fs';
chmod('my_file.txt', 0o775, (err) => {
if (err) throw err;
console.log('The permissions for file "my_file.txt" have been changed!');
});
File modes#
The mode argument used in both the fs.chmod() and fs.chmodSync()
methods is a numeric bitmask created using a logical OR of the following
constants:
| Constant | Octal | Description |
|---|---|---|
fs.constants.S_IRUSR |
0o400 |
read by owner |
fs.constants.S_IWUSR |
0o200 |
write by owner |
fs.constants.S_IXUSR |
0o100 |
execute/search by owner |
fs.constants.S_IRGRP |
0o40 |
read by group |
fs.constants.S_IWGRP |
0o20 |
write by group |
fs.constants.S_IXGRP |
0o10 |
execute/search by group |
fs.constants.S_IROTH |
0o4 |
read by others |
fs.constants.S_IWOTH |
0o2 |
write by others |
fs.constants.S_IXOTH |
0o1 |
execute/search by others |
An easier method of constructing the mode is to use a sequence of three
octal digits (e.g. 765). The left-most digit (7 in the example), specifies
the permissions for the file owner. The middle digit (6 in the example),
specifies permissions for the group. The right-most digit (5 in the example),
specifies the permissions for others.
| Number | Description |
|---|---|
7 |
read, write, and execute |
6 |
read and write |
5 |
read and execute |
4 |
read only |
3 |
write and execute |
2 |
write only |
1 |
execute only |
0 |
no permission |
For example, the octal value 0o765 means:
- The owner may read, write, and execute the file.
- The group may read and write the file.
- Others may read and execute the file.
When using raw numbers where file modes are expected, any value larger than
0o777 may result in platform-specific behaviors that are not supported to work
consistently. Therefore constants like S_ISVTX, S_ISGID, or S_ISUID are
not exposed in fs.constants.
Caveats: on Windows only the write permission can be changed, and the distinction among the permissions of group, owner, or others is not implemented.
fs.chown(path, uid, gid, callback)#
Asynchronously changes owner and group of a file. No arguments other than a possible exception are given to the completion callback.
See the POSIX chown(2) documentation for more detail.
fs.close(fd[, callback])#
fd<integer>callback<Function>err<Error>
Closes the file descriptor. No arguments other than a possible exception are given to the completion callback.
Calling fs.close() on any file descriptor (fd) that is currently in use
through any other fs operation may lead to undefined behavior.
See the POSIX close(2) documentation for more detail.
fs.copyFile(src, dest[, mode], callback)#
src<string>|<Buffer>|<URL>source filename to copydest<string>|<Buffer>|<URL>destination filename of the copy operationmode<integer>modifiers for copy operation. Default:0.callback<Function>err<Error>
Asynchronously copies src to dest. By default, dest is overwritten if it
already exists. No arguments other than a possible exception are given to the
callback function. Node.js makes no guarantees about the atomicity of the copy
operation. If an error occurs after the destination file has been opened for
writing, Node.js will attempt to remove the destination.
mode is an optional integer that specifies the behavior
of the copy operation. It is possible to create a mask consisting of the bitwise
OR of two or more values (e.g.
fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE).
fs.constants.COPYFILE_EXCL: The copy operation will fail ifdestalready exists.fs.constants.COPYFILE_FICLONE: The copy operation will attempt to create a copy-on-write reflink. If the platform does not support copy-on-write, then a fallback copy mechanism is used.fs.constants.COPYFILE_FICLONE_FORCE: The copy operation will attempt to create a copy-on-write reflink. If the platform does not support copy-on-write, then the operation will fail.
import { copyFile, constants } from 'node:fs';
function callback(err) {
if (err) throw err;
console.log('source.txt was copied to destination.txt');
}
// destination.txt will be created or overwritten by default.
copyFile('source.txt', 'destination.txt', callback);
// By using COPYFILE_EXCL, the operation will fail if destination.txt exists.
copyFile('source.txt', 'destination.txt', constants.COPYFILE_EXCL, callback);
fs.cp(src, dest[, options], callback)#
src<string>|<URL>source path to copy.dest<string>|<URL>destination path to copy to.options<Object>dereference<boolean>dereference symlinks. Default:false.errorOnExist<boolean>whenforceisfalse, and the destination exists, throw an error. Default:false.filter<Function>Function to filter copied files/directories. Returntrueto copy the item,falseto ignore it. When ignoring a directory, all of its contents will be skipped as well. Can also return aPromisethat fulfills withtrueorfalse. Default:undefined.force<boolean>overwrite existing file or directory. The copy operation will ignore errors if you set this to false and the destination exists. Use theerrorOnExistoption to change this behavior. Default:true.mode<integer>modifiers for copy operation. Default:0. Seemodeflag offs.copyFile().preserveTimestamps<boolean>Whentruetimestamps fromsrcwill be preserved. Default:false.recursive<boolean>copy directories recursively Default:falseverbatimSymlinks<boolean>Whentrue, path resolution for symlinks will be skipped. Default:false
callback<Function>err<Error>
Asynchronously copies the entire directory structure from src to dest,
including subdirectories and files.
When copying a directory to another directory, globs are not supported and
behavior is similar to cp dir1/ dir2/.
fs.createReadStream(path[, options])#
path<string>|<Buffer>|<URL>options<string>|<Object>flags<string>See support of file systemflags. Default:'r'.encoding<string>Default:nullfd<integer>|<FileHandle>Default:nullmode<integer>Default:0o666autoClose<boolean>Default:trueemitClose<boolean>Default:truestart<integer>end<integer>Default:InfinityhighWaterMark<integer>Default:64 * 1024fs<Object>|<null>Default:nullsignal<AbortSignal>|<null>Default:null
- Returns:
<fs.ReadStream>
options can include start and end values to read a range of bytes from
the file instead of the entire file. Both start and end are inclusive and
start counting at 0, allowed values are in the
[0, Number.MAX_SAFE_INTEGER] range. If fd is specified and start is
omitted or undefined, fs.createReadStream() reads sequentially from the
current file position. The encoding can be any one of those accepted by
<Buffer>.
If fd is specified, ReadStream will ignore the path argument and will use
the specified file descriptor. This means that no 'open' event will be
emitted. fd should be blocking; non-blocking fds should be passed to
<net.Socket>.
If fd points to a character device that only supports blocking reads
(such as keyboard or sound card), read operations do not finish until data is
available. This can prevent the process from exiting and the stream from
closing naturally.
By default, the stream will emit a 'close' event after it has been
destroyed. Set the emitClose option to false to change this behavior.
By providing the fs option, it is possible to override the corresponding fs
implementations for open, read, and close. When providing the fs option,
an override for read is required. If no fd is provided, an override for
open is also required. If autoClose is true, an override for close is
also required.
import { createReadStream } from 'node:fs';
// Create a stream from some character device.
const stream = createReadStream('/dev/input/event0');
setTimeout(() => {
stream.close(); // This may not close the stream.
// Artificially marking end-of-stream, as if the underlying resource had
// indicated end-of-file by itself, allows the stream to close.
// This does not cancel pending read operations, and if there is such an
// operation, the process may still not be able to exit successfully
// until it finishes.
stream.push(null);
stream.read(0);
}, 100);
If autoClose is false, then the file descriptor won't be closed, even if
there's an error. It is the application's responsibility to close it and make
sure there's no file descriptor leak. If autoClose is set to true (default
behavior), on 'error' or 'end' the file descriptor will be closed
automatically.
mode sets the file mode (permission and sticky bits), but only if the
file was created.
An example to read the last 10 bytes of a file which is 100 bytes long:
import { createReadStream } from 'node:fs';
createReadStream('sample.txt', { start: 90, end: 99 });
If options is a string, then it specifies the encoding.
fs.createWriteStream(path[, options])#
path<string>|<Buffer>|<URL>options<string>|<Object>flags<string>See support of file systemflags. Default:'w'.encoding<string>Default:'utf8'fd<integer>|<FileHandle>Default:nullmode<integer>Default:0o666autoClose<boolean>Default:trueemitClose<boolean>Default:truestart<integer>fs<Object>|<null>Default:nullsignal<AbortSignal>|<null>Default:nullhighWaterMark<number>Default:16384flush<boolean>Iftrue, the underlying file descriptor is flushed prior to closing it. Default:false.
- Returns:
<fs.WriteStream>
options may also include a start option to allow writing data at some
position past the beginning of the file, allowed values are in the
[0, Number.MAX_SAFE_INTEGER] range. Modifying a file rather than
replacing it may require the flags option to be set to r+ rather than the
default w. The encoding can be any one of those accepted by <Buffer>.
If autoClose is set to true (default behavior) on 'error' or 'finish'
the file descriptor will be closed automatically. If autoClose is false,
then the file descriptor won't be closed, even if there's an error.
It is the application's responsibility to close it and make sure there's no
file descriptor leak.
By default, the stream will emit a 'close' event after it has been
destroyed. Set the emitClose option to false to change this behavior.
By providing the fs option it is possible to override the corresponding fs
implementations for open, write, writev, and close. Overriding write()
without writev() can reduce performance as some optimizations (_writev())
will be disabled. When providing the fs option, overrides for at least one of
write and writev are required. If no fd option is supplied, an override
for open is also required. If autoClose is true, an override for close
is also required.
Like <fs.ReadStream>, if fd is specified, <fs.WriteStream> will ignore the path argument and will use the specified file descriptor. This means that no
'open' event will be emitted. fd should be blocking; non-blocking fds
should be passed to <net.Socket>.
If options is a string, then it specifies the encoding.
fs.exists(path, callback)#
Stability: 0 - Deprecated: Use fs.stat() or fs.access() instead.
path<string>|<Buffer>|<URL>callback<Function>exists<boolean>
Test whether or not the element at the given path exists by checking with the file system.
Then call the callback argument with either true or false:
import { exists } from 'node:fs';
exists('/etc/passwd', (e) => {
console.log(e ? 'it exists' : 'no passwd!');
});
The parameters for this callback are not consistent with other Node.js
callbacks. Normally, the first parameter to a Node.js callback is an err
parameter, optionally followed by other parameters. The fs.exists() callback
has only one boolean parameter. This is one reason fs.access() is recommended
instead of fs.exists().
If path is a symbolic link, it is followed. Thus, if path exists but points
to a non-existent element, the callback will receive the value false.
Using fs.exists() to check for the existence of a file before calling
fs.open(), fs.readFile(), or fs.writeFile() is not recommended. Doing
so introduces a race condition, since other processes may change the file's
state between the two calls. Instead, user code should open/read/write the
file directly and handle the error raised if the file does not exist.
write (NOT RECOMMENDED)
import { exists, open, close } from 'node:fs';
exists('myfile', (e) => {
if (e) {
console.error('myfile already exists');
} else {
open('myfile', 'wx', (err, fd) => {
if (err) throw err;
try {
writeMyData(fd);
} finally {
close(fd, (err) => {
if (err) throw err;
});
}
});
}
});
write (RECOMMENDED)
import { open, close } from 'node:fs';
open('myfile', 'wx', (err, fd) => {
if (err) {
if (err.code === 'EEXIST') {
console.error('myfile already exists');
return;
}
throw err;
}
try {
writeMyData(fd);
} finally {
close(fd, (err) => {
if (err) throw err;
});
}
});
read (NOT RECOMMENDED)
import { open, close, exists } from 'node:fs';
exists('myfile', (e) => {
if (e) {
open('myfile', 'r', (err, fd) => {
if (err) throw err;
try {
readMyData(fd);
} finally {
close(fd, (err) => {
if (err) throw err;
});
}
});
} else {
console.error('myfile does not exist');
}
});
read (RECOMMENDED)
import { open, close } from 'node:fs';
open('myfile', 'r', (err, fd) => {
if (err) {
if (err.code === 'ENOENT') {
console.error('myfile does not exist');
return;
}
throw err;
}
try {
readMyData(fd);
} finally {
close(fd, (err) => {
if (err) throw err;
});
}
});
The "not recommended" examples above check for existence and then use the file; the "recommended" examples are better because they use the file directly and handle the error, if any.
In general, check for the existence of a file only if the file won't be used directly, for example when its existence is a signal from another process.
fs.fchmod(fd, mode, callback)#
fd<integer>mode<string>|<integer>callback<Function>err<Error>
Sets the permissions on the file. No arguments other than a possible exception are given to the completion callback.
See the POSIX fchmod(2) documentation for more detail.