# mainFields
– Documentation: https://esbuild.github.io/api/#main-fields
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L104 string []
diff --git a/README.md b/README.md index 25e04f3..c21f230 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,5 @@
Readable | ReadableStream | AsyncIterator<any, any, undefined> arrayBuffer(stream) => #
src/.fastpm/-/@types/node@17.0.45/stream/consumers.d.ts#L22 "node:stream/consumers"
#
src/.fastpm/-/@types/node@17.0.45/stream/consumers.d.ts#L18 arrayBuffer
(stream)
#
stream
Promise<ArrayBuffer>
blob
(stream) Readable | ReadableStream | AsyncIterator<any, any, undefined>#
stream
blob(stream) =>
buffer
(stream) Readable | ReadableStream | AsyncIterator<any, any, undefined>#
stream
buffer(stream) =>
json
(stream) Readable | ReadableStream | AsyncIterator<any, any, undefined>#
stream
json(stream) =>
text
(stream) Readable | ReadableStream | AsyncIterator<any, any, undefined>#
stream
text(stream) =>
"node:stream/promises"
finished(stream, options) => #
src/.fastpm/-/@types/node@17.0.45/stream/promises.d.ts#L3 finished
(stream, options)
Promise<void>
pipeline
(source, destination, options) #
options
pipeline<A extends PipelineSource<any>, B>(source, destination, options) =>
source
transform1
destination
options
pipeline<A extends PipelineSource<any>, T1 extends PipelineTransform<A, any>, B>(source, transform1, destination, options) =>
source
transform1
transform2
destination
options
pipeline<A extends PipelineSource<any>, T1 extends PipelineTransform<A, any>, T2 extends PipelineTransform<T1, any>, B>(source, transform1, transform2, destination, options) =>
source
transform1
transform2
transform3
destination
options
pipeline<A extends PipelineSource<any>, T1 extends PipelineTransform<A, any>, T2 extends PipelineTransform<T1, any>, T3 extends PipelineTransform<T2, any>, B>(source, transform1, transform2, transform3, destination, options) =>
source
transform1
transform2
transform3
transform4
destination
options
pipeline<A extends PipelineSource<any>, T1 extends PipelineTransform<A, any>, T2 extends PipelineTransform<T1, any>, T3 extends PipelineTransform<T2, any>, T4 extends PipelineTransform<T3, any>, B>(source, transform1, transform2, transform3, transform4, destination, options) =>
streams
readonly ReadableStream | WritableStream | ReadWriteStream []
options
pipeline(streams, options) =>
stream1
stream2
streams
pipeline(stream1, stream2, streams) =>
EventEmitter
+
+```js
+const EventEmitter = require('events')
+```
+
+All `EventEmitter`s emit the event `'newListener'` when new listeners are
+added and `'removeListener'` when existing listeners are removed.
+
+It supports the following option:
+
+ typeof captureRejectionSymbol boolean typeof errorMonitor
+
+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.
+
+#
src/.fastpm/-/@types/node@17.0.45/events.d.ts#L73 EventEmitter
– The EventEmitter
class is defined and exposed by the events
module:
#
src/.fastpm/-/@types/node@17.0.45/events.d.ts#L74 constructor
(options)
#
src/.fastpm/-/@types/node@17.0.45/events.d.ts#L301 captureRejectionSymbol
#
src/.fastpm/-/@types/node@17.0.45/events.d.ts#L306 captureRejections
– Sets or gets the default captureRejection value for all emitters.#
src/.fastpm/-/@types/node@17.0.45/events.d.ts#L300 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.
addListener(eventName, listener) =>
emit
(eventName, args) – Synchronously calls each of the listeners registered for the event namedeventName
, in the order they were registered, passing the supplied arguments
+to each.
+ +Returns `true` if the event had listeners, `false` otherwise. + +```js +const EventEmitter = require('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 +``` + +
+eventName
string | symbol
args
any []
emit(eventName, args) =>
eventNames
() – Returns an array listing the events for which the emitter has registered
+listeners. The values in the array are strings or Symbol
s.
+ +```js +const EventEmitter = require('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) ] +``` + +
+eventNames() =>
getMaxListeners
() – Returns the current max listener value for the EventEmitter
which is either
+set by emitter.setMaxListeners(n)
or defaults to {@link defaultMaxListeners}.
getMaxListeners() =>
listenerCount
(eventName) – Returns the number of listeners listening to the event named eventName
. string | symbol#
eventName
– The name of the event being listened for
+
listenerCount(eventName) =>
listeners
(eventName) – Returns a copy of the array of listeners for the event named eventName
.
+ +```js +server.on('connection', stream => { + console.log('someone connected!') +}) +console.log(util.inspect(server.listeners('connection'))) +// Prints: [ [Function] ] +``` + +
+eventName
string | symbol
listeners(eventName) =>
off
(eventName, listener) – Alias for emitter.removeListener()
. string | symbol#
eventName
off(eventName, listener) =>
on
(eventName, listener) – 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.
+ +```js +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. + +```js +const myEE = new EventEmitter() +myEE.on('foo', () => console.log('a')) +myEE.prependListener('foo', () => console.log('b')) +myEE.emit('foo') +// Prints: +// b +// a +``` + +
+eventName
– The name of the event.string | symbol
listener
(args) any []#
args
listener(args) =>
on(eventName, listener) =>
once
(eventName, listener) – Adds a one-timelistener
function for the event named eventName
. The
+next time eventName
is triggered, this listener is removed and then invoked.
+ +```js +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. + +```js +const myEE = new EventEmitter() +myEE.once('foo', () => console.log('a')) +myEE.prependOnceListener('foo', () => console.log('b')) +myEE.emit('foo') +// Prints: +// b +// a +``` + +
+eventName
– The name of the event.string | symbol
listener
(args) any []#
args
listener(args) =>
once(eventName, listener) =>
prependListener
(eventName, listener) – 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.
+ +```js +server.prependListener('connection', stream => { + console.log('someone connected!') +}) +``` + +Returns a reference to the `EventEmitter`, so that calls can be chained. + +
+eventName
– The name of the event.string | symbol
listener
(args) any []#
args
listener(args) =>
prependListener(eventName, listener) =>
prependOnceListener
(eventName, listener) – Adds a one-timelistener
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.
+ +```js +server.prependOnceListener('connection', stream => { + console.log('Ah, we have our first user!') +}) +``` + +Returns a reference to the `EventEmitter`, so that calls can be chained. + +
+eventName
– The name of the event.string | symbol
listener
(args) any []#
args
listener(args) =>
prependOnceListener(eventName, listener) =>
rawListeners
(eventName) – Returns a copy of the array of listeners for the event named eventName
,
+including any wrappers (such as those created by .once()
).
+ +```js +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') +``` + +
+eventName
string | symbol
rawListeners(eventName) =>
removeAllListeners
(event) – 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. + +
+event
string | symbol
removeAllListeners(event) =>
removeListener
(eventName, listener) – Removes the specified listener
from the listener array for the event namedeventName
.
+ +```js +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. + +```js +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 indices 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: + +```js +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. + +
+eventName
string | symbol
listener
(args) any []#
args
listener(args) =>
removeListener(eventName, listener) =>
setMaxListeners
(n) – By default EventEmitter
s 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 toInfinity
(or 0
) to indicate an unlimited number of listeners.
+ +Returns a reference to the `EventEmitter`, so that calls can be chained. + +
+n
number
setMaxListeners(n) =>
getEventListeners
(emitter, name) – Returns a copy of the array of listeners for the event named eventName
.
+ +For `EventEmitter`s this behaves exactly the same as calling `.listeners` on +the emitter. + +For `EventTarget`s this is the only way to get the event listeners for the +event target. This is useful for debugging and diagnostic purposes. + +```js +const { getEventListeners, EventEmitter } = require('events') + +{ + const ee = new EventEmitter() + const listener = () => console.log('Events are fun') + ee.on('foo', listener) + getEventListeners(ee, 'foo') // [listener] +} +{ + const et = new EventTarget() + const listener = () => console.log('Events are fun') + et.addEventListener('foo', listener) + getEventListeners(et, 'foo') // [listener] +} +``` + +
+emitter
name
string | symbol
getEventListeners(emitter, name) =>
listenerCount
(emitter, eventName) – A class method that returns the number of listeners for the given eventName
registered on the given emitter
.
+ +```js +const { EventEmitter, listenerCount } = require('events') +const myEmitter = new EventEmitter() +myEmitter.on('event', () => {}) +myEmitter.on('event', () => {}) +console.log(listenerCount(myEmitter, 'event')) +// Prints: 2 +``` + +
+emitter
– The emitter to queryeventName
– The event name
+string | symbol
listenerCount(emitter, eventName) =>
on
(emitter, eventName, options) – ```js
+const { on, EventEmitter } = require('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: + +```js +const { on, EventEmitter } = require('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()); +```` + +
+emitter
eventName
– The name of the event being listened forstring
options
on(emitter, eventName, options) =>
once
(emitter, eventName, options) – 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](https://dom.spec.whatwg.org/#interface-eventtarget) interface, which has no special`'error'` event +semantics and does not listen to the `'error'` event. + +```js +const { once, EventEmitter } = require('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.log('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: + +```js +const { EventEmitter, once } = require('events') + +const ee = new EventEmitter() + +once(ee, 'error') + .then(([err]) => console.log('ok', err.message)) + .catch(err => console.log('error', err.message)) + +ee.emit('error', new Error('boom')) + +// Prints: ok boom +``` + +An `AbortSignal` can be used to cancel waiting for the event: + +```js +const { EventEmitter, once } = require('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() // Abort waiting for the event +ee.emit('foo') // Prints: Waiting for the event was canceled! +``` + +
+emitter
eventName
string | symbol
options
once(emitter, eventName, options) =>
emitter
eventName
string
options
once(emitter, eventName, options) =>
setMaxListeners
(n, eventTargets) – By default EventEmitter
s 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 EventEmitter.setMaxListeners()
method allows the default limit to be
+modified (if eventTargets is empty) or modify the limit specified in every EventTarget
| EventEmitter
passed as arguments.
+The value can be set toInfinity
(or 0
) to indicate an unlimited number of listeners.
+ +```js +EventEmitter.setMaxListeners(20) +// Equivalent to +EventEmitter.defaultMaxListeners = 20 + +const eventTarget = new EventTarget() +// Only way to increase limit for `EventTarget` instances +// as these doesn't expose its own `setMaxListeners` method +EventEmitter.setMaxListeners(20, eventTarget) +``` + +
+n
number
eventTargets
setMaxListeners(n, eventTargets) =>
Abortable
AbortSignal#
src/.fastpm/-/@types/node@17.0.45/events.d.ts#L317 signal
– When provided the corresponding AbortController
can be used to cancel an asynchronous action.
WebSocket_2
clients
Set<T>
options
path
string
captureRejectionSymbol
typeof captureRejectionSymbol
captureRejections
– Sets or gets the default captureRejection value for all emitters.boolean
defaultMaxListeners
number
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.typeof errorMonitor
+ +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. + +
+addListener
(event, cb) – Alias for emitter.on(eventName, listener)
. #
event
"connection"
addListener(event, cb) =>
event
"error"
cb
(err) Error#
err
cb(err) =>
addListener(event, cb) =>
event
"headers"
cb
(headers, request) cb(headers, request) =>
addListener(event, cb) =>
event
"close"
| "listening"
cb
()
cb() =>
addListener(event, cb) =>
event
string | symbol
listener
(args) any []#
args
listener(args) =>
addListener(event, listener) =>
address
()
address() =>
close
(cb)
close(cb) =>
emit
(eventName, args) – Synchronously calls each of the listeners registered for the event namedeventName
, in the order they were registered, passing the supplied arguments
+to each.
+ +Returns `true` if the event had listeners, `false` otherwise. + +```js +const EventEmitter = require('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 +``` + +
+eventName
string | symbol
args
any []
emit(eventName, args) =>
eventNames
() – Returns an array listing the events for which the emitter has registered
+listeners. The values in the array are strings or Symbol
s.
+ +```js +const EventEmitter = require('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) ] +``` + +
+eventNames() =>
getMaxListeners
() – Returns the current max listener value for the EventEmitter
which is either
+set by emitter.setMaxListeners(n)
or defaults to {@link defaultMaxListeners}.
getMaxListeners() =>
handleUpgrade
(request, socket, upgradeHead, callback) #
request
handleUpgrade(request, socket, upgradeHead, callback) =>
listenerCount
(eventName) – Returns the number of listeners listening to the event named eventName
. string | symbol#
eventName
– The name of the event being listened for
+
listenerCount(eventName) =>
listeners
(eventName) – Returns a copy of the array of listeners for the event named eventName
.
+ +```js +server.on('connection', stream => { + console.log('someone connected!') +}) +console.log(util.inspect(server.listeners('connection'))) +// Prints: [ [Function] ] +``` + +
+eventName
string | symbol
listeners(eventName) =>
off
(event, cb) – Alias for emitter.removeListener()
. #
event
"connection"
off(event, cb) =>
event
"error"
off(event, cb) =>
event
"headers"
cb
(this, headers, request) cb(this, headers, request) =>
off(event, cb) =>
event
"close"
| "listening"
off(event, cb) =>
event
string | symbol
off(event, listener) =>
on
(event, cb) – 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.
+ +```js +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. + +```js +const myEE = new EventEmitter() +myEE.on('foo', () => console.log('a')) +myEE.prependListener('foo', () => console.log('b')) +myEE.emit('foo') +// Prints: +// b +// a +``` + +
+event
"connection"
cb
(this, socket, request) #
request
cb(this, socket, request) =>
on(event, cb) =>
event
"error"
on(event, cb) =>
event
"headers"
cb
(this, headers, request) cb(this, headers, request) =>
on(event, cb) =>
event
"close"
| "listening"
on(event, cb) =>
event
string | symbol
on(event, listener) =>
once
(event, cb) – Adds a one-timelistener
function for the event named eventName
. The
+next time eventName
is triggered, this listener is removed and then invoked.
+ +```js +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. + +```js +const myEE = new EventEmitter() +myEE.once('foo', () => console.log('a')) +myEE.prependOnceListener('foo', () => console.log('b')) +myEE.emit('foo') +// Prints: +// b +// a +``` + +
+event
"connection"
cb
(this, socket, request) #
request
cb(this, socket, request) =>
once(event, cb) =>
event
"error"
once(event, cb) =>
event
"headers"
cb
(this, headers, request) cb(this, headers, request) =>
once(event, cb) =>
event
"close"
| "listening"
once(event, cb) =>
event
string | symbol
once(event, listener) =>
prependListener
(eventName, listener) – 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.
+ +```js +server.prependListener('connection', stream => { + console.log('someone connected!') +}) +``` + +Returns a reference to the `EventEmitter`, so that calls can be chained. + +
+eventName
– The name of the event.string | symbol
listener
(args) any []#
args
listener(args) =>
prependListener(eventName, listener) =>
prependOnceListener
(eventName, listener) – Adds a one-timelistener
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.
+ +```js +server.prependOnceListener('connection', stream => { + console.log('Ah, we have our first user!') +}) +``` + +Returns a reference to the `EventEmitter`, so that calls can be chained. + +
+eventName
– The name of the event.string | symbol
listener
(args) any []#
args
listener(args) =>
prependOnceListener(eventName, listener) =>
rawListeners
(eventName) – Returns a copy of the array of listeners for the event named eventName
,
+including any wrappers (such as those created by .once()
).
+ +```js +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') +``` + +
+eventName
string | symbol
rawListeners(eventName) =>
removeAllListeners
(event) – 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. + +
+event
string | symbol
removeAllListeners(event) =>
removeListener
(event, cb) – Removes the specified listener
from the listener array for the event namedeventName
.
+ +```js +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. + +```js +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 indices 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: + +```js +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. + +
+event
"connection"
removeListener(event, cb) =>
event
"error"
cb
(err) Error#
err
cb(err) =>
removeListener(event, cb) =>
event
"headers"
cb
(headers, request) cb(headers, request) =>
removeListener(event, cb) =>
event
"close"
| "listening"
cb
()
cb() =>
removeListener(event, cb) =>
event
string | symbol
listener
(args) any []#
args
listener(args) =>
removeListener(event, listener) =>
setMaxListeners
(n) – By default EventEmitter
s 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 toInfinity
(or 0
) to indicate an unlimited number of listeners.
+ +Returns a reference to the `EventEmitter`, so that calls can be chained. + +
+n
number
setMaxListeners(n) =>
shouldHandle
(request) #
request
shouldHandle(request) =>
getEventListeners
(emitter, name) – Returns a copy of the array of listeners for the event named eventName
.
+ +For `EventEmitter`s this behaves exactly the same as calling `.listeners` on +the emitter. + +For `EventTarget`s this is the only way to get the event listeners for the +event target. This is useful for debugging and diagnostic purposes. + +```js +const { getEventListeners, EventEmitter } = require('events') + +{ + const ee = new EventEmitter() + const listener = () => console.log('Events are fun') + ee.on('foo', listener) + getEventListeners(ee, 'foo') // [listener] +} +{ + const et = new EventTarget() + const listener = () => console.log('Events are fun') + et.addEventListener('foo', listener) + getEventListeners(et, 'foo') // [listener] +} +``` + +
+emitter
name
string | symbol
getEventListeners(emitter, name) =>
listenerCount
(emitter, eventName) – A class method that returns the number of listeners for the given eventName
registered on the given emitter
.
+ +```js +const { EventEmitter, listenerCount } = require('events') +const myEmitter = new EventEmitter() +myEmitter.on('event', () => {}) +myEmitter.on('event', () => {}) +console.log(listenerCount(myEmitter, 'event')) +// Prints: 2 +``` + +
+emitter
– The emitter to queryeventName
– The event name
+string | symbol
listenerCount(emitter, eventName) =>
on
(emitter, eventName, options) – ```js
+const { on, EventEmitter } = require('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: + +```js +const { on, EventEmitter } = require('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()); +```` + +
+emitter
eventName
– The name of the event being listened forstring
options
on(emitter, eventName, options) =>
once
(emitter, eventName, options) – 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](https://dom.spec.whatwg.org/#interface-eventtarget) interface, which has no special`'error'` event +semantics and does not listen to the `'error'` event. + +```js +const { once, EventEmitter } = require('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.log('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: + +```js +const { EventEmitter, once } = require('events') + +const ee = new EventEmitter() + +once(ee, 'error') + .then(([err]) => console.log('ok', err.message)) + .catch(err => console.log('error', err.message)) + +ee.emit('error', new Error('boom')) + +// Prints: ok boom +``` + +An `AbortSignal` can be used to cancel waiting for the event: + +```js +const { EventEmitter, once } = require('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() // Abort waiting for the event +ee.emit('foo') // Prints: Waiting for the event was canceled! +``` + +
+emitter
eventName
string | symbol
options
once(emitter, eventName, options) =>
emitter
eventName
string
options
once(emitter, eventName, options) =>
setMaxListeners
(n, eventTargets) – By default EventEmitter
s 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 EventEmitter.setMaxListeners()
method allows the default limit to be
+modified (if eventTargets is empty) or modify the limit specified in every EventTarget
| EventEmitter
passed as arguments.
+The value can be set toInfinity
(or 0
) to indicate an unlimited number of listeners.
+ +```js +EventEmitter.setMaxListeners(20) +// Equivalent to +EventEmitter.defaultMaxListeners = 20 + +const eventTarget = new EventTarget() +// Only way to increase limit for `EventTarget` instances +// as these doesn't expose its own `setMaxListeners` method +EventEmitter.setMaxListeners(20, eventTarget) +``` + +
+n
number
eventTargets
setMaxListeners(n, eventTargets) =>
AddressInfo
ClientOptions
string string string | Buffer string boolean string boolean | PerMessageDeflateOptions string string number string string number string#
src/.fastpm/-/@types/node@17.0.45/tls.d.ts#L656 ca
– Optionally override the trusted CA certificates. Default is to trust
+the well-known CAs curated by Mozilla. Mozilla's CAs are completely
+replaced when CAs are explicitly specified using this option.#
src/.fastpm/-/@types/node@17.0.45/tls.d.ts#L668 cert
– Cert chains in PEM format. One cert chain should be provided per
+private key. Each cert chain should consist of the PEM formatted
+certificate for a provided private key, followed by the PEM
+formatted intermediate certificates (if any), in order, and not
+including the root CA (the root CA must be pre-known to the peer,
+see ca). When providing multiple cert chains, they do not have to
+be in the same order as their private keys in key. If the
+intermediate certificates are not provided, the peer will not be
+able to validate the certificate, and the handshake will fail.#
src/.fastpm/-/@types/node@17.0.45/tls.d.ts#L682 ciphers
– Cipher suite specification, replacing the default. For more
+information, see modifying the default cipher suite. Permitted
+ciphers can be obtained via tls.getCiphers(). Cipher names must be
+uppercased in order for OpenSSL to accept them.#
src/.fastpm/-/@types/node@17.0.45/tls.d.ts#L686 clientCertEngine
– Name of an OpenSSL engine which can provide the client certificate.#
src/.fastpm/-/@types/node@17.0.45/tls.d.ts#L690 crl
– PEM formatted CRLs (Certificate Revocation Lists).#
src/.fastpm/-/@types/node@17.0.45/tls.d.ts#L699 dhparam
– Diffie Hellman parameters, required for Perfect Forward Secrecy. Use
+openssl dhparam to create the parameters. The key length must be
+greater than or equal to 1024 bits or else an error will be thrown.
+Although 1024 bits is permissible, use 2048 bits or larger for
+stronger security. If omitted or invalid, the parameters are
+silently discarded and DHE ciphers will not be available.#
src/.fastpm/-/@types/node@17.0.45/tls.d.ts#L709 ecdhCurve
– A string describing a named curve or a colon separated list of curve
+NIDs or names, for example P-521:P-384:P-256, to use for ECDH key
+agreement. Set to auto to select the curve automatically. Use
+crypto.getCurves() to obtain a list of available curve names. On
+recent releases, openssl ecparam -list_curves will also display the
+name and description of each available elliptic curve. Default:
+tls.DEFAULT_ECDH_CURVE.#
src/.fastpm/-/@types/node@17.0.45/tls.d.ts#L715 honorCipherOrder
– Attempt to use the server's cipher suite preferences instead of the
+client's. When true, causes SSL_OP_CIPHER_SERVER_PREFERENCE to be
+set in secureOptions#
src/.fastpm/-/@types/node@17.0.45/tls.d.ts#L726 key
– Private keys in PEM format. PEM allows the option of private keys
+being encrypted. Encrypted keys will be decrypted with
+options.passphrase. Multiple keys using different algorithms can be
+provided either as an array of unencrypted key strings or buffers,
+or an array of objects in the form {pem: <string|buffer>[,
+passphrase: <string>]}. The object form can only occur in an array.
+object.passphrase is optional. Encrypted keys will be decrypted with
+object.passphrase if provided, or options.passphrase if it is not.#
src/.fastpm/-/@types/node@17.0.45/tls.d.ts#L746 maxVersion
– Optionally set the maximum TLS version to allow. One
+of 'TLSv1.3'
, 'TLSv1.2'
, 'TLSv1.1'
, or 'TLSv1'
. Cannot be specified along with the
+secureProtocol
option, use one or the other.
+Default: 'TLSv1.3'
, unless changed using CLI options. Using
+--tls-max-v1.2
sets the default to 'TLSv1.2'
. Using --tls-max-v1.3
sets the default to
+'TLSv1.3'
. If multiple of the options are provided, the highest maximum is used.#
src/.fastpm/-/@types/node@17.0.45/tls.d.ts#L757 minVersion
– Optionally set the minimum TLS version to allow. One
+of 'TLSv1.3'
, 'TLSv1.2'
, 'TLSv1.1'
, or 'TLSv1'
. Cannot be specified along with the
+secureProtocol
option, use one or the other. It is not recommended to use
+less than TLSv1.2, but it may be required for interoperability.
+Default: 'TLSv1.2'
, unless changed using CLI options. Using
+--tls-v1.0
sets the default to 'TLSv1'
. Using --tls-v1.1
sets the default to
+'TLSv1.1'
. Using --tls-min-v1.3
sets the default to
+'TLSv1.3'. If multiple of the options are provided, the lowest minimum is used.#
src/.fastpm/-/@types/node@17.0.45/tls.d.ts#L761 passphrase
– Shared passphrase used for a single private key and/or a PFX.#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L2930 perMessageDeflate
#
src/.fastpm/-/@types/node@17.0.45/tls.d.ts#L772 pfx
– PFX or PKCS12 encoded private key and certificate chain. pfx is an
+alternative to providing key and cert individually. PFX is usually
+encrypted, if it is, passphrase will be used to decrypt it. Multiple
+PFX can be provided either as an array of unencrypted PFX buffers,
+or an array of objects in the form {buf: <string|buffer>[,
+passphrase: <string>]}. The object form can only occur in an array.
+object.passphrase is optional. Encrypted PFX will be decrypted with
+object.passphrase if provided, or options.passphrase if it is not.#
src/.fastpm/-/@types/node@17.0.45/tls.d.ts#L731 privateKeyEngine
– Name of an OpenSSL engine to get private key from. Should be used
+together with privateKeyIdentifier.#
src/.fastpm/-/@types/node@17.0.45/tls.d.ts#L737 privateKeyIdentifier
– Identifier of a private key managed by an OpenSSL engine. Should be
+used together with privateKeyEngine. Should not be set together with
+key, because both options define a private key in different ways.#
src/.fastpm/-/@types/node@17.0.45/tls.d.ts#L778 secureOptions
– Optionally affect the OpenSSL protocol behavior, which is not
+usually necessary. This should be used carefully if at all! Value is
+a numeric bitmask of the SSL_OP_* options from OpenSSL Options#
src/.fastpm/-/@types/node@17.0.45/tls.d.ts#L790 secureProtocol
– Legacy mechanism to select the TLS protocol version to use, it does
+not support independent control of the minimum and maximum version,
+and does not support limiting the protocol to TLSv1.3. Use
+minVersion and maxVersion instead. The possible values are listed as
+SSL_METHODS, use the function names as strings. For example, use
+'TLSv1_1_method' to force TLS version 1.1, or 'TLS_method' to allow
+any TLS protocol version up to TLSv1.3. It is not recommended to use
+TLS versions less than 1.2, but it may be required for
+interoperability. Default: none, see minVersion.#
src/.fastpm/-/@types/node@17.0.45/tls.d.ts#L795 sessionIdContext
– Opaque identifier used by servers to ensure session state is not
+shared between applications. Unused by clients.#
src/.fastpm/-/@types/node@17.0.45/tls.d.ts#L806 sessionTimeout
– The number of seconds after which a TLS session created by the
+server will no longer be resumable. See Session Resumption for more
+information. Default: 300.#
src/.fastpm/-/@types/node@17.0.45/tls.d.ts#L675 sigalgs
– Colon-separated list of supported signature algorithms. The list
+can contain digest algorithms (SHA256, MD5 etc.), public key
+algorithms (RSA-PSS, ECDSA etc.), combination of both (e.g
+'RSA+SHA384') or TLS v1.3 scheme names (e.g. rsa_pss_pss_sha512).#
src/.fastpm/-/@types/node@17.0.45/tls.d.ts#L800 ticketKeys
– 48-bytes of cryptographically strong pseudo-random data.
+See Session Resumption for more information.
CloseEvent
ErrorEvent
Event
EventListenerOptions
MessageEvent
PerMessageDeflateOptions
zlibInflateOptions
ServerOptions
boolean | PerMessageDeflateOptions#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L3013 perMessageDeflate
#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L3002 verifyClient
#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L3006 handleProtocols
(protocols, request)
WebSocket
boolean#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L2643 CLOSING
– The connection is in the process of closing.2
#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L2639 CONNECTING
– The connection is not yet open.0
#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L2641 OPEN
– The connection is open and ready to communicate.1
#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L2624 binaryType
"nodebuffer"
| "arraybuffer"
| "fragments"
#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L2628 isPaused
– Indicates whether the websocket is paused
onerror
onmessage
onopen
null
|
protocol
string
readyState
– The current state of the connection0
| 1
| 2
| 3
url
string
addEventListener
(method, cb, options) options
addEventListener(method, cb, options) =>
method
"close"
cb
(event) #
event
cb(event) =>
options
addEventListener(method, cb, options) =>
method
"error"
cb
(event) #
event
cb(event) =>
options
addEventListener(method, cb, options) =>
method
"open"
options
addEventListener(method, cb, options) =>
addListener
(event, listener) #
event
"close"
addListener(event, listener) =>
event
"error"
listener
(err) Error#
err
listener(err) =>
addListener(event, listener) =>
event
"upgrade"
listener
(request) #
request
listener(request) =>
addListener(event, listener) =>
event
"message"
addListener(event, listener) =>
event
"open"
listener
()
listener() =>
addListener(event, listener) =>
event
"ping"
| "pong"
addListener(event, listener) =>
event
"unexpected-response"
listener
(request, response) listener(request, response) =>
addListener(event, listener) =>
event
string | symbol
listener
(args) any []#
args
listener(args) =>
addListener(event, listener) =>
close
(code, data) number#
code
close(code, data) =>
emit
(eventName, args) – Synchronously calls each of the listeners registered for the event namedeventName
, in the order they were registered, passing the supplied arguments
+to each.
+ +Returns `true` if the event had listeners, `false` otherwise. + +```js +const EventEmitter = require('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 +``` + +
+eventName
string | symbol
args
any []
emit(eventName, args) =>
eventNames
() – Returns an array listing the events for which the emitter has registered
+listeners. The values in the array are strings or Symbol
s.
+ +```js +const EventEmitter = require('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) ] +``` + +
+eventNames() =>
getMaxListeners
() – Returns the current max listener value for the EventEmitter
which is either
+set by emitter.setMaxListeners(n)
or defaults to {@link defaultMaxListeners}.
getMaxListeners() =>
listenerCount
(eventName) – Returns the number of listeners listening to the event named eventName
. string | symbol#
eventName
– The name of the event being listened for
+
listenerCount(eventName) =>
listeners
(eventName) – Returns a copy of the array of listeners for the event named eventName
.
+ +```js +server.on('connection', stream => { + console.log('someone connected!') +}) +console.log(util.inspect(server.listeners('connection'))) +// Prints: [ [Function] ] +``` + +
+eventName
string | symbol
listeners(eventName) =>
off
(event, listener) #
event
"close"
off(event, listener) =>
event
"error"
listener
(this, err) listener(this, err) =>
off(event, listener) =>
event
"upgrade"
listener
(this, request) listener(this, request) =>
off(event, listener) =>
event
"message"
listener
(this, data, isBinary) listener(this, data, isBinary) =>
off(event, listener) =>
event
"open"
listener
(this) #
this
listener(this) =>
off(event, listener) =>
event
"ping"
| "pong"
listener
(this, data) #
this
listener(this, data) =>
off(event, listener) =>
event
"unexpected-response"
listener
(this, request, response) listener(this, request, response) =>
off(event, listener) =>
event
string | symbol
listener
(this, args) listener(this, args) =>
off(event, listener) =>
on
(event, listener) #
event
"close"
on(event, listener) =>
event
"error"
listener
(this, err) listener(this, err) =>
on(event, listener) =>
event
"upgrade"
listener
(this, request) listener(this, request) =>
on(event, listener) =>
event
"message"
listener
(this, data, isBinary) listener(this, data, isBinary) =>
on(event, listener) =>
event
"open"
listener
(this) #
this
listener(this) =>
on(event, listener) =>
event
"ping"
| "pong"
listener
(this, data) #
this
listener(this, data) =>
on(event, listener) =>
event
"unexpected-response"
listener
(this, request, response) listener(this, request, response) =>
on(event, listener) =>
event
string | symbol
listener
(this, args) listener(this, args) =>
on(event, listener) =>
once
(event, listener) #
event
"close"
once(event, listener) =>
event
"error"
listener
(this, err) listener(this, err) =>
once(event, listener) =>
event
"upgrade"
listener
(this, request) listener(this, request) =>
once(event, listener) =>
event
"message"
listener
(this, data, isBinary) listener(this, data, isBinary) =>
once(event, listener) =>
event
"open"
listener
(this) #
this
listener(this) =>
once(event, listener) =>
event
"ping"
| "pong"
listener
(this, data) #
this
listener(this, data) =>
once(event, listener) =>
event
"unexpected-response"
listener
(this, request, response) listener(this, request, response) =>
once(event, listener) =>
event
string | symbol
listener
(this, args) listener(this, args) =>
once(event, listener) =>
pause
() – Pause the websocket causing it to stop emitting events. Some events can still be
+emitted after this is called, until all buffered data is consumed. This method
+is a noop if the ready state is CONNECTING
or CLOSED
.
pause() =>
ping
(data, mask, cb) ping(data, mask, cb) =>
pong
(data, mask, cb) pong(data, mask, cb) =>
prependListener
(eventName, listener) – 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.
+ +```js +server.prependListener('connection', stream => { + console.log('someone connected!') +}) +``` + +Returns a reference to the `EventEmitter`, so that calls can be chained. + +
+eventName
– The name of the event.string | symbol
listener
(args) any []#
args
listener(args) =>
prependListener(eventName, listener) =>
prependOnceListener
(eventName, listener) – Adds a one-timelistener
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.
+ +```js +server.prependOnceListener('connection', stream => { + console.log('Ah, we have our first user!') +}) +``` + +Returns a reference to the `EventEmitter`, so that calls can be chained. + +
+eventName
– The name of the event.string | symbol
listener
(args) any []#
args
listener(args) =>
prependOnceListener(eventName, listener) =>
rawListeners
(eventName) – Returns a copy of the array of listeners for the event named eventName
,
+including any wrappers (such as those created by .once()
).
+ +```js +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') +``` + +
+eventName
string | symbol
rawListeners(eventName) =>
removeAllListeners
(event) – 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. + +
+event
string | symbol
removeAllListeners(event) =>
removeEventListener
(method, cb) removeEventListener(method, cb) =>
method
"close"
cb
(event) #
event
cb(event) =>
removeEventListener(method, cb) =>
method
"error"
cb
(event) #
event
cb(event) =>
removeEventListener(method, cb) =>
method
"open"
removeEventListener(method, cb) =>
removeListener
(event, listener) #
event
"close"
removeListener(event, listener) =>
event
"error"
listener
(err) Error#
err
listener(err) =>
removeListener(event, listener) =>
event
"upgrade"
listener
(request) #
request
listener(request) =>
removeListener(event, listener) =>
event
"message"
removeListener(event, listener) =>
event
"open"
listener
()
listener() =>
removeListener(event, listener) =>
event
"ping"
| "pong"
removeListener(event, listener) =>
event
"unexpected-response"
listener
(request, response) listener(request, response) =>
removeListener(event, listener) =>
event
string | symbol
listener
(args) any []#
args
listener(args) =>
removeListener(event, listener) =>
resume
() – Make a paused socket resume emitting events. This method is a noop if the ready
+state is CONNECTING
or CLOSED
.
resume() =>
send
(data, cb) any#
data
send(data, cb) =>
data
any
options
{
}
cb
(err) Error#
err
cb(err) =>
send(data, { binary, compress, fin, mask }, cb) =>
setMaxListeners
(n) – By default EventEmitter
s 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 toInfinity
(or 0
) to indicate an unlimited number of listeners.
+ +Returns a reference to the `EventEmitter`, so that calls can be chained. + +
+n
number
setMaxListeners(n) =>
terminate
()
terminate() =>
WebSocketServer
#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L3089 addListener
(event, cb) – Alias for emitter.on(eventName, listener)
.
#
event
"connection"
addListener(event, cb) =>
event
"error"
cb
(err) Error#
err
cb(err) =>
addListener(event, cb) =>
event
"headers"
cb
(headers, request) cb(headers, request) =>
addListener(event, cb) =>
event
"close"
| "listening"
cb
()
cb() =>
addListener(event, cb) =>
event
string | symbol
listener
(args) any []#
args
listener(args) =>
addListener(event, listener) =>
address
()
address() =>
close
(cb)
close(cb) =>
emit
(eventName, args) – Synchronously calls each of the listeners registered for the event namedeventName
, in the order they were registered, passing the supplied arguments
+to each.
+ +Returns `true` if the event had listeners, `false` otherwise. + +```js +const EventEmitter = require('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 +``` + +
+eventName
string | symbol
args
any []
emit(eventName, args) =>
eventNames
() – Returns an array listing the events for which the emitter has registered
+listeners. The values in the array are strings or Symbol
s.
+ +```js +const EventEmitter = require('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) ] +``` + +
+eventNames() =>
getMaxListeners
() – Returns the current max listener value for the EventEmitter
which is either
+set by emitter.setMaxListeners(n)
or defaults to {@link defaultMaxListeners}.
getMaxListeners() =>
handleUpgrade
(request, socket, upgradeHead, callback) #
request
handleUpgrade(request, socket, upgradeHead, callback) =>
listenerCount
(eventName) – Returns the number of listeners listening to the event named eventName
. string | symbol#
eventName
– The name of the event being listened for
+
listenerCount(eventName) =>
listeners
(eventName) – Returns a copy of the array of listeners for the event named eventName
.
+ +```js +server.on('connection', stream => { + console.log('someone connected!') +}) +console.log(util.inspect(server.listeners('connection'))) +// Prints: [ [Function] ] +``` + +
+eventName
string | symbol
listeners(eventName) =>
off
(event, cb) – Alias for emitter.removeListener()
. #
event
"connection"
off(event, cb) =>
event
"error"
off(event, cb) =>
event
"headers"
cb
(this, headers, request) cb(this, headers, request) =>
off(event, cb) =>
event
"close"
| "listening"
off(event, cb) =>
event
string | symbol
off(event, listener) =>
on
(event, cb) – 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.
+ +```js +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. + +```js +const myEE = new EventEmitter() +myEE.on('foo', () => console.log('a')) +myEE.prependListener('foo', () => console.log('b')) +myEE.emit('foo') +// Prints: +// b +// a +``` + +
+event
"connection"
cb
(this, socket, request) #
request
cb(this, socket, request) =>
on(event, cb) =>
event
"error"
on(event, cb) =>
event
"headers"
cb
(this, headers, request) cb(this, headers, request) =>
on(event, cb) =>
event
"close"
| "listening"
on(event, cb) =>
event
string | symbol
on(event, listener) =>
once
(event, cb) – Adds a one-timelistener
function for the event named eventName
. The
+next time eventName
is triggered, this listener is removed and then invoked.
+ +```js +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. + +```js +const myEE = new EventEmitter() +myEE.once('foo', () => console.log('a')) +myEE.prependOnceListener('foo', () => console.log('b')) +myEE.emit('foo') +// Prints: +// b +// a +``` + +
+event
"connection"
cb
(this, socket, request) #
request
cb(this, socket, request) =>
once(event, cb) =>
event
"error"
once(event, cb) =>
event
"headers"
cb
(this, headers, request) cb(this, headers, request) =>
once(event, cb) =>
event
"close"
| "listening"
once(event, cb) =>
event
string | symbol
once(event, listener) =>
prependListener
(eventName, listener) – 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.
+ +```js +server.prependListener('connection', stream => { + console.log('someone connected!') +}) +``` + +Returns a reference to the `EventEmitter`, so that calls can be chained. + +
+eventName
– The name of the event.string | symbol
listener
(args) any []#
args
listener(args) =>
prependListener(eventName, listener) =>
prependOnceListener
(eventName, listener) – Adds a one-timelistener
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.
+ +```js +server.prependOnceListener('connection', stream => { + console.log('Ah, we have our first user!') +}) +``` + +Returns a reference to the `EventEmitter`, so that calls can be chained. + +
+eventName
– The name of the event.string | symbol
listener
(args) any []#
args
listener(args) =>
prependOnceListener(eventName, listener) =>
rawListeners
(eventName) – Returns a copy of the array of listeners for the event named eventName
,
+including any wrappers (such as those created by .once()
).
+ +```js +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') +``` + +
+eventName
string | symbol
rawListeners(eventName) =>
removeAllListeners
(event) – 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. + +
+event
string | symbol
removeAllListeners(event) =>
removeListener
(event, cb) – Removes the specified listener
from the listener array for the event namedeventName
.
+ +```js +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. + +```js +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 indices 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: + +```js +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. + +
+event
"connection"
removeListener(event, cb) =>
event
"error"
cb
(err) Error#
err
cb(err) =>
removeListener(event, cb) =>
event
"headers"
cb
(headers, request) cb(headers, request) =>
removeListener(event, cb) =>
event
"close"
| "listening"
cb
()
cb() =>
removeListener(event, cb) =>
event
string | symbol
listener
(args) any []#
args
listener(args) =>
removeListener(event, listener) =>
setMaxListeners
(n) – By default EventEmitter
s 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 toInfinity
(or 0
) to indicate an unlimited number of listeners.
+ +Returns a reference to the `EventEmitter`, so that calls can be chained. + +
+n
number
setMaxListeners(n) =>
shouldHandle
(request) #
request
shouldHandle(request) =>
CertMeta
– CertMeta represents the accepted types for certificate & key data.Data
– Data represents the message payload received over the WebSocket.RawData
– Data represents the raw message payload received over the WebSocket.VerifyClientCallbackAsync
({ origin, req, secure }, callback) =>
VerifyClientCallbackSync
WebSocket
typeof WebSocketAlias
WebSocketServer
typeof Server
createWebSocketStream
(websocket, options) #
options
createWebSocketStream(websocket, options) =>
internal
__promisify__(stream, options) => #
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L1010 finished
#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L1011 __promisify__
(stream, options)
Promise<void>
pipeline
__promisify__<A extends PipelineSource<any>, B>(source, destination, options) => #
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L1199 __promisify__
(source, destination, options)
#
options
source
transform1
destination
options
__promisify__<A extends PipelineSource<any>, T1 extends PipelineTransform<A, any>, B>(source, transform1, destination, options) =>
source
transform1
transform2
destination
options
__promisify__<A extends PipelineSource<any>, T1 extends PipelineTransform<A, any>, T2 extends PipelineTransform<T1, any>, B>(source, transform1, transform2, destination, options) =>
source
transform1
transform2
transform3
destination
options
__promisify__<A extends PipelineSource<any>, T1 extends PipelineTransform<A, any>, T2 extends PipelineTransform<T1, any>, T3 extends PipelineTransform<T2, any>, B>(source, transform1, transform2, transform3, destination, options) =>
source
transform1
transform2
transform3
transform4
destination
options
__promisify__<A extends PipelineSource<any>, T1 extends PipelineTransform<A, any>, T2 extends PipelineTransform<T1, any>, T3 extends PipelineTransform<T2, any>, T4 extends PipelineTransform<T3, any>, B>(source, transform1, transform2, transform3, transform4, destination, options) =>
streams
readonly ReadableStream | WritableStream | ReadWriteStream []
options
__promisify__(streams, options) =>
stream1
stream2
streams
__promisify__(stream1, stream2, streams) =>
Duplex
– Duplex streams are streams that implement both the Readable
and Writable
interfaces.+ +Examples of `Duplex` streams include: + +- `TCP sockets` +- `zlib streams` +- `crypto streams` + +
+ boolean
+
+This can be changed manually to change the half-open behavior of an existing`Duplex` stream instance, but must be changed before the `'end'` event is
+emitted.
+
+ boolean boolean boolean boolean boolean number number boolean typeof captureRejectionSymbol boolean typeof errorMonitor
+
+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.
+
+ [asyncIterator]() => #
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L819 allowHalfOpen
– If false
then the stream will automatically end the writable side when the
+readable side ends. Set initially by the allowHalfOpen
constructor option,
+which defaults to false
.#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L115 destroyed
– Is true
after readable.destroy()
has been called.#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L71 readable
– Is true
if it is safe to call readable.read()
, which means
+the stream has not been destroyed or emitted 'error'
or 'end'
.#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L65 readableAborted
– Returns whether the stream was destroyed or errored before emitting 'end'
.#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L77 readableDidRead
– Returns whether 'data'
has been emitted.#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L82 readableEncoding
– Getter for the property encoding
of a given Readable
stream. The encoding
property can be set using the readable.setEncoding()
method.null
| BufferEncoding#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L87 readableEnded
– Becomes true
when 'end'
event is emitted.#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L93 readableFlowing
– This property reflects the current state of a Readable
stream as described
+in the Three states
section.null
| boolean#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L98 readableHighWaterMark
– Returns the value of highWaterMark
passed when creating this Readable
.#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L105 readableLength
– This property contains the number of bytes (or objects) in the queue
+ready to be read. The value provides introspection data regarding
+the status of the highWaterMark
.#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L110 readableObjectMode
– Getter for the property objectMode
of a given Readable
stream.#
src/.fastpm/-/@types/node@17.0.45/events.d.ts#L301 captureRejectionSymbol
#
src/.fastpm/-/@types/node@17.0.45/events.d.ts#L306 captureRejections
– Sets or gets the default captureRejection value for all emitters.#
src/.fastpm/-/@types/node@17.0.45/events.d.ts#L300 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.#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L479 [asyncIterator]
()
AsyncIterableIterator<any>
_construct
(callback)
_construct(callback) =>
_destroy
(error, callback) #
error
null
| Error
_destroy(error, callback) =>
_final
(callback)
_final(callback) =>
_read
(size) number#
size
_read(size) =>
_write
(chunk, encoding, callback) _write(chunk, encoding, callback) =>
_writev
(chunks, callback) { #
chunks
callback
(error) #
error
null
| Error
callback(error) =>
_writev(chunks, callback) =>
addListener
(event, listener) – Event emitter
+The defined events on documents including:
+1. close
+2. data
+3. end
+4. error
+5. pause
+6. readable
+7. resumeaddListener(event, listener) =>
event
"data"
listener
(chunk) any#
chunk
listener(chunk) =>
addListener(event, listener) =>
event
"end"
listener
()
listener() =>
addListener(event, listener) =>
event
"error"
listener
(err) Error#
err
listener(err) =>
addListener(event, listener) =>
event
"pause"
listener
()
listener() =>
addListener(event, listener) =>
event
"readable"
listener
()
listener() =>
addListener(event, listener) =>
event
"resume"
listener
()
listener() =>
addListener(event, listener) =>
event
string | symbol
listener
(args) any []#
args
listener(args) =>
addListener(event, listener) =>
cork
()
cork() =>
destroy
(error) – Destroy the stream. Optionally emit an 'error'
event, and emit a 'close'
event (unless emitClose
is set to false
). After this call, the readable
+stream will release any internal resources and subsequent calls to push()
will be ignored.
+ +Once `destroy()` has been called any further calls will be a no-op and no +further errors except from `_destroy()` may be emitted as `'error'`. + +Implementors should not override this method, but instead implement `readable._destroy()`. + +
+error
– Error which will be passed as payload in 'error'
event
+Error
destroy(error) =>
emit
(event) – Synchronously calls each of the listeners registered for the event namedeventName
, in the order they were registered, passing the supplied arguments
+to each.
+ +Returns `true` if the event had listeners, `false` otherwise. + +```js +const EventEmitter = require('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 +``` + +
+event
"close"
emit(event) =>
event
"data"
chunk
any
emit(event, chunk) =>
event
"end"
emit(event) =>
event
"error"
err
Error
emit(event, err) =>
event
"pause"
emit(event) =>
event
"readable"
emit(event) =>
event
"resume"
emit(event) =>
event
string | symbol
args
any []
emit(event, args) =>
end
(cb) cb() => #
cb
()
void
end(cb) =>
chunk
any
cb
()
cb() =>
end(chunk, cb) =>
chunk
any
encoding
cb
()
cb() =>
end(chunk, encoding, cb) =>
eventNames
() – Returns an array listing the events for which the emitter has registered
+listeners. The values in the array are strings or Symbol
s.
+ +```js +const EventEmitter = require('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) ] +``` + +
+eventNames() =>
getMaxListeners
() – Returns the current max listener value for the EventEmitter
which is either
+set by emitter.setMaxListeners(n)
or defaults to {@link defaultMaxListeners}.
getMaxListeners() =>
isPaused
() – The readable.isPaused()
method returns the current operating state of theReadable
. This is used primarily by the mechanism that underlies thereadable.pipe()
method. In most
+typical cases, there will be no reason to
+use this method directly.
+ +```js +const readable = new stream.Readable() + +readable.isPaused() // === false +readable.pause() +readable.isPaused() // === true +readable.resume() +readable.isPaused() // === false +``` + +
+isPaused() =>
listenerCount
(eventName) – Returns the number of listeners listening to the event named eventName
. string | symbol#
eventName
– The name of the event being listened for
+
listenerCount(eventName) =>
listeners
(eventName) – Returns a copy of the array of listeners for the event named eventName
.
+ +```js +server.on('connection', stream => { + console.log('someone connected!') +}) +console.log(util.inspect(server.listeners('connection'))) +// Prints: [ [Function] ] +``` + +
+eventName
string | symbol
listeners(eventName) =>
off
(eventName, listener) – Alias for emitter.removeListener()
. string | symbol#
eventName
off(eventName, listener) =>
on
(event, listener) – 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.
+ +```js +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. + +```js +const myEE = new EventEmitter() +myEE.on('foo', () => console.log('a')) +myEE.prependListener('foo', () => console.log('b')) +myEE.emit('foo') +// Prints: +// b +// a +``` + +
+event
"close"
listener
()
listener() =>
on(event, listener) =>
event
"data"
listener
(chunk) any#
chunk
listener(chunk) =>
on(event, listener) =>
event
"end"
listener
()
listener() =>
on(event, listener) =>
event
"error"
listener
(err) Error#
err
listener(err) =>
on(event, listener) =>
event
"pause"
listener
()
listener() =>
on(event, listener) =>
event
"readable"
listener
()
listener() =>
on(event, listener) =>
event
"resume"
listener
()
listener() =>
on(event, listener) =>
event
string | symbol
listener
(args) any []#
args
listener(args) =>
on(event, listener) =>
once
(event, listener) – Adds a one-timelistener
function for the event named eventName
. The
+next time eventName
is triggered, this listener is removed and then invoked.
+ +```js +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. + +```js +const myEE = new EventEmitter() +myEE.once('foo', () => console.log('a')) +myEE.prependOnceListener('foo', () => console.log('b')) +myEE.emit('foo') +// Prints: +// b +// a +``` + +
+event
"close"
listener
()
listener() =>
once(event, listener) =>
event
"data"
listener
(chunk) any#
chunk
listener(chunk) =>
once(event, listener) =>
event
"end"
listener
()
listener() =>
once(event, listener) =>
event
"error"
listener
(err) Error#
err
listener(err) =>
once(event, listener) =>
event
"pause"
listener
()
listener() =>
once(event, listener) =>
event
"readable"
listener
()
listener() =>
once(event, listener) =>
event
"resume"
listener
()
listener() =>
once(event, listener) =>
event
string | symbol
listener
(args) any []#
args
listener(args) =>
once(event, listener) =>
pause
() – The readable.pause()
method will cause a stream in flowing mode to stop
+emitting 'data'
events, switching out of flowing mode. Any data that
+becomes available will remain in the internal buffer.
+ +```js +const readable = getReadableStreamSomehow() +readable.on('data', chunk => { + console.log(`Received ${chunk.length} bytes of data.`) + readable.pause() + console.log('There will be no additional data for 1 second.') + setTimeout(() => { + console.log('Now data will start flowing again.') + readable.resume() + }, 1000) +}) +``` + +The `readable.pause()` method has no effect if there is a `'readable'`event listener. + +
+pause() =>
pipe
(destination, { end }) { #
options
pipe<T extends WritableStream<T>>(destination, { end }) =>
prependListener
(event, listener) – 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.
+ +```js +server.prependListener('connection', stream => { + console.log('someone connected!') +}) +``` + +Returns a reference to the `EventEmitter`, so that calls can be chained. + +
+event
"close"
listener
()
listener() =>
prependListener(event, listener) =>
event
"data"
listener
(chunk) any#
chunk
listener(chunk) =>
prependListener(event, listener) =>
event
"end"
listener
()
listener() =>
prependListener(event, listener) =>
event
"error"
listener
(err) Error#
err
listener(err) =>
prependListener(event, listener) =>
event
"pause"
listener
()
listener() =>
prependListener(event, listener) =>
event
"readable"
listener
()
listener() =>
prependListener(event, listener) =>
event
"resume"
listener
()
listener() =>
prependListener(event, listener) =>
event
string | symbol
listener
(args) any []#
args
listener(args) =>
prependListener(event, listener) =>
prependOnceListener
(event, listener) – Adds a one-timelistener
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.
+ +```js +server.prependOnceListener('connection', stream => { + console.log('Ah, we have our first user!') +}) +``` + +Returns a reference to the `EventEmitter`, so that calls can be chained. + +
+event
"close"
listener
()
listener() =>
prependOnceListener(event, listener) =>
event
"data"
listener
(chunk) any#
chunk
listener(chunk) =>
prependOnceListener(event, listener) =>
event
"end"
listener
()
listener() =>
prependOnceListener(event, listener) =>
event
"error"
listener
(err) Error#
err
listener(err) =>
prependOnceListener(event, listener) =>
event
"pause"
listener
()
listener() =>
prependOnceListener(event, listener) =>
event
"readable"
listener
()
listener() =>
prependOnceListener(event, listener) =>
event
"resume"
listener
()
listener() =>
prependOnceListener(event, listener) =>
event
string | symbol
listener
(args) any []#
args
listener(args) =>
prependOnceListener(event, listener) =>
push
(chunk, encoding) push(chunk, encoding) =>
rawListeners
(eventName) – Returns a copy of the array of listeners for the event named eventName
,
+including any wrappers (such as those created by .once()
).
+ +```js +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') +``` + +
+eventName
string | symbol
rawListeners(eventName) =>
read
(size) – The readable.read()
method pulls some data out of the internal buffer and
+returns it. If no data available to be read, null
is returned. By default,
+the data will be returned as a Buffer
object unless an encoding has been
+specified using the readable.setEncoding()
method or the stream is operating
+in object mode.
+ +The optional `size` argument specifies a specific number of bytes to read. If`size` bytes are not available to be read, `null` will be returned _unless_the stream has ended, in which +case all of the data remaining in the internal +buffer will be returned. + +If the `size` argument is not specified, all of the data contained in the +internal buffer will be returned. + +The `size` argument must be less than or equal to 1 GiB. + +The `readable.read()` method should only be called on `Readable` streams +operating in paused mode. In flowing mode, `readable.read()` is called +automatically until the internal buffer is fully drained. + +```js +const readable = getReadableStreamSomehow() + +// 'readable' may be triggered multiple times as data is buffered in +readable.on('readable', () => { + let chunk + console.log('Stream is readable (new data received in buffer)') + // Use a loop to make sure we read all currently available data + while (null !== (chunk = readable.read())) { + console.log(`Read ${chunk.length} bytes of data...`) + } +}) + +// 'end' will be triggered once when there is no more data available +readable.on('end', () => { + console.log('Reached end of stream.') +}) +``` + +Each call to `readable.read()` returns a chunk of data, or `null`. The chunks +are not concatenated. A `while` loop is necessary to consume all data +currently in the buffer. When reading a large file `.read()` may return `null`, +having consumed all buffered content so far, but there is still more data to +come not yet buffered. In this case a new `'readable'` event will be emitted +when there is more data in the buffer. Finally the `'end'` event will be +emitted when there is no more data to come. + +Therefore to read a file's whole contents from a `readable`, it is necessary +to collect chunks across multiple `'readable'` events: + +```js +const chunks = [] + +readable.on('readable', () => { + let chunk + while (null !== (chunk = readable.read())) { + chunks.push(chunk) + } +}) + +readable.on('end', () => { + const content = chunks.join('') +}) +``` + +A `Readable` stream in object mode will always return a single item from +a call to `readable.read(size)`, regardless of the value of the`size` argument. + +If the `readable.read()` method returns a chunk of data, a `'data'` event will +also be emitted. + +Calling {@link read} after the `'end'` event has +been emitted will return `null`. No runtime error will be raised. + +
+size
– Optional argument to specify how much data to read.
+number
read(size) =>
removeAllListeners
(event) – 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. + +
+event
string | symbol
removeAllListeners(event) =>
removeListener
(event, listener) – Removes the specified listener
from the listener array for the event namedeventName
.
+ +```js +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. + +```js +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 indices 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: + +```js +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. + +
+event
"close"
listener
()
listener() =>
removeListener(event, listener) =>
event
"data"
listener
(chunk) any#
chunk
listener(chunk) =>
removeListener(event, listener) =>
event
"end"
listener
()
listener() =>
removeListener(event, listener) =>
event
"error"
listener
(err) Error#
err
listener(err) =>
removeListener(event, listener) =>
event
"pause"
listener
()
listener() =>
removeListener(event, listener) =>
event
"readable"
listener
()
listener() =>
removeListener(event, listener) =>
event
"resume"
listener
()
listener() =>
removeListener(event, listener) =>
event
string | symbol
listener
(args) any []#
args
listener(args) =>
removeListener(event, listener) =>
resume
() – The readable.resume()
method causes an explicitly paused Readable
stream to
+resume emitting 'data'
events, switching the stream into flowing mode.
+ +The `readable.resume()` method can be used to fully consume the data from a +stream without actually processing any of that data: + +```js +getReadableStreamSomehow() + .resume() + .on('end', () => { + console.log('Reached the end, but did not read anything.') + }) +``` + +The `readable.resume()` method has no effect if there is a `'readable'`event listener. + +
+resume() =>
setDefaultEncoding
(encoding) #
encoding
setDefaultEncoding(encoding) =>
setEncoding
(encoding) – The readable.setEncoding()
method sets the character encoding for
+data read from the Readable
stream.
+ +By default, no encoding is assigned and stream data will be returned as`Buffer` objects. Setting an encoding causes the stream data +to be returned as strings of the specified encoding rather than as `Buffer`objects. For instance, calling `readable.setEncoding('utf8')` will cause the +output data to be interpreted as UTF-8 data, and passed as strings. Calling`readable.setEncoding('hex')` will cause the data to be encoded in hexadecimal +string format. + +The `Readable` stream will properly handle multi-byte characters delivered +through the stream that would otherwise become improperly decoded if simply +pulled from the stream as `Buffer` objects. + +```js +const readable = getReadableStreamSomehow() +readable.setEncoding('utf8') +readable.on('data', chunk => { + assert.equal(typeof chunk, 'string') + console.log('Got %d characters of string data:', chunk.length) +}) +``` + +
+encoding
– The encoding to use.
+setEncoding(encoding) =>
setMaxListeners
(n) – By default EventEmitter
s 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 toInfinity
(or 0
) to indicate an unlimited number of listeners.
+ +Returns a reference to the `EventEmitter`, so that calls can be chained. + +
+n
number
setMaxListeners(n) =>
uncork
()
uncork() =>
unpipe
(destination) – The readable.unpipe()
method detaches a Writable
stream previously attached
+using the {@link pipe} method.
+ +If the `destination` is not specified, then _all_ pipes are detached. + +If the `destination` is specified, but no pipe is set up for it, then +the method does nothing. + +```js +const fs = require('fs') +const readable = getReadableStreamSomehow() +const writable = fs.createWriteStream('file.txt') +// All the data from readable goes into 'file.txt', +// but only for the first second. +readable.pipe(writable) +setTimeout(() => { + console.log('Stop writing to file.txt.') + readable.unpipe(writable) + console.log('Manually close the file stream.') + writable.end() +}, 1000) +``` + +
+destination
– Optional specific stream to unpipe
+unpipe(destination) =>
unshift
(chunk, encoding) – Passing chunk
as null
signals the end of the stream (EOF) and behaves the
+same as readable.push(null)
, after which no more data can be written. The EOF
+signal is put at the end of the buffer and any buffered data will still be
+flushed.
+ +The `readable.unshift()` method pushes a chunk of data back into the internal +buffer. This is useful in certain situations where a stream is being consumed by +code that needs to "un-consume" some amount of data that it has optimistically +pulled out of the source, so that the data can be passed on to some other party. + +The `stream.unshift(chunk)` method cannot be called after the `'end'` event +has been emitted or a runtime error will be thrown. + +Developers using `stream.unshift()` often should consider switching to +use of a `Transform` stream instead. See the `API for stream implementers` section for more information. + +```js +// Pull off a header delimited by \n\n. +// Use unshift() if we get too much. +// Call the callback with (error, header, stream). +const { StringDecoder } = require('string_decoder') +function parseHeader(stream, callback) { + stream.on('error', callback) + stream.on('readable', onReadable) + const decoder = new StringDecoder('utf8') + let header = '' + function onReadable() { + let chunk + while (null !== (chunk = stream.read())) { + const str = decoder.write(chunk) + if (str.match(/\n\n/)) { + // Found the header boundary. + const split = str.split(/\n\n/) + header += split.shift() + const remaining = split.join('\n\n') + const buf = Buffer.from(remaining, 'utf8') + stream.removeListener('error', callback) + // Remove the 'readable' listener before unshifting. + stream.removeListener('readable', onReadable) + if (buf.length) + stream.unshift(buf) + // Now the body of the message can be read from the stream. + callback(null, header, stream) + } else { + // Still reading the header. + header += str + } + } + } +} +``` + +Unlike {@link push}, `stream.unshift(chunk)` will not +end the reading process by resetting the internal reading state of the stream. +This can cause unexpected results if `readable.unshift()` is called during a +read (i.e. from within a {@link _read} implementation on a +custom stream). Following the call to `readable.unshift()` with an immediate {@link push} will reset the reading state appropriately, +however it is best to simply avoid calling `readable.unshift()` while in the +process of performing a read. + +
+chunk
– Chunk of data to unshift onto the read queue. For streams not operating in object mode, chunk
must be a string, Buffer
, Uint8Array
or null
. For object mode
+streams, chunk
may be any JavaScript value.any
encoding
– Encoding of string chunks. Must be a valid Buffer
encoding, such as 'utf8'
or 'ascii'
.
+unshift(chunk, encoding) =>
wrap
(stream) – Prior to Node.js 0.10, streams did not implement the entire stream
module API
+as it is currently defined. (See Compatibility
for more information.)
+ +When using an older Node.js library that emits `'data'` events and has a {@link pause} method that is advisory only, the`readable.wrap()` method can be used to create a `Readable` +stream that uses +the old stream as its data source. + +It will rarely be necessary to use `readable.wrap()` but the method has been +provided as a convenience for interacting with older Node.js applications and +libraries. + +```js +const { OldReader } = require('./old-api-module.js') +const { Readable } = require('stream') +const oreader = new OldReader() +const myReader = new Readable().wrap(oreader) + +myReader.on('readable', () => { + myReader.read() // etc. +}) +``` + +
+stream
– An "old style" readable stream
+wrap(stream) =>
write
(chunk, encoding, cb) write(chunk, encoding, cb) =>
chunk
any
cb
(error) undefined | #
error
null
| Error
cb(error) =>
write(chunk, cb) =>
from
(src) – A utility method for creating duplex streams.
+ +- `Stream` converts writable stream into writable `Duplex` and readable stream + to `Duplex`. +- `Blob` converts into readable `Duplex`. +- `string` converts into readable `Duplex`. +- `ArrayBuffer` converts into readable `Duplex`. +- `AsyncIterable` converts into a readable `Duplex`. Cannot yield `null`. +- `AsyncGeneratorFunction` converts into a readable/writable transform + `Duplex`. Must take a source `AsyncIterable` as first parameter. Cannot yield + `null`. +- `AsyncFunction` converts into a writable `Duplex`. Must return + either `null` or `undefined` +- `Object ({ writable, readable })` converts `readable` and + `writable` into `Stream` and then combines them into `Duplex` where the + `Duplex` will write to the `writable` and read from the `readable`. +- `Promise` converts into readable `Duplex`. Value `null` is ignored. + +
+src
string | Object | Stream | Iterable<any> | AsyncIterable<any> | Blob | ArrayBuffer | AsyncGeneratorFunction | Promise<any>
from(src) =>
getEventListeners
(emitter, name) – Returns a copy of the array of listeners for the event named eventName
.
+ +For `EventEmitter`s this behaves exactly the same as calling `.listeners` on +the emitter. + +For `EventTarget`s this is the only way to get the event listeners for the +event target. This is useful for debugging and diagnostic purposes. + +```js +const { getEventListeners, EventEmitter } = require('events') + +{ + const ee = new EventEmitter() + const listener = () => console.log('Events are fun') + ee.on('foo', listener) + getEventListeners(ee, 'foo') // [listener] +} +{ + const et = new EventTarget() + const listener = () => console.log('Events are fun') + et.addEventListener('foo', listener) + getEventListeners(et, 'foo') // [listener] +} +``` + +
+emitter
name
string | symbol
getEventListeners(emitter, name) =>
isDisturbed
(stream) – Returns whether the stream has been read from or cancelled. #
stream
isDisturbed(stream) =>
listenerCount
(emitter, eventName) – A class method that returns the number of listeners for the given eventName
registered on the given emitter
.
+ +```js +const { EventEmitter, listenerCount } = require('events') +const myEmitter = new EventEmitter() +myEmitter.on('event', () => {}) +myEmitter.on('event', () => {}) +console.log(listenerCount(myEmitter, 'event')) +// Prints: 2 +``` + +
+emitter
– The emitter to queryeventName
– The event name
+string | symbol
listenerCount(emitter, eventName) =>
on
(emitter, eventName, options) – ```js
+const { on, EventEmitter } = require('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: + +```js +const { on, EventEmitter } = require('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()); +```` + +
+emitter
eventName
– The name of the event being listened forstring
options
on(emitter, eventName, options) =>
once
(emitter, eventName, options) – 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](https://dom.spec.whatwg.org/#interface-eventtarget) interface, which has no special`'error'` event +semantics and does not listen to the `'error'` event. + +```js +const { once, EventEmitter } = require('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.log('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: + +```js +const { EventEmitter, once } = require('events') + +const ee = new EventEmitter() + +once(ee, 'error') + .then(([err]) => console.log('ok', err.message)) + .catch(err => console.log('error', err.message)) + +ee.emit('error', new Error('boom')) + +// Prints: ok boom +``` + +An `AbortSignal` can be used to cancel waiting for the event: + +```js +const { EventEmitter, once } = require('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() // Abort waiting for the event +ee.emit('foo') // Prints: Waiting for the event was canceled! +``` + +
+emitter
eventName
string | symbol
options
once(emitter, eventName, options) =>
emitter
eventName
string
options
once(emitter, eventName, options) =>
setMaxListeners
(n, eventTargets) – By default EventEmitter
s 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 EventEmitter.setMaxListeners()
method allows the default limit to be
+modified (if eventTargets is empty) or modify the limit specified in every EventTarget
| EventEmitter
passed as arguments.
+The value can be set toInfinity
(or 0
) to indicate an unlimited number of listeners.
+ +```js +EventEmitter.setMaxListeners(20) +// Equivalent to +EventEmitter.defaultMaxListeners = 20 + +const eventTarget = new EventTarget() +// Only way to increase limit for `EventTarget` instances +// as these doesn't expose its own `setMaxListeners` method +EventEmitter.setMaxListeners(20, eventTarget) +``` + +
+n
number
eventTargets
setMaxListeners(n, eventTargets) =>
PassThrough
– The stream.PassThrough
class is a trivial implementation of a Transform
stream that simply passes the input bytes across to the output. Its purpose is
+primarily for examples and testing, but there are some use cases wherestream.PassThrough
is useful as a building block for novel sorts of streams. boolean
+
+This can be changed manually to change the half-open behavior of an existing`Duplex` stream instance, but must be changed before the `'end'` event is
+emitted.
+
+ boolean boolean boolean boolean boolean number number boolean typeof captureRejectionSymbol boolean typeof errorMonitor
+
+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.
+
+ [asyncIterator]() => #
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L819 allowHalfOpen
– If false
then the stream will automatically end the writable side when the
+readable side ends. Set initially by the allowHalfOpen
constructor option,
+which defaults to false
.#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L115 destroyed
– Is true
after readable.destroy()
has been called.#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L71 readable
– Is true
if it is safe to call readable.read()
, which means
+the stream has not been destroyed or emitted 'error'
or 'end'
.#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L65 readableAborted
– Returns whether the stream was destroyed or errored before emitting 'end'
.#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L77 readableDidRead
– Returns whether 'data'
has been emitted.#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L82 readableEncoding
– Getter for the property encoding
of a given Readable
stream. The encoding
property can be set using the readable.setEncoding()
method.null
| BufferEncoding#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L87 readableEnded
– Becomes true
when 'end'
event is emitted.#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L93 readableFlowing
– This property reflects the current state of a Readable
stream as described
+in the Three states
section.null
| boolean#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L98 readableHighWaterMark
– Returns the value of highWaterMark
passed when creating this Readable
.#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L105 readableLength
– This property contains the number of bytes (or objects) in the queue
+ready to be read. The value provides introspection data regarding
+the status of the highWaterMark
.#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L110 readableObjectMode
– Getter for the property objectMode
of a given Readable
stream.#
src/.fastpm/-/@types/node@17.0.45/events.d.ts#L301 captureRejectionSymbol
#
src/.fastpm/-/@types/node@17.0.45/events.d.ts#L306 captureRejections
– Sets or gets the default captureRejection value for all emitters.#
src/.fastpm/-/@types/node@17.0.45/events.d.ts#L300 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.#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L479 [asyncIterator]
()
AsyncIterableIterator<any>
_construct
(callback)
_construct(callback) =>
_destroy
(error, callback) #
error
null
| Error
_destroy(error, callback) =>
_final
(callback)
_final(callback) =>
_flush
(callback) #
callback
_flush(callback) =>
_read
(size) number#
size
_read(size) =>
_transform
(chunk, encoding, callback) _write
(chunk, encoding, callback) _write(chunk, encoding, callback) =>
_writev
(chunks, callback) { #
chunks
callback
(error) #
error
null
| Error
callback(error) =>
_writev(chunks, callback) =>
addListener
(event, listener) – Event emitter
+The defined events on documents including:
+1. close
+2. data
+3. end
+4. error
+5. pause
+6. readable
+7. resumeaddListener(event, listener) =>
event
"data"
listener
(chunk) any#
chunk
listener(chunk) =>
addListener(event, listener) =>
event
"end"
listener
()
listener() =>
addListener(event, listener) =>
event
"error"
listener
(err) Error#
err
listener(err) =>
addListener(event, listener) =>
event
"pause"
listener
()
listener() =>
addListener(event, listener) =>
event
"readable"
listener
()
listener() =>
addListener(event, listener) =>
event
"resume"
listener
()
listener() =>
addListener(event, listener) =>
event
string | symbol
listener
(args) any []#
args
listener(args) =>
addListener(event, listener) =>
cork
()
cork() =>
destroy
(error) – Destroy the stream. Optionally emit an 'error'
event, and emit a 'close'
event (unless emitClose
is set to false
). After this call, the readable
+stream will release any internal resources and subsequent calls to push()
will be ignored.
+ +Once `destroy()` has been called any further calls will be a no-op and no +further errors except from `_destroy()` may be emitted as `'error'`. + +Implementors should not override this method, but instead implement `readable._destroy()`. + +
+error
– Error which will be passed as payload in 'error'
event
+Error
destroy(error) =>
emit
(event) – Synchronously calls each of the listeners registered for the event namedeventName
, in the order they were registered, passing the supplied arguments
+to each.
+ +Returns `true` if the event had listeners, `false` otherwise. + +```js +const EventEmitter = require('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 +``` + +
+event
"close"
emit(event) =>
event
"data"
chunk
any
emit(event, chunk) =>
event
"end"
emit(event) =>
event
"error"
err
Error
emit(event, err) =>
event
"pause"
emit(event) =>
event
"readable"
emit(event) =>
event
"resume"
emit(event) =>
event
string | symbol
args
any []
emit(event, args) =>
end
(cb) cb() => #
cb
()
void
end(cb) =>
chunk
any
cb
()
cb() =>
end(chunk, cb) =>
chunk
any
encoding
cb
()
cb() =>
end(chunk, encoding, cb) =>
eventNames
() – Returns an array listing the events for which the emitter has registered
+listeners. The values in the array are strings or Symbol
s.
+ +```js +const EventEmitter = require('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) ] +``` + +
+eventNames() =>
getMaxListeners
() – Returns the current max listener value for the EventEmitter
which is either
+set by emitter.setMaxListeners(n)
or defaults to {@link defaultMaxListeners}.
getMaxListeners() =>
isPaused
() – The readable.isPaused()
method returns the current operating state of theReadable
. This is used primarily by the mechanism that underlies thereadable.pipe()
method. In most
+typical cases, there will be no reason to
+use this method directly.
+ +```js +const readable = new stream.Readable() + +readable.isPaused() // === false +readable.pause() +readable.isPaused() // === true +readable.resume() +readable.isPaused() // === false +``` + +
+isPaused() =>
listenerCount
(eventName) – Returns the number of listeners listening to the event named eventName
. string | symbol#
eventName
– The name of the event being listened for
+
listenerCount(eventName) =>
listeners
(eventName) – Returns a copy of the array of listeners for the event named eventName
.
+ +```js +server.on('connection', stream => { + console.log('someone connected!') +}) +console.log(util.inspect(server.listeners('connection'))) +// Prints: [ [Function] ] +``` + +
+eventName
string | symbol
listeners(eventName) =>
off
(eventName, listener) – Alias for emitter.removeListener()
. string | symbol#
eventName
off(eventName, listener) =>
on
(event, listener) – 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.
+ +```js +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. + +```js +const myEE = new EventEmitter() +myEE.on('foo', () => console.log('a')) +myEE.prependListener('foo', () => console.log('b')) +myEE.emit('foo') +// Prints: +// b +// a +``` + +
+event
"close"
listener
()
listener() =>
on(event, listener) =>
event
"data"
listener
(chunk) any#
chunk
listener(chunk) =>
on(event, listener) =>
event
"end"
listener
()
listener() =>
on(event, listener) =>
event
"error"
listener
(err) Error#
err
listener(err) =>
on(event, listener) =>
event
"pause"
listener
()
listener() =>
on(event, listener) =>
event
"readable"
listener
()
listener() =>
on(event, listener) =>
event
"resume"
listener
()
listener() =>
on(event, listener) =>
event
string | symbol
listener
(args) any []#
args
listener(args) =>
on(event, listener) =>
once
(event, listener) – Adds a one-timelistener
function for the event named eventName
. The
+next time eventName
is triggered, this listener is removed and then invoked.
+ +```js +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. + +```js +const myEE = new EventEmitter() +myEE.once('foo', () => console.log('a')) +myEE.prependOnceListener('foo', () => console.log('b')) +myEE.emit('foo') +// Prints: +// b +// a +``` + +
+event
"close"
listener
()
listener() =>
once(event, listener) =>
event
"data"
listener
(chunk) any#
chunk
listener(chunk) =>
once(event, listener) =>
event
"end"
listener
()
listener() =>
once(event, listener) =>
event
"error"
listener
(err) Error#
err
listener(err) =>
once(event, listener) =>
event
"pause"
listener
()
listener() =>
once(event, listener) =>
event
"readable"
listener
()
listener() =>
once(event, listener) =>
event
"resume"
listener
()
listener() =>
once(event, listener) =>
event
string | symbol
listener
(args) any []#
args
listener(args) =>
once(event, listener) =>
pause
() – The readable.pause()
method will cause a stream in flowing mode to stop
+emitting 'data'
events, switching out of flowing mode. Any data that
+becomes available will remain in the internal buffer.
+ +```js +const readable = getReadableStreamSomehow() +readable.on('data', chunk => { + console.log(`Received ${chunk.length} bytes of data.`) + readable.pause() + console.log('There will be no additional data for 1 second.') + setTimeout(() => { + console.log('Now data will start flowing again.') + readable.resume() + }, 1000) +}) +``` + +The `readable.pause()` method has no effect if there is a `'readable'`event listener. + +
+pause() =>
pipe
(destination, { end }) { #
options
pipe<T extends WritableStream<T>>(destination, { end }) =>
prependListener
(event, listener) – 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.
+ +```js +server.prependListener('connection', stream => { + console.log('someone connected!') +}) +``` + +Returns a reference to the `EventEmitter`, so that calls can be chained. + +
+event
"close"
listener
()
listener() =>
prependListener(event, listener) =>
event
"data"
listener
(chunk) any#
chunk
listener(chunk) =>
prependListener(event, listener) =>
event
"end"
listener
()
listener() =>
prependListener(event, listener) =>
event
"error"
listener
(err) Error#
err
listener(err) =>
prependListener(event, listener) =>
event
"pause"
listener
()
listener() =>
prependListener(event, listener) =>
event
"readable"
listener
()
listener() =>
prependListener(event, listener) =>
event
"resume"
listener
()
listener() =>
prependListener(event, listener) =>
event
string | symbol
listener
(args) any []#
args
listener(args) =>
prependListener(event, listener) =>
prependOnceListener
(event, listener) – Adds a one-timelistener
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.
+ +```js +server.prependOnceListener('connection', stream => { + console.log('Ah, we have our first user!') +}) +``` + +Returns a reference to the `EventEmitter`, so that calls can be chained. + +
+event
"close"
listener
()
listener() =>
prependOnceListener(event, listener) =>
event
"data"
listener
(chunk) any#
chunk
listener(chunk) =>
prependOnceListener(event, listener) =>
event
"end"
listener
()
listener() =>
prependOnceListener(event, listener) =>
event
"error"
listener
(err) Error#
err
listener(err) =>
prependOnceListener(event, listener) =>
event
"pause"
listener
()
listener() =>
prependOnceListener(event, listener) =>
event
"readable"
listener
()
listener() =>
prependOnceListener(event, listener) =>
event
"resume"
listener
()
listener() =>
prependOnceListener(event, listener) =>
event
string | symbol
listener
(args) any []#
args
listener(args) =>
prependOnceListener(event, listener) =>
push
(chunk, encoding) push(chunk, encoding) =>
rawListeners
(eventName) – Returns a copy of the array of listeners for the event named eventName
,
+including any wrappers (such as those created by .once()
).
+ +```js +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') +``` + +
+eventName
string | symbol
rawListeners(eventName) =>
read
(size) – The readable.read()
method pulls some data out of the internal buffer and
+returns it. If no data available to be read, null
is returned. By default,
+the data will be returned as a Buffer
object unless an encoding has been
+specified using the readable.setEncoding()
method or the stream is operating
+in object mode.
+ +The optional `size` argument specifies a specific number of bytes to read. If`size` bytes are not available to be read, `null` will be returned _unless_the stream has ended, in which +case all of the data remaining in the internal +buffer will be returned. + +If the `size` argument is not specified, all of the data contained in the +internal buffer will be returned. + +The `size` argument must be less than or equal to 1 GiB. + +The `readable.read()` method should only be called on `Readable` streams +operating in paused mode. In flowing mode, `readable.read()` is called +automatically until the internal buffer is fully drained. + +```js +const readable = getReadableStreamSomehow() + +// 'readable' may be triggered multiple times as data is buffered in +readable.on('readable', () => { + let chunk + console.log('Stream is readable (new data received in buffer)') + // Use a loop to make sure we read all currently available data + while (null !== (chunk = readable.read())) { + console.log(`Read ${chunk.length} bytes of data...`) + } +}) + +// 'end' will be triggered once when there is no more data available +readable.on('end', () => { + console.log('Reached end of stream.') +}) +``` + +Each call to `readable.read()` returns a chunk of data, or `null`. The chunks +are not concatenated. A `while` loop is necessary to consume all data +currently in the buffer. When reading a large file `.read()` may return `null`, +having consumed all buffered content so far, but there is still more data to +come not yet buffered. In this case a new `'readable'` event will be emitted +when there is more data in the buffer. Finally the `'end'` event will be +emitted when there is no more data to come. + +Therefore to read a file's whole contents from a `readable`, it is necessary +to collect chunks across multiple `'readable'` events: + +```js +const chunks = [] + +readable.on('readable', () => { + let chunk + while (null !== (chunk = readable.read())) { + chunks.push(chunk) + } +}) + +readable.on('end', () => { + const content = chunks.join('') +}) +``` + +A `Readable` stream in object mode will always return a single item from +a call to `readable.read(size)`, regardless of the value of the`size` argument. + +If the `readable.read()` method returns a chunk of data, a `'data'` event will +also be emitted. + +Calling {@link read} after the `'end'` event has +been emitted will return `null`. No runtime error will be raised. + +
+size
– Optional argument to specify how much data to read.
+number
read(size) =>
removeAllListeners
(event) – 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. + +
+event
string | symbol
removeAllListeners(event) =>
removeListener
(event, listener) – Removes the specified listener
from the listener array for the event namedeventName
.
+ +```js +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. + +```js +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 indices 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: + +```js +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. + +
+event
"close"
listener
()
listener() =>
removeListener(event, listener) =>
event
"data"
listener
(chunk) any#
chunk
listener(chunk) =>
removeListener(event, listener) =>
event
"end"
listener
()
listener() =>
removeListener(event, listener) =>
event
"error"
listener
(err) Error#
err
listener(err) =>
removeListener(event, listener) =>
event
"pause"
listener
()
listener() =>
removeListener(event, listener) =>
event
"readable"
listener
()
listener() =>
removeListener(event, listener) =>
event
"resume"
listener
()
listener() =>
removeListener(event, listener) =>
event
string | symbol
listener
(args) any []#
args
listener(args) =>
removeListener(event, listener) =>
resume
() – The readable.resume()
method causes an explicitly paused Readable
stream to
+resume emitting 'data'
events, switching the stream into flowing mode.
+ +The `readable.resume()` method can be used to fully consume the data from a +stream without actually processing any of that data: + +```js +getReadableStreamSomehow() + .resume() + .on('end', () => { + console.log('Reached the end, but did not read anything.') + }) +``` + +The `readable.resume()` method has no effect if there is a `'readable'`event listener. + +
+resume() =>
setDefaultEncoding
(encoding) #
encoding
setDefaultEncoding(encoding) =>
setEncoding
(encoding) – The readable.setEncoding()
method sets the character encoding for
+data read from the Readable
stream.
+ +By default, no encoding is assigned and stream data will be returned as`Buffer` objects. Setting an encoding causes the stream data +to be returned as strings of the specified encoding rather than as `Buffer`objects. For instance, calling `readable.setEncoding('utf8')` will cause the +output data to be interpreted as UTF-8 data, and passed as strings. Calling`readable.setEncoding('hex')` will cause the data to be encoded in hexadecimal +string format. + +The `Readable` stream will properly handle multi-byte characters delivered +through the stream that would otherwise become improperly decoded if simply +pulled from the stream as `Buffer` objects. + +```js +const readable = getReadableStreamSomehow() +readable.setEncoding('utf8') +readable.on('data', chunk => { + assert.equal(typeof chunk, 'string') + console.log('Got %d characters of string data:', chunk.length) +}) +``` + +
+encoding
– The encoding to use.
+setEncoding(encoding) =>
setMaxListeners
(n) – By default EventEmitter
s 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 toInfinity
(or 0
) to indicate an unlimited number of listeners.
+ +Returns a reference to the `EventEmitter`, so that calls can be chained. + +
+n
number
setMaxListeners(n) =>
uncork
()
uncork() =>
unpipe
(destination) – The readable.unpipe()
method detaches a Writable
stream previously attached
+using the {@link pipe} method.
+ +If the `destination` is not specified, then _all_ pipes are detached. + +If the `destination` is specified, but no pipe is set up for it, then +the method does nothing. + +```js +const fs = require('fs') +const readable = getReadableStreamSomehow() +const writable = fs.createWriteStream('file.txt') +// All the data from readable goes into 'file.txt', +// but only for the first second. +readable.pipe(writable) +setTimeout(() => { + console.log('Stop writing to file.txt.') + readable.unpipe(writable) + console.log('Manually close the file stream.') + writable.end() +}, 1000) +``` + +
+destination
– Optional specific stream to unpipe
+unpipe(destination) =>
unshift
(chunk, encoding) – Passing chunk
as null
signals the end of the stream (EOF) and behaves the
+same as readable.push(null)
, after which no more data can be written. The EOF
+signal is put at the end of the buffer and any buffered data will still be
+flushed.
+ +The `readable.unshift()` method pushes a chunk of data back into the internal +buffer. This is useful in certain situations where a stream is being consumed by +code that needs to "un-consume" some amount of data that it has optimistically +pulled out of the source, so that the data can be passed on to some other party. + +The `stream.unshift(chunk)` method cannot be called after the `'end'` event +has been emitted or a runtime error will be thrown. + +Developers using `stream.unshift()` often should consider switching to +use of a `Transform` stream instead. See the `API for stream implementers` section for more information. + +```js +// Pull off a header delimited by \n\n. +// Use unshift() if we get too much. +// Call the callback with (error, header, stream). +const { StringDecoder } = require('string_decoder') +function parseHeader(stream, callback) { + stream.on('error', callback) + stream.on('readable', onReadable) + const decoder = new StringDecoder('utf8') + let header = '' + function onReadable() { + let chunk + while (null !== (chunk = stream.read())) { + const str = decoder.write(chunk) + if (str.match(/\n\n/)) { + // Found the header boundary. + const split = str.split(/\n\n/) + header += split.shift() + const remaining = split.join('\n\n') + const buf = Buffer.from(remaining, 'utf8') + stream.removeListener('error', callback) + // Remove the 'readable' listener before unshifting. + stream.removeListener('readable', onReadable) + if (buf.length) + stream.unshift(buf) + // Now the body of the message can be read from the stream. + callback(null, header, stream) + } else { + // Still reading the header. + header += str + } + } + } +} +``` + +Unlike {@link push}, `stream.unshift(chunk)` will not +end the reading process by resetting the internal reading state of the stream. +This can cause unexpected results if `readable.unshift()` is called during a +read (i.e. from within a {@link _read} implementation on a +custom stream). Following the call to `readable.unshift()` with an immediate {@link push} will reset the reading state appropriately, +however it is best to simply avoid calling `readable.unshift()` while in the +process of performing a read. + +
+chunk
– Chunk of data to unshift onto the read queue. For streams not operating in object mode, chunk
must be a string, Buffer
, Uint8Array
or null
. For object mode
+streams, chunk
may be any JavaScript value.any
encoding
– Encoding of string chunks. Must be a valid Buffer
encoding, such as 'utf8'
or 'ascii'
.
+unshift(chunk, encoding) =>
wrap
(stream) – Prior to Node.js 0.10, streams did not implement the entire stream
module API
+as it is currently defined. (See Compatibility
for more information.)
+ +When using an older Node.js library that emits `'data'` events and has a {@link pause} method that is advisory only, the`readable.wrap()` method can be used to create a `Readable` +stream that uses +the old stream as its data source. + +It will rarely be necessary to use `readable.wrap()` but the method has been +provided as a convenience for interacting with older Node.js applications and +libraries. + +```js +const { OldReader } = require('./old-api-module.js') +const { Readable } = require('stream') +const oreader = new OldReader() +const myReader = new Readable().wrap(oreader) + +myReader.on('readable', () => { + myReader.read() // etc. +}) +``` + +
+stream
– An "old style" readable stream
+wrap(stream) =>
write
(chunk, encoding, cb) write(chunk, encoding, cb) =>
chunk
any
cb
(error) undefined | #
error
null
| Error
cb(error) =>
write(chunk, cb) =>
from
(src) – A utility method for creating duplex streams.
+ +- `Stream` converts writable stream into writable `Duplex` and readable stream + to `Duplex`. +- `Blob` converts into readable `Duplex`. +- `string` converts into readable `Duplex`. +- `ArrayBuffer` converts into readable `Duplex`. +- `AsyncIterable` converts into a readable `Duplex`. Cannot yield `null`. +- `AsyncGeneratorFunction` converts into a readable/writable transform + `Duplex`. Must take a source `AsyncIterable` as first parameter. Cannot yield + `null`. +- `AsyncFunction` converts into a writable `Duplex`. Must return + either `null` or `undefined` +- `Object ({ writable, readable })` converts `readable` and + `writable` into `Stream` and then combines them into `Duplex` where the + `Duplex` will write to the `writable` and read from the `readable`. +- `Promise` converts into readable `Duplex`. Value `null` is ignored. + +
+src
string | Object | Stream | Iterable<any> | AsyncIterable<any> | Blob | ArrayBuffer | AsyncGeneratorFunction | Promise<any>
from(src) =>
getEventListeners
(emitter, name) – Returns a copy of the array of listeners for the event named eventName
.
+ +For `EventEmitter`s this behaves exactly the same as calling `.listeners` on +the emitter. + +For `EventTarget`s this is the only way to get the event listeners for the +event target. This is useful for debugging and diagnostic purposes. + +```js +const { getEventListeners, EventEmitter } = require('events') + +{ + const ee = new EventEmitter() + const listener = () => console.log('Events are fun') + ee.on('foo', listener) + getEventListeners(ee, 'foo') // [listener] +} +{ + const et = new EventTarget() + const listener = () => console.log('Events are fun') + et.addEventListener('foo', listener) + getEventListeners(et, 'foo') // [listener] +} +``` + +
+emitter
name
string | symbol
getEventListeners(emitter, name) =>
isDisturbed
(stream) – Returns whether the stream has been read from or cancelled. #
stream
isDisturbed(stream) =>
listenerCount
(emitter, eventName) – A class method that returns the number of listeners for the given eventName
registered on the given emitter
.
+ +```js +const { EventEmitter, listenerCount } = require('events') +const myEmitter = new EventEmitter() +myEmitter.on('event', () => {}) +myEmitter.on('event', () => {}) +console.log(listenerCount(myEmitter, 'event')) +// Prints: 2 +``` + +
+emitter
– The emitter to queryeventName
– The event name
+string | symbol
listenerCount(emitter, eventName) =>
on
(emitter, eventName, options) – ```js
+const { on, EventEmitter } = require('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: + +```js +const { on, EventEmitter } = require('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()); +```` + +
+emitter
eventName
– The name of the event being listened forstring
options
on(emitter, eventName, options) =>
once
(emitter, eventName, options) – 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](https://dom.spec.whatwg.org/#interface-eventtarget) interface, which has no special`'error'` event +semantics and does not listen to the `'error'` event. + +```js +const { once, EventEmitter } = require('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.log('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: + +```js +const { EventEmitter, once } = require('events') + +const ee = new EventEmitter() + +once(ee, 'error') + .then(([err]) => console.log('ok', err.message)) + .catch(err => console.log('error', err.message)) + +ee.emit('error', new Error('boom')) + +// Prints: ok boom +``` + +An `AbortSignal` can be used to cancel waiting for the event: + +```js +const { EventEmitter, once } = require('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() // Abort waiting for the event +ee.emit('foo') // Prints: Waiting for the event was canceled! +``` + +
+emitter
eventName
string | symbol
options
once(emitter, eventName, options) =>
emitter
eventName
string
options
once(emitter, eventName, options) =>
setMaxListeners
(n, eventTargets) – By default EventEmitter
s 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 EventEmitter.setMaxListeners()
method allows the default limit to be
+modified (if eventTargets is empty) or modify the limit specified in every EventTarget
| EventEmitter
passed as arguments.
+The value can be set toInfinity
(or 0
) to indicate an unlimited number of listeners.
+ +```js +EventEmitter.setMaxListeners(20) +// Equivalent to +EventEmitter.defaultMaxListeners = 20 + +const eventTarget = new EventTarget() +// Only way to increase limit for `EventTarget` instances +// as these doesn't expose its own `setMaxListeners` method +EventEmitter.setMaxListeners(20, eventTarget) +``` + +
+n
number
eventTargets
setMaxListeners(n, eventTargets) =>
Readable
boolean boolean boolean boolean boolean number number boolean typeof captureRejectionSymbol boolean typeof errorMonitor
+
+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.
+
+ [asyncIterator]() => #
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L115 destroyed
– Is true
after readable.destroy()
has been called.#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L71 readable
– Is true
if it is safe to call readable.read()
, which means
+the stream has not been destroyed or emitted 'error'
or 'end'
.#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L65 readableAborted
– Returns whether the stream was destroyed or errored before emitting 'end'
.#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L77 readableDidRead
– Returns whether 'data'
has been emitted.#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L82 readableEncoding
– Getter for the property encoding
of a given Readable
stream. The encoding
property can be set using the readable.setEncoding()
method.null
| BufferEncoding#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L87 readableEnded
– Becomes true
when 'end'
event is emitted.#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L93 readableFlowing
– This property reflects the current state of a Readable
stream as described
+in the Three states
section.null
| boolean#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L98 readableHighWaterMark
– Returns the value of highWaterMark
passed when creating this Readable
.#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L105 readableLength
– This property contains the number of bytes (or objects) in the queue
+ready to be read. The value provides introspection data regarding
+the status of the highWaterMark
.#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L110 readableObjectMode
– Getter for the property objectMode
of a given Readable
stream.#
src/.fastpm/-/@types/node@17.0.45/events.d.ts#L301 captureRejectionSymbol
#
src/.fastpm/-/@types/node@17.0.45/events.d.ts#L306 captureRejections
– Sets or gets the default captureRejection value for all emitters.#
src/.fastpm/-/@types/node@17.0.45/events.d.ts#L300 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.#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L479 [asyncIterator]
()
AsyncIterableIterator<any>
_construct
(callback)
_construct(callback) =>
_destroy
(error, callback) #
error
null
| Error
_destroy(error, callback) =>
_read
(size) number#
size
_read(size) =>
addListener
(event, listener) – Event emitter
+The defined events on documents including:
+1. close
+2. data
+3. end
+4. error
+5. pause
+6. readable
+7. resumeaddListener(event, listener) =>
event
"data"
listener
(chunk) any#
chunk
listener(chunk) =>
addListener(event, listener) =>
event
"end"
listener
()
listener() =>
addListener(event, listener) =>
event
"error"
listener
(err) Error#
err
listener(err) =>
addListener(event, listener) =>
event
"pause"
listener
()
listener() =>
addListener(event, listener) =>
event
"readable"
listener
()
listener() =>
addListener(event, listener) =>
event
"resume"
listener
()
listener() =>
addListener(event, listener) =>
event
string | symbol
listener
(args) any []#
args
listener(args) =>
addListener(event, listener) =>
destroy
(error) – Destroy the stream. Optionally emit an 'error'
event, and emit a 'close'
event (unless emitClose
is set to false
). After this call, the readable
+stream will release any internal resources and subsequent calls to push()
will be ignored.
+ +Once `destroy()` has been called any further calls will be a no-op and no +further errors except from `_destroy()` may be emitted as `'error'`. + +Implementors should not override this method, but instead implement `readable._destroy()`. + +
+error
– Error which will be passed as payload in 'error'
event
+Error
destroy(error) =>
emit
(event) – Synchronously calls each of the listeners registered for the event namedeventName
, in the order they were registered, passing the supplied arguments
+to each.
+ +Returns `true` if the event had listeners, `false` otherwise. + +```js +const EventEmitter = require('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 +``` + +
+event
"close"
emit(event) =>
event
"data"
chunk
any
emit(event, chunk) =>
event
"end"
emit(event) =>
event
"error"
err
Error
emit(event, err) =>
event
"pause"
emit(event) =>
event
"readable"
emit(event) =>
event
"resume"
emit(event) =>
event
string | symbol
args
any []
emit(event, args) =>
eventNames
() – Returns an array listing the events for which the emitter has registered
+listeners. The values in the array are strings or Symbol
s.
+ +```js +const EventEmitter = require('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) ] +``` + +
+eventNames() =>
getMaxListeners
() – Returns the current max listener value for the EventEmitter
which is either
+set by emitter.setMaxListeners(n)
or defaults to {@link defaultMaxListeners}.
getMaxListeners() =>
isPaused
() – The readable.isPaused()
method returns the current operating state of theReadable
. This is used primarily by the mechanism that underlies thereadable.pipe()
method. In most
+typical cases, there will be no reason to
+use this method directly.
+ +```js +const readable = new stream.Readable() + +readable.isPaused() // === false +readable.pause() +readable.isPaused() // === true +readable.resume() +readable.isPaused() // === false +``` + +
+isPaused() =>
listenerCount
(eventName) – Returns the number of listeners listening to the event named eventName
. string | symbol#
eventName
– The name of the event being listened for
+
listenerCount(eventName) =>
listeners
(eventName) – Returns a copy of the array of listeners for the event named eventName
.
+ +```js +server.on('connection', stream => { + console.log('someone connected!') +}) +console.log(util.inspect(server.listeners('connection'))) +// Prints: [ [Function] ] +``` + +
+eventName
string | symbol
listeners(eventName) =>
off
(eventName, listener) – Alias for emitter.removeListener()
. string | symbol#
eventName
off(eventName, listener) =>
on
(event, listener) – 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.
+ +```js +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. + +```js +const myEE = new EventEmitter() +myEE.on('foo', () => console.log('a')) +myEE.prependListener('foo', () => console.log('b')) +myEE.emit('foo') +// Prints: +// b +// a +``` + +
+event
"close"
listener
()
listener() =>
on(event, listener) =>
event
"data"
listener
(chunk) any#
chunk
listener(chunk) =>
on(event, listener) =>
event
"end"
listener
()
listener() =>
on(event, listener) =>
event
"error"
listener
(err) Error#
err
listener(err) =>
on(event, listener) =>
event
"pause"
listener
()
listener() =>
on(event, listener) =>
event
"readable"
listener
()
listener() =>
on(event, listener) =>
event
"resume"
listener
()
listener() =>
on(event, listener) =>
event
string | symbol
listener
(args) any []#
args
listener(args) =>
on(event, listener) =>
once
(event, listener) – Adds a one-timelistener
function for the event named eventName
. The
+next time eventName
is triggered, this listener is removed and then invoked.
+ +```js +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. + +```js +const myEE = new EventEmitter() +myEE.once('foo', () => console.log('a')) +myEE.prependOnceListener('foo', () => console.log('b')) +myEE.emit('foo') +// Prints: +// b +// a +``` + +
+event
"close"
listener
()
listener() =>
once(event, listener) =>
event
"data"
listener
(chunk) any#
chunk
listener(chunk) =>
once(event, listener) =>
event
"end"
listener
()
listener() =>
once(event, listener) =>
event
"error"
listener
(err) Error#
err
listener(err) =>
once(event, listener) =>
event
"pause"
listener
()
listener() =>
once(event, listener) =>
event
"readable"
listener
()
listener() =>
once(event, listener) =>
event
"resume"
listener
()
listener() =>
once(event, listener) =>
event
string | symbol
listener
(args) any []#
args
listener(args) =>
once(event, listener) =>
pause
() – The readable.pause()
method will cause a stream in flowing mode to stop
+emitting 'data'
events, switching out of flowing mode. Any data that
+becomes available will remain in the internal buffer.
+ +```js +const readable = getReadableStreamSomehow() +readable.on('data', chunk => { + console.log(`Received ${chunk.length} bytes of data.`) + readable.pause() + console.log('There will be no additional data for 1 second.') + setTimeout(() => { + console.log('Now data will start flowing again.') + readable.resume() + }, 1000) +}) +``` + +The `readable.pause()` method has no effect if there is a `'readable'`event listener. + +
+pause() =>
pipe
(destination, { end }) { #
options
pipe<T extends WritableStream<T>>(destination, { end }) =>
prependListener
(event, listener) – 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.
+ +```js +server.prependListener('connection', stream => { + console.log('someone connected!') +}) +``` + +Returns a reference to the `EventEmitter`, so that calls can be chained. + +
+event
"close"
listener
()
listener() =>
prependListener(event, listener) =>
event
"data"
listener
(chunk) any#
chunk
listener(chunk) =>
prependListener(event, listener) =>
event
"end"
listener
()
listener() =>
prependListener(event, listener) =>
event
"error"
listener
(err) Error#
err
listener(err) =>
prependListener(event, listener) =>
event
"pause"
listener
()
listener() =>
prependListener(event, listener) =>
event
"readable"
listener
()
listener() =>
prependListener(event, listener) =>
event
"resume"
listener
()
listener() =>
prependListener(event, listener) =>
event
string | symbol
listener
(args) any []#
args
listener(args) =>
prependListener(event, listener) =>
prependOnceListener
(event, listener) – Adds a one-timelistener
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.
+ +```js +server.prependOnceListener('connection', stream => { + console.log('Ah, we have our first user!') +}) +``` + +Returns a reference to the `EventEmitter`, so that calls can be chained. + +
+event
"close"
listener
()
listener() =>
prependOnceListener(event, listener) =>
event
"data"
listener
(chunk) any#
chunk
listener(chunk) =>
prependOnceListener(event, listener) =>
event
"end"
listener
()
listener() =>
prependOnceListener(event, listener) =>
event
"error"
listener
(err) Error#
err
listener(err) =>
prependOnceListener(event, listener) =>
event
"pause"
listener
()
listener() =>
prependOnceListener(event, listener) =>
event
"readable"
listener
()
listener() =>
prependOnceListener(event, listener) =>
event
"resume"
listener
()
listener() =>
prependOnceListener(event, listener) =>
event
string | symbol
listener
(args) any []#
args
listener(args) =>
prependOnceListener(event, listener) =>
push
(chunk, encoding) push(chunk, encoding) =>
rawListeners
(eventName) – Returns a copy of the array of listeners for the event named eventName
,
+including any wrappers (such as those created by .once()
).
+ +```js +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') +``` + +
+eventName
string | symbol
rawListeners(eventName) =>
read
(size) – The readable.read()
method pulls some data out of the internal buffer and
+returns it. If no data available to be read, null
is returned. By default,
+the data will be returned as a Buffer
object unless an encoding has been
+specified using the readable.setEncoding()
method or the stream is operating
+in object mode.
+ +The optional `size` argument specifies a specific number of bytes to read. If`size` bytes are not available to be read, `null` will be returned _unless_the stream has ended, in which +case all of the data remaining in the internal +buffer will be returned. + +If the `size` argument is not specified, all of the data contained in the +internal buffer will be returned. + +The `size` argument must be less than or equal to 1 GiB. + +The `readable.read()` method should only be called on `Readable` streams +operating in paused mode. In flowing mode, `readable.read()` is called +automatically until the internal buffer is fully drained. + +```js +const readable = getReadableStreamSomehow() + +// 'readable' may be triggered multiple times as data is buffered in +readable.on('readable', () => { + let chunk + console.log('Stream is readable (new data received in buffer)') + // Use a loop to make sure we read all currently available data + while (null !== (chunk = readable.read())) { + console.log(`Read ${chunk.length} bytes of data...`) + } +}) + +// 'end' will be triggered once when there is no more data available +readable.on('end', () => { + console.log('Reached end of stream.') +}) +``` + +Each call to `readable.read()` returns a chunk of data, or `null`. The chunks +are not concatenated. A `while` loop is necessary to consume all data +currently in the buffer. When reading a large file `.read()` may return `null`, +having consumed all buffered content so far, but there is still more data to +come not yet buffered. In this case a new `'readable'` event will be emitted +when there is more data in the buffer. Finally the `'end'` event will be +emitted when there is no more data to come. + +Therefore to read a file's whole contents from a `readable`, it is necessary +to collect chunks across multiple `'readable'` events: + +```js +const chunks = [] + +readable.on('readable', () => { + let chunk + while (null !== (chunk = readable.read())) { + chunks.push(chunk) + } +}) + +readable.on('end', () => { + const content = chunks.join('') +}) +``` + +A `Readable` stream in object mode will always return a single item from +a call to `readable.read(size)`, regardless of the value of the`size` argument. + +If the `readable.read()` method returns a chunk of data, a `'data'` event will +also be emitted. + +Calling {@link read} after the `'end'` event has +been emitted will return `null`. No runtime error will be raised. + +
+size
– Optional argument to specify how much data to read.
+number
read(size) =>
removeAllListeners
(event) – 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. + +
+event
string | symbol
removeAllListeners(event) =>
removeListener
(event, listener) – Removes the specified listener
from the listener array for the event namedeventName
.
+ +```js +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. + +```js +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 indices 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: + +```js +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. + +
+event
"close"
listener
()
listener() =>
removeListener(event, listener) =>
event
"data"
listener
(chunk) any#
chunk
listener(chunk) =>
removeListener(event, listener) =>
event
"end"
listener
()
listener() =>
removeListener(event, listener) =>
event
"error"
listener
(err) Error#
err
listener(err) =>
removeListener(event, listener) =>
event
"pause"
listener
()
listener() =>
removeListener(event, listener) =>
event
"readable"
listener
()
listener() =>
removeListener(event, listener) =>
event
"resume"
listener
()
listener() =>
removeListener(event, listener) =>
event
string | symbol
listener
(args) any []#
args
listener(args) =>
removeListener(event, listener) =>
resume
() – The readable.resume()
method causes an explicitly paused Readable
stream to
+resume emitting 'data'
events, switching the stream into flowing mode.
+ +The `readable.resume()` method can be used to fully consume the data from a +stream without actually processing any of that data: + +```js +getReadableStreamSomehow() + .resume() + .on('end', () => { + console.log('Reached the end, but did not read anything.') + }) +``` + +The `readable.resume()` method has no effect if there is a `'readable'`event listener. + +
+resume() =>
setEncoding
(encoding) – The readable.setEncoding()
method sets the character encoding for
+data read from the Readable
stream.
+ +By default, no encoding is assigned and stream data will be returned as`Buffer` objects. Setting an encoding causes the stream data +to be returned as strings of the specified encoding rather than as `Buffer`objects. For instance, calling `readable.setEncoding('utf8')` will cause the +output data to be interpreted as UTF-8 data, and passed as strings. Calling`readable.setEncoding('hex')` will cause the data to be encoded in hexadecimal +string format. + +The `Readable` stream will properly handle multi-byte characters delivered +through the stream that would otherwise become improperly decoded if simply +pulled from the stream as `Buffer` objects. + +```js +const readable = getReadableStreamSomehow() +readable.setEncoding('utf8') +readable.on('data', chunk => { + assert.equal(typeof chunk, 'string') + console.log('Got %d characters of string data:', chunk.length) +}) +``` + +
+encoding
– The encoding to use.
+setEncoding(encoding) =>
setMaxListeners
(n) – By default EventEmitter
s 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 toInfinity
(or 0
) to indicate an unlimited number of listeners.
+ +Returns a reference to the `EventEmitter`, so that calls can be chained. + +
+n
number
setMaxListeners(n) =>
unpipe
(destination) – The readable.unpipe()
method detaches a Writable
stream previously attached
+using the {@link pipe} method.
+ +If the `destination` is not specified, then _all_ pipes are detached. + +If the `destination` is specified, but no pipe is set up for it, then +the method does nothing. + +```js +const fs = require('fs') +const readable = getReadableStreamSomehow() +const writable = fs.createWriteStream('file.txt') +// All the data from readable goes into 'file.txt', +// but only for the first second. +readable.pipe(writable) +setTimeout(() => { + console.log('Stop writing to file.txt.') + readable.unpipe(writable) + console.log('Manually close the file stream.') + writable.end() +}, 1000) +``` + +
+destination
– Optional specific stream to unpipe
+unpipe(destination) =>
unshift
(chunk, encoding) – Passing chunk
as null
signals the end of the stream (EOF) and behaves the
+same as readable.push(null)
, after which no more data can be written. The EOF
+signal is put at the end of the buffer and any buffered data will still be
+flushed.
+ +The `readable.unshift()` method pushes a chunk of data back into the internal +buffer. This is useful in certain situations where a stream is being consumed by +code that needs to "un-consume" some amount of data that it has optimistically +pulled out of the source, so that the data can be passed on to some other party. + +The `stream.unshift(chunk)` method cannot be called after the `'end'` event +has been emitted or a runtime error will be thrown. + +Developers using `stream.unshift()` often should consider switching to +use of a `Transform` stream instead. See the `API for stream implementers` section for more information. + +```js +// Pull off a header delimited by \n\n. +// Use unshift() if we get too much. +// Call the callback with (error, header, stream). +const { StringDecoder } = require('string_decoder') +function parseHeader(stream, callback) { + stream.on('error', callback) + stream.on('readable', onReadable) + const decoder = new StringDecoder('utf8') + let header = '' + function onReadable() { + let chunk + while (null !== (chunk = stream.read())) { + const str = decoder.write(chunk) + if (str.match(/\n\n/)) { + // Found the header boundary. + const split = str.split(/\n\n/) + header += split.shift() + const remaining = split.join('\n\n') + const buf = Buffer.from(remaining, 'utf8') + stream.removeListener('error', callback) + // Remove the 'readable' listener before unshifting. + stream.removeListener('readable', onReadable) + if (buf.length) + stream.unshift(buf) + // Now the body of the message can be read from the stream. + callback(null, header, stream) + } else { + // Still reading the header. + header += str + } + } + } +} +``` + +Unlike {@link push}, `stream.unshift(chunk)` will not +end the reading process by resetting the internal reading state of the stream. +This can cause unexpected results if `readable.unshift()` is called during a +read (i.e. from within a {@link _read} implementation on a +custom stream). Following the call to `readable.unshift()` with an immediate {@link push} will reset the reading state appropriately, +however it is best to simply avoid calling `readable.unshift()` while in the +process of performing a read. + +
+chunk
– Chunk of data to unshift onto the read queue. For streams not operating in object mode, chunk
must be a string, Buffer
, Uint8Array
or null
. For object mode
+streams, chunk
may be any JavaScript value.any
encoding
– Encoding of string chunks. Must be a valid Buffer
encoding, such as 'utf8'
or 'ascii'
.
+unshift(chunk, encoding) =>
wrap
(stream) – Prior to Node.js 0.10, streams did not implement the entire stream
module API
+as it is currently defined. (See Compatibility
for more information.)
+ +When using an older Node.js library that emits `'data'` events and has a {@link pause} method that is advisory only, the`readable.wrap()` method can be used to create a `Readable` +stream that uses +the old stream as its data source. + +It will rarely be necessary to use `readable.wrap()` but the method has been +provided as a convenience for interacting with older Node.js applications and +libraries. + +```js +const { OldReader } = require('./old-api-module.js') +const { Readable } = require('stream') +const oreader = new OldReader() +const myReader = new Readable().wrap(oreader) + +myReader.on('readable', () => { + myReader.read() // etc. +}) +``` + +
+stream
– An "old style" readable stream
+wrap(stream) =>
from
(iterable, options) – A utility method for creating Readable Streams out of iterators.getEventListeners
(emitter, name) – Returns a copy of the array of listeners for the event named eventName
.
+ +For `EventEmitter`s this behaves exactly the same as calling `.listeners` on +the emitter. + +For `EventTarget`s this is the only way to get the event listeners for the +event target. This is useful for debugging and diagnostic purposes. + +```js +const { getEventListeners, EventEmitter } = require('events') + +{ + const ee = new EventEmitter() + const listener = () => console.log('Events are fun') + ee.on('foo', listener) + getEventListeners(ee, 'foo') // [listener] +} +{ + const et = new EventTarget() + const listener = () => console.log('Events are fun') + et.addEventListener('foo', listener) + getEventListeners(et, 'foo') // [listener] +} +``` + +
+emitter
name
string | symbol
getEventListeners(emitter, name) =>
isDisturbed
(stream) – Returns whether the stream has been read from or cancelled. #
stream
isDisturbed(stream) =>
listenerCount
(emitter, eventName) – A class method that returns the number of listeners for the given eventName
registered on the given emitter
.
+ +```js +const { EventEmitter, listenerCount } = require('events') +const myEmitter = new EventEmitter() +myEmitter.on('event', () => {}) +myEmitter.on('event', () => {}) +console.log(listenerCount(myEmitter, 'event')) +// Prints: 2 +``` + +
+emitter
– The emitter to queryeventName
– The event name
+string | symbol
listenerCount(emitter, eventName) =>
on
(emitter, eventName, options) – ```js
+const { on, EventEmitter } = require('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: + +```js +const { on, EventEmitter } = require('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()); +```` + +
+emitter
eventName
– The name of the event being listened forstring
options
on(emitter, eventName, options) =>
once
(emitter, eventName, options) – 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](https://dom.spec.whatwg.org/#interface-eventtarget) interface, which has no special`'error'` event +semantics and does not listen to the `'error'` event. + +```js +const { once, EventEmitter } = require('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.log('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: + +```js +const { EventEmitter, once } = require('events') + +const ee = new EventEmitter() + +once(ee, 'error') + .then(([err]) => console.log('ok', err.message)) + .catch(err => console.log('error', err.message)) + +ee.emit('error', new Error('boom')) + +// Prints: ok boom +``` + +An `AbortSignal` can be used to cancel waiting for the event: + +```js +const { EventEmitter, once } = require('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() // Abort waiting for the event +ee.emit('foo') // Prints: Waiting for the event was canceled! +``` + +
+emitter
eventName
string | symbol
options
once(emitter, eventName, options) =>
emitter
eventName
string
options
once(emitter, eventName, options) =>
setMaxListeners
(n, eventTargets) – By default EventEmitter
s 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 EventEmitter.setMaxListeners()
method allows the default limit to be
+modified (if eventTargets is empty) or modify the limit specified in every EventTarget
| EventEmitter
passed as arguments.
+The value can be set toInfinity
(or 0
) to indicate an unlimited number of listeners.
+ +```js +EventEmitter.setMaxListeners(20) +// Equivalent to +EventEmitter.defaultMaxListeners = 20 + +const eventTarget = new EventTarget() +// Only way to increase limit for `EventTarget` instances +// as these doesn't expose its own `setMaxListeners` method +EventEmitter.setMaxListeners(20, eventTarget) +``` + +
+n
number
eventTargets
setMaxListeners(n, eventTargets) =>
Stream
typeof captureRejectionSymbol boolean typeof errorMonitor
+
+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.
+
+#
src/.fastpm/-/@types/node@17.0.45/events.d.ts#L301 captureRejectionSymbol
#
src/.fastpm/-/@types/node@17.0.45/events.d.ts#L306 captureRejections
– Sets or gets the default captureRejection value for all emitters.#
src/.fastpm/-/@types/node@17.0.45/events.d.ts#L300 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.
addListener(eventName, listener) =>
emit
(eventName, args) – Synchronously calls each of the listeners registered for the event namedeventName
, in the order they were registered, passing the supplied arguments
+to each.
+ +Returns `true` if the event had listeners, `false` otherwise. + +```js +const EventEmitter = require('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 +``` + +
+eventName
string | symbol
args
any []
emit(eventName, args) =>
eventNames
() – Returns an array listing the events for which the emitter has registered
+listeners. The values in the array are strings or Symbol
s.
+ +```js +const EventEmitter = require('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) ] +``` + +
+eventNames() =>
getMaxListeners
() – Returns the current max listener value for the EventEmitter
which is either
+set by emitter.setMaxListeners(n)
or defaults to {@link defaultMaxListeners}.
getMaxListeners() =>
listenerCount
(eventName) – Returns the number of listeners listening to the event named eventName
. string | symbol#
eventName
– The name of the event being listened for
+
listenerCount(eventName) =>
listeners
(eventName) – Returns a copy of the array of listeners for the event named eventName
.
+ +```js +server.on('connection', stream => { + console.log('someone connected!') +}) +console.log(util.inspect(server.listeners('connection'))) +// Prints: [ [Function] ] +``` + +
+eventName
string | symbol
listeners(eventName) =>
off
(eventName, listener) – Alias for emitter.removeListener()
. string | symbol#
eventName
off(eventName, listener) =>
on
(eventName, listener) – 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.
+ +```js +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. + +```js +const myEE = new EventEmitter() +myEE.on('foo', () => console.log('a')) +myEE.prependListener('foo', () => console.log('b')) +myEE.emit('foo') +// Prints: +// b +// a +``` + +
+eventName
– The name of the event.string | symbol
listener
(args) any []#
args
listener(args) =>
on(eventName, listener) =>
once
(eventName, listener) – Adds a one-timelistener
function for the event named eventName
. The
+next time eventName
is triggered, this listener is removed and then invoked.
+ +```js +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. + +```js +const myEE = new EventEmitter() +myEE.once('foo', () => console.log('a')) +myEE.prependOnceListener('foo', () => console.log('b')) +myEE.emit('foo') +// Prints: +// b +// a +``` + +
+eventName
– The name of the event.string | symbol
listener
(args) any []#
args
listener(args) =>
once(eventName, listener) =>
pipe
(destination, { end }) { #
options
pipe<T extends WritableStream<T>>(destination, { end }) =>
prependListener
(eventName, listener) – 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.
+ +```js +server.prependListener('connection', stream => { + console.log('someone connected!') +}) +``` + +Returns a reference to the `EventEmitter`, so that calls can be chained. + +
+eventName
– The name of the event.string | symbol
listener
(args) any []#
args
listener(args) =>
prependListener(eventName, listener) =>
prependOnceListener
(eventName, listener) – Adds a one-timelistener
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.
+ +```js +server.prependOnceListener('connection', stream => { + console.log('Ah, we have our first user!') +}) +``` + +Returns a reference to the `EventEmitter`, so that calls can be chained. + +
+eventName
– The name of the event.string | symbol
listener
(args) any []#
args
listener(args) =>
prependOnceListener(eventName, listener) =>
rawListeners
(eventName) – Returns a copy of the array of listeners for the event named eventName
,
+including any wrappers (such as those created by .once()
).
+ +```js +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') +``` + +
+eventName
string | symbol
rawListeners(eventName) =>
removeAllListeners
(event) – 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. + +
+event
string | symbol
removeAllListeners(event) =>
removeListener
(eventName, listener) – Removes the specified listener
from the listener array for the event namedeventName
.
+ +```js +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. + +```js +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 indices 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: + +```js +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. + +
+eventName
string | symbol
listener
(args) any []#
args
listener(args) =>
removeListener(eventName, listener) =>
setMaxListeners
(n) – By default EventEmitter
s 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 toInfinity
(or 0
) to indicate an unlimited number of listeners.
+ +Returns a reference to the `EventEmitter`, so that calls can be chained. + +
+n
number
setMaxListeners(n) =>
getEventListeners
(emitter, name) – Returns a copy of the array of listeners for the event named eventName
.
+ +For `EventEmitter`s this behaves exactly the same as calling `.listeners` on +the emitter. + +For `EventTarget`s this is the only way to get the event listeners for the +event target. This is useful for debugging and diagnostic purposes. + +```js +const { getEventListeners, EventEmitter } = require('events') + +{ + const ee = new EventEmitter() + const listener = () => console.log('Events are fun') + ee.on('foo', listener) + getEventListeners(ee, 'foo') // [listener] +} +{ + const et = new EventTarget() + const listener = () => console.log('Events are fun') + et.addEventListener('foo', listener) + getEventListeners(et, 'foo') // [listener] +} +``` + +
+emitter
name
string | symbol
getEventListeners(emitter, name) =>
listenerCount
(emitter, eventName) – A class method that returns the number of listeners for the given eventName
registered on the given emitter
.
+ +```js +const { EventEmitter, listenerCount } = require('events') +const myEmitter = new EventEmitter() +myEmitter.on('event', () => {}) +myEmitter.on('event', () => {}) +console.log(listenerCount(myEmitter, 'event')) +// Prints: 2 +``` + +
+emitter
– The emitter to queryeventName
– The event name
+string | symbol
listenerCount(emitter, eventName) =>
on
(emitter, eventName, options) – ```js
+const { on, EventEmitter } = require('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: + +```js +const { on, EventEmitter } = require('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()); +```` + +
+emitter
eventName
– The name of the event being listened forstring
options
on(emitter, eventName, options) =>
once
(emitter, eventName, options) – 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](https://dom.spec.whatwg.org/#interface-eventtarget) interface, which has no special`'error'` event +semantics and does not listen to the `'error'` event. + +```js +const { once, EventEmitter } = require('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.log('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: + +```js +const { EventEmitter, once } = require('events') + +const ee = new EventEmitter() + +once(ee, 'error') + .then(([err]) => console.log('ok', err.message)) + .catch(err => console.log('error', err.message)) + +ee.emit('error', new Error('boom')) + +// Prints: ok boom +``` + +An `AbortSignal` can be used to cancel waiting for the event: + +```js +const { EventEmitter, once } = require('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() // Abort waiting for the event +ee.emit('foo') // Prints: Waiting for the event was canceled! +``` + +
+emitter
eventName
string | symbol
options
once(emitter, eventName, options) =>
emitter
eventName
string
options
once(emitter, eventName, options) =>
setMaxListeners
(n, eventTargets) – By default EventEmitter
s 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 EventEmitter.setMaxListeners()
method allows the default limit to be
+modified (if eventTargets is empty) or modify the limit specified in every EventTarget
| EventEmitter
passed as arguments.
+The value can be set toInfinity
(or 0
) to indicate an unlimited number of listeners.
+ +```js +EventEmitter.setMaxListeners(20) +// Equivalent to +EventEmitter.defaultMaxListeners = 20 + +const eventTarget = new EventTarget() +// Only way to increase limit for `EventTarget` instances +// as these doesn't expose its own `setMaxListeners` method +EventEmitter.setMaxListeners(20, eventTarget) +``` + +
+n
number
eventTargets
setMaxListeners(n, eventTargets) =>
Transform
– Transform streams are Duplex
streams where the output is in some way
+related to the input. Like all Duplex
streams, Transform
streams
+implement both the Readable
and Writable
interfaces.+ +Examples of `Transform` streams include: + +- `zlib streams` +- `crypto streams` + +
+ boolean
+
+This can be changed manually to change the half-open behavior of an existing`Duplex` stream instance, but must be changed before the `'end'` event is
+emitted.
+
+ boolean boolean boolean boolean boolean number number boolean typeof captureRejectionSymbol boolean typeof errorMonitor
+
+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.
+
+ [asyncIterator]() => #
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L819 allowHalfOpen
– If false
then the stream will automatically end the writable side when the
+readable side ends. Set initially by the allowHalfOpen
constructor option,
+which defaults to false
.#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L115 destroyed
– Is true
after readable.destroy()
has been called.#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L71 readable
– Is true
if it is safe to call readable.read()
, which means
+the stream has not been destroyed or emitted 'error'
or 'end'
.#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L65 readableAborted
– Returns whether the stream was destroyed or errored before emitting 'end'
.#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L77 readableDidRead
– Returns whether 'data'
has been emitted.#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L82 readableEncoding
– Getter for the property encoding
of a given Readable
stream. The encoding
property can be set using the readable.setEncoding()
method.null
| BufferEncoding#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L87 readableEnded
– Becomes true
when 'end'
event is emitted.#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L93 readableFlowing
– This property reflects the current state of a Readable
stream as described
+in the Three states
section.null
| boolean#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L98 readableHighWaterMark
– Returns the value of highWaterMark
passed when creating this Readable
.#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L105 readableLength
– This property contains the number of bytes (or objects) in the queue
+ready to be read. The value provides introspection data regarding
+the status of the highWaterMark
.#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L110 readableObjectMode
– Getter for the property objectMode
of a given Readable
stream.#
src/.fastpm/-/@types/node@17.0.45/events.d.ts#L301 captureRejectionSymbol
#
src/.fastpm/-/@types/node@17.0.45/events.d.ts#L306 captureRejections
– Sets or gets the default captureRejection value for all emitters.#
src/.fastpm/-/@types/node@17.0.45/events.d.ts#L300 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.#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L479 [asyncIterator]
()
AsyncIterableIterator<any>
_construct
(callback)
_construct(callback) =>
_destroy
(error, callback) #
error
null
| Error
_destroy(error, callback) =>
_final
(callback)
_final(callback) =>
_flush
(callback) #
callback
_flush(callback) =>
_read
(size) number#
size
_read(size) =>
_transform
(chunk, encoding, callback) _write
(chunk, encoding, callback) _write(chunk, encoding, callback) =>
_writev
(chunks, callback) { #
chunks
callback
(error) #
error
null
| Error
callback(error) =>
_writev(chunks, callback) =>
addListener
(event, listener) – Event emitter
+The defined events on documents including:
+1. close
+2. data
+3. end
+4. error
+5. pause
+6. readable
+7. resumeaddListener(event, listener) =>
event
"data"
listener
(chunk) any#
chunk
listener(chunk) =>
addListener(event, listener) =>
event
"end"
listener
()
listener() =>
addListener(event, listener) =>
event
"error"
listener
(err) Error#
err
listener(err) =>
addListener(event, listener) =>
event
"pause"
listener
()
listener() =>
addListener(event, listener) =>
event
"readable"
listener
()
listener() =>
addListener(event, listener) =>
event
"resume"
listener
()
listener() =>
addListener(event, listener) =>
event
string | symbol
listener
(args) any []#
args
listener(args) =>
addListener(event, listener) =>
cork
()
cork() =>
destroy
(error) – Destroy the stream. Optionally emit an 'error'
event, and emit a 'close'
event (unless emitClose
is set to false
). After this call, the readable
+stream will release any internal resources and subsequent calls to push()
will be ignored.
+ +Once `destroy()` has been called any further calls will be a no-op and no +further errors except from `_destroy()` may be emitted as `'error'`. + +Implementors should not override this method, but instead implement `readable._destroy()`. + +
+error
– Error which will be passed as payload in 'error'
event
+Error
destroy(error) =>
emit
(event) – Synchronously calls each of the listeners registered for the event namedeventName
, in the order they were registered, passing the supplied arguments
+to each.
+ +Returns `true` if the event had listeners, `false` otherwise. + +```js +const EventEmitter = require('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 +``` + +
+event
"close"
emit(event) =>
event
"data"
chunk
any
emit(event, chunk) =>
event
"end"
emit(event) =>
event
"error"
err
Error
emit(event, err) =>
event
"pause"
emit(event) =>
event
"readable"
emit(event) =>
event
"resume"
emit(event) =>
event
string | symbol
args
any []
emit(event, args) =>
end
(cb) cb() => #
cb
()
void
end(cb) =>
chunk
any
cb
()
cb() =>
end(chunk, cb) =>
chunk
any
encoding
cb
()
cb() =>
end(chunk, encoding, cb) =>
eventNames
() – Returns an array listing the events for which the emitter has registered
+listeners. The values in the array are strings or Symbol
s.
+ +```js +const EventEmitter = require('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) ] +``` + +
+eventNames() =>
getMaxListeners
() – Returns the current max listener value for the EventEmitter
which is either
+set by emitter.setMaxListeners(n)
or defaults to {@link defaultMaxListeners}.
getMaxListeners() =>
isPaused
() – The readable.isPaused()
method returns the current operating state of theReadable
. This is used primarily by the mechanism that underlies thereadable.pipe()
method. In most
+typical cases, there will be no reason to
+use this method directly.
+ +```js +const readable = new stream.Readable() + +readable.isPaused() // === false +readable.pause() +readable.isPaused() // === true +readable.resume() +readable.isPaused() // === false +``` + +
+isPaused() =>
listenerCount
(eventName) – Returns the number of listeners listening to the event named eventName
. string | symbol#
eventName
– The name of the event being listened for
+
listenerCount(eventName) =>
listeners
(eventName) – Returns a copy of the array of listeners for the event named eventName
.
+ +```js +server.on('connection', stream => { + console.log('someone connected!') +}) +console.log(util.inspect(server.listeners('connection'))) +// Prints: [ [Function] ] +``` + +
+eventName
string | symbol
listeners(eventName) =>
off
(eventName, listener) – Alias for emitter.removeListener()
. string | symbol#
eventName
off(eventName, listener) =>
on
(event, listener) – 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.
+ +```js +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. + +```js +const myEE = new EventEmitter() +myEE.on('foo', () => console.log('a')) +myEE.prependListener('foo', () => console.log('b')) +myEE.emit('foo') +// Prints: +// b +// a +``` + +
+event
"close"
listener
()
listener() =>
on(event, listener) =>
event
"data"
listener
(chunk) any#
chunk
listener(chunk) =>
on(event, listener) =>
event
"end"
listener
()
listener() =>
on(event, listener) =>
event
"error"
listener
(err) Error#
err
listener(err) =>
on(event, listener) =>
event
"pause"
listener
()
listener() =>
on(event, listener) =>
event
"readable"
listener
()
listener() =>
on(event, listener) =>
event
"resume"
listener
()
listener() =>
on(event, listener) =>
event
string | symbol
listener
(args) any []#
args
listener(args) =>
on(event, listener) =>
once
(event, listener) – Adds a one-timelistener
function for the event named eventName
. The
+next time eventName
is triggered, this listener is removed and then invoked.
+ +```js +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. + +```js +const myEE = new EventEmitter() +myEE.once('foo', () => console.log('a')) +myEE.prependOnceListener('foo', () => console.log('b')) +myEE.emit('foo') +// Prints: +// b +// a +``` + +
+event
"close"
listener
()
listener() =>
once(event, listener) =>
event
"data"
listener
(chunk) any#
chunk
listener(chunk) =>
once(event, listener) =>
event
"end"
listener
()
listener() =>
once(event, listener) =>
event
"error"
listener
(err) Error#
err
listener(err) =>
once(event, listener) =>
event
"pause"
listener
()
listener() =>
once(event, listener) =>
event
"readable"
listener
()
listener() =>
once(event, listener) =>
event
"resume"
listener
()
listener() =>
once(event, listener) =>
event
string | symbol
listener
(args) any []#
args
listener(args) =>
once(event, listener) =>
pause
() – The readable.pause()
method will cause a stream in flowing mode to stop
+emitting 'data'
events, switching out of flowing mode. Any data that
+becomes available will remain in the internal buffer.
+ +```js +const readable = getReadableStreamSomehow() +readable.on('data', chunk => { + console.log(`Received ${chunk.length} bytes of data.`) + readable.pause() + console.log('There will be no additional data for 1 second.') + setTimeout(() => { + console.log('Now data will start flowing again.') + readable.resume() + }, 1000) +}) +``` + +The `readable.pause()` method has no effect if there is a `'readable'`event listener. + +
+pause() =>
pipe
(destination, { end }) { #
options
pipe<T extends WritableStream<T>>(destination, { end }) =>
prependListener
(event, listener) – 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.
+ +```js +server.prependListener('connection', stream => { + console.log('someone connected!') +}) +``` + +Returns a reference to the `EventEmitter`, so that calls can be chained. + +
+event
"close"
listener
()
listener() =>
prependListener(event, listener) =>
event
"data"
listener
(chunk) any#
chunk
listener(chunk) =>
prependListener(event, listener) =>
event
"end"
listener
()
listener() =>
prependListener(event, listener) =>
event
"error"
listener
(err) Error#
err
listener(err) =>
prependListener(event, listener) =>
event
"pause"
listener
()
listener() =>
prependListener(event, listener) =>
event
"readable"
listener
()
listener() =>
prependListener(event, listener) =>
event
"resume"
listener
()
listener() =>
prependListener(event, listener) =>
event
string | symbol
listener
(args) any []#
args
listener(args) =>
prependListener(event, listener) =>
prependOnceListener
(event, listener) – Adds a one-timelistener
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.
+ +```js +server.prependOnceListener('connection', stream => { + console.log('Ah, we have our first user!') +}) +``` + +Returns a reference to the `EventEmitter`, so that calls can be chained. + +
+event
"close"
listener
()
listener() =>
prependOnceListener(event, listener) =>
event
"data"
listener
(chunk) any#
chunk
listener(chunk) =>
prependOnceListener(event, listener) =>
event
"end"
listener
()
listener() =>
prependOnceListener(event, listener) =>
event
"error"
listener
(err) Error#
err
listener(err) =>
prependOnceListener(event, listener) =>
event
"pause"
listener
()
listener() =>
prependOnceListener(event, listener) =>
event
"readable"
listener
()
listener() =>
prependOnceListener(event, listener) =>
event
"resume"
listener
()
listener() =>
prependOnceListener(event, listener) =>
event
string | symbol
listener
(args) any []#
args
listener(args) =>
prependOnceListener(event, listener) =>
push
(chunk, encoding) push(chunk, encoding) =>
rawListeners
(eventName) – Returns a copy of the array of listeners for the event named eventName
,
+including any wrappers (such as those created by .once()
).
+ +```js +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') +``` + +
+eventName
string | symbol
rawListeners(eventName) =>
read
(size) – The readable.read()
method pulls some data out of the internal buffer and
+returns it. If no data available to be read, null
is returned. By default,
+the data will be returned as a Buffer
object unless an encoding has been
+specified using the readable.setEncoding()
method or the stream is operating
+in object mode.
+ +The optional `size` argument specifies a specific number of bytes to read. If`size` bytes are not available to be read, `null` will be returned _unless_the stream has ended, in which +case all of the data remaining in the internal +buffer will be returned. + +If the `size` argument is not specified, all of the data contained in the +internal buffer will be returned. + +The `size` argument must be less than or equal to 1 GiB. + +The `readable.read()` method should only be called on `Readable` streams +operating in paused mode. In flowing mode, `readable.read()` is called +automatically until the internal buffer is fully drained. + +```js +const readable = getReadableStreamSomehow() + +// 'readable' may be triggered multiple times as data is buffered in +readable.on('readable', () => { + let chunk + console.log('Stream is readable (new data received in buffer)') + // Use a loop to make sure we read all currently available data + while (null !== (chunk = readable.read())) { + console.log(`Read ${chunk.length} bytes of data...`) + } +}) + +// 'end' will be triggered once when there is no more data available +readable.on('end', () => { + console.log('Reached end of stream.') +}) +``` + +Each call to `readable.read()` returns a chunk of data, or `null`. The chunks +are not concatenated. A `while` loop is necessary to consume all data +currently in the buffer. When reading a large file `.read()` may return `null`, +having consumed all buffered content so far, but there is still more data to +come not yet buffered. In this case a new `'readable'` event will be emitted +when there is more data in the buffer. Finally the `'end'` event will be +emitted when there is no more data to come. + +Therefore to read a file's whole contents from a `readable`, it is necessary +to collect chunks across multiple `'readable'` events: + +```js +const chunks = [] + +readable.on('readable', () => { + let chunk + while (null !== (chunk = readable.read())) { + chunks.push(chunk) + } +}) + +readable.on('end', () => { + const content = chunks.join('') +}) +``` + +A `Readable` stream in object mode will always return a single item from +a call to `readable.read(size)`, regardless of the value of the`size` argument. + +If the `readable.read()` method returns a chunk of data, a `'data'` event will +also be emitted. + +Calling {@link read} after the `'end'` event has +been emitted will return `null`. No runtime error will be raised. + +
+size
– Optional argument to specify how much data to read.
+number
read(size) =>
removeAllListeners
(event) – 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. + +
+event
string | symbol
removeAllListeners(event) =>
removeListener
(event, listener) – Removes the specified listener
from the listener array for the event namedeventName
.
+ +```js +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. + +```js +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 indices 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: + +```js +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. + +
+event
"close"
listener
()
listener() =>
removeListener(event, listener) =>
event
"data"
listener
(chunk) any#
chunk
listener(chunk) =>
removeListener(event, listener) =>
event
"end"
listener
()
listener() =>
removeListener(event, listener) =>
event
"error"
listener
(err) Error#
err
listener(err) =>
removeListener(event, listener) =>
event
"pause"
listener
()
listener() =>
removeListener(event, listener) =>
event
"readable"
listener
()
listener() =>
removeListener(event, listener) =>
event
"resume"
listener
()
listener() =>
removeListener(event, listener) =>
event
string | symbol
listener
(args) any []#
args
listener(args) =>
removeListener(event, listener) =>
resume
() – The readable.resume()
method causes an explicitly paused Readable
stream to
+resume emitting 'data'
events, switching the stream into flowing mode.
+ +The `readable.resume()` method can be used to fully consume the data from a +stream without actually processing any of that data: + +```js +getReadableStreamSomehow() + .resume() + .on('end', () => { + console.log('Reached the end, but did not read anything.') + }) +``` + +The `readable.resume()` method has no effect if there is a `'readable'`event listener. + +
+resume() =>
setDefaultEncoding
(encoding) #
encoding
setDefaultEncoding(encoding) =>
setEncoding
(encoding) – The readable.setEncoding()
method sets the character encoding for
+data read from the Readable
stream.
+ +By default, no encoding is assigned and stream data will be returned as`Buffer` objects. Setting an encoding causes the stream data +to be returned as strings of the specified encoding rather than as `Buffer`objects. For instance, calling `readable.setEncoding('utf8')` will cause the +output data to be interpreted as UTF-8 data, and passed as strings. Calling`readable.setEncoding('hex')` will cause the data to be encoded in hexadecimal +string format. + +The `Readable` stream will properly handle multi-byte characters delivered +through the stream that would otherwise become improperly decoded if simply +pulled from the stream as `Buffer` objects. + +```js +const readable = getReadableStreamSomehow() +readable.setEncoding('utf8') +readable.on('data', chunk => { + assert.equal(typeof chunk, 'string') + console.log('Got %d characters of string data:', chunk.length) +}) +``` + +
+encoding
– The encoding to use.
+setEncoding(encoding) =>
setMaxListeners
(n) – By default EventEmitter
s 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 toInfinity
(or 0
) to indicate an unlimited number of listeners.
+ +Returns a reference to the `EventEmitter`, so that calls can be chained. + +
+n
number
setMaxListeners(n) =>
uncork
()
uncork() =>
unpipe
(destination) – The readable.unpipe()
method detaches a Writable
stream previously attached
+using the {@link pipe} method.
+ +If the `destination` is not specified, then _all_ pipes are detached. + +If the `destination` is specified, but no pipe is set up for it, then +the method does nothing. + +```js +const fs = require('fs') +const readable = getReadableStreamSomehow() +const writable = fs.createWriteStream('file.txt') +// All the data from readable goes into 'file.txt', +// but only for the first second. +readable.pipe(writable) +setTimeout(() => { + console.log('Stop writing to file.txt.') + readable.unpipe(writable) + console.log('Manually close the file stream.') + writable.end() +}, 1000) +``` + +
+destination
– Optional specific stream to unpipe
+unpipe(destination) =>
unshift
(chunk, encoding) – Passing chunk
as null
signals the end of the stream (EOF) and behaves the
+same as readable.push(null)
, after which no more data can be written. The EOF
+signal is put at the end of the buffer and any buffered data will still be
+flushed.
+ +The `readable.unshift()` method pushes a chunk of data back into the internal +buffer. This is useful in certain situations where a stream is being consumed by +code that needs to "un-consume" some amount of data that it has optimistically +pulled out of the source, so that the data can be passed on to some other party. + +The `stream.unshift(chunk)` method cannot be called after the `'end'` event +has been emitted or a runtime error will be thrown. + +Developers using `stream.unshift()` often should consider switching to +use of a `Transform` stream instead. See the `API for stream implementers` section for more information. + +```js +// Pull off a header delimited by \n\n. +// Use unshift() if we get too much. +// Call the callback with (error, header, stream). +const { StringDecoder } = require('string_decoder') +function parseHeader(stream, callback) { + stream.on('error', callback) + stream.on('readable', onReadable) + const decoder = new StringDecoder('utf8') + let header = '' + function onReadable() { + let chunk + while (null !== (chunk = stream.read())) { + const str = decoder.write(chunk) + if (str.match(/\n\n/)) { + // Found the header boundary. + const split = str.split(/\n\n/) + header += split.shift() + const remaining = split.join('\n\n') + const buf = Buffer.from(remaining, 'utf8') + stream.removeListener('error', callback) + // Remove the 'readable' listener before unshifting. + stream.removeListener('readable', onReadable) + if (buf.length) + stream.unshift(buf) + // Now the body of the message can be read from the stream. + callback(null, header, stream) + } else { + // Still reading the header. + header += str + } + } + } +} +``` + +Unlike {@link push}, `stream.unshift(chunk)` will not +end the reading process by resetting the internal reading state of the stream. +This can cause unexpected results if `readable.unshift()` is called during a +read (i.e. from within a {@link _read} implementation on a +custom stream). Following the call to `readable.unshift()` with an immediate {@link push} will reset the reading state appropriately, +however it is best to simply avoid calling `readable.unshift()` while in the +process of performing a read. + +
+chunk
– Chunk of data to unshift onto the read queue. For streams not operating in object mode, chunk
must be a string, Buffer
, Uint8Array
or null
. For object mode
+streams, chunk
may be any JavaScript value.any
encoding
– Encoding of string chunks. Must be a valid Buffer
encoding, such as 'utf8'
or 'ascii'
.
+unshift(chunk, encoding) =>
wrap
(stream) – Prior to Node.js 0.10, streams did not implement the entire stream
module API
+as it is currently defined. (See Compatibility
for more information.)
+ +When using an older Node.js library that emits `'data'` events and has a {@link pause} method that is advisory only, the`readable.wrap()` method can be used to create a `Readable` +stream that uses +the old stream as its data source. + +It will rarely be necessary to use `readable.wrap()` but the method has been +provided as a convenience for interacting with older Node.js applications and +libraries. + +```js +const { OldReader } = require('./old-api-module.js') +const { Readable } = require('stream') +const oreader = new OldReader() +const myReader = new Readable().wrap(oreader) + +myReader.on('readable', () => { + myReader.read() // etc. +}) +``` + +
+stream
– An "old style" readable stream
+wrap(stream) =>
write
(chunk, encoding, cb) write(chunk, encoding, cb) =>
chunk
any
cb
(error) undefined | #
error
null
| Error
cb(error) =>
write(chunk, cb) =>
from
(src) – A utility method for creating duplex streams.
+ +- `Stream` converts writable stream into writable `Duplex` and readable stream + to `Duplex`. +- `Blob` converts into readable `Duplex`. +- `string` converts into readable `Duplex`. +- `ArrayBuffer` converts into readable `Duplex`. +- `AsyncIterable` converts into a readable `Duplex`. Cannot yield `null`. +- `AsyncGeneratorFunction` converts into a readable/writable transform + `Duplex`. Must take a source `AsyncIterable` as first parameter. Cannot yield + `null`. +- `AsyncFunction` converts into a writable `Duplex`. Must return + either `null` or `undefined` +- `Object ({ writable, readable })` converts `readable` and + `writable` into `Stream` and then combines them into `Duplex` where the + `Duplex` will write to the `writable` and read from the `readable`. +- `Promise` converts into readable `Duplex`. Value `null` is ignored. + +
+src
string | Object | Stream | Iterable<any> | AsyncIterable<any> | Blob | ArrayBuffer | AsyncGeneratorFunction | Promise<any>
from(src) =>
getEventListeners
(emitter, name) – Returns a copy of the array of listeners for the event named eventName
.
+ +For `EventEmitter`s this behaves exactly the same as calling `.listeners` on +the emitter. + +For `EventTarget`s this is the only way to get the event listeners for the +event target. This is useful for debugging and diagnostic purposes. + +```js +const { getEventListeners, EventEmitter } = require('events') + +{ + const ee = new EventEmitter() + const listener = () => console.log('Events are fun') + ee.on('foo', listener) + getEventListeners(ee, 'foo') // [listener] +} +{ + const et = new EventTarget() + const listener = () => console.log('Events are fun') + et.addEventListener('foo', listener) + getEventListeners(et, 'foo') // [listener] +} +``` + +
+emitter
name
string | symbol
getEventListeners(emitter, name) =>
isDisturbed
(stream) – Returns whether the stream has been read from or cancelled. #
stream
isDisturbed(stream) =>
listenerCount
(emitter, eventName) – A class method that returns the number of listeners for the given eventName
registered on the given emitter
.
+ +```js +const { EventEmitter, listenerCount } = require('events') +const myEmitter = new EventEmitter() +myEmitter.on('event', () => {}) +myEmitter.on('event', () => {}) +console.log(listenerCount(myEmitter, 'event')) +// Prints: 2 +``` + +
+emitter
– The emitter to queryeventName
– The event name
+string | symbol
listenerCount(emitter, eventName) =>
on
(emitter, eventName, options) – ```js
+const { on, EventEmitter } = require('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: + +```js +const { on, EventEmitter } = require('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()); +```` + +
+emitter
eventName
– The name of the event being listened forstring
options
on(emitter, eventName, options) =>
once
(emitter, eventName, options) – 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](https://dom.spec.whatwg.org/#interface-eventtarget) interface, which has no special`'error'` event +semantics and does not listen to the `'error'` event. + +```js +const { once, EventEmitter } = require('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.log('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: + +```js +const { EventEmitter, once } = require('events') + +const ee = new EventEmitter() + +once(ee, 'error') + .then(([err]) => console.log('ok', err.message)) + .catch(err => console.log('error', err.message)) + +ee.emit('error', new Error('boom')) + +// Prints: ok boom +``` + +An `AbortSignal` can be used to cancel waiting for the event: + +```js +const { EventEmitter, once } = require('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() // Abort waiting for the event +ee.emit('foo') // Prints: Waiting for the event was canceled! +``` + +
+emitter
eventName
string | symbol
options
once(emitter, eventName, options) =>
emitter
eventName
string
options
once(emitter, eventName, options) =>
setMaxListeners
(n, eventTargets) – By default EventEmitter
s 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 EventEmitter.setMaxListeners()
method allows the default limit to be
+modified (if eventTargets is empty) or modify the limit specified in every EventTarget
| EventEmitter
passed as arguments.
+The value can be set toInfinity
(or 0
) to indicate an unlimited number of listeners.
+ +```js +EventEmitter.setMaxListeners(20) +// Equivalent to +EventEmitter.defaultMaxListeners = 20 + +const eventTarget = new EventTarget() +// Only way to increase limit for `EventTarget` instances +// as these doesn't expose its own `setMaxListeners` method +EventEmitter.setMaxListeners(20, eventTarget) +``` + +
+n
number
eventTargets
setMaxListeners(n, eventTargets) =>
Writable
boolean boolean number boolean boolean number number boolean typeof captureRejectionSymbol boolean typeof errorMonitor
+
+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.
+
+#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L543 destroyed
– Is true
after writable.destroy()
has been called.#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L504 writable
– Is true
if it is safe to call writable.write()
, which means
+the stream has not been destroyed, errored or ended.#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L538 writableCorked
– Number of times writable.uncork()
needs to be
+called in order to fully uncork the stream.#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L510 writableEnded
– Is true
after writable.end()
has been called. This property
+does not indicate whether the data has been flushed, for this use writable.writableFinished
instead.#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L515 writableFinished
– Is set to true
immediately before the 'finish'
event is emitted.#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L520 writableHighWaterMark
– Return the value of highWaterMark
passed when creating this Writable
.#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L527 writableLength
– This property contains the number of bytes (or objects) in the queue
+ready to be written. The value provides introspection data regarding
+the status of the highWaterMark
.#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L532 writableObjectMode
– Getter for the property objectMode
of a given Writable
stream.#
src/.fastpm/-/@types/node@17.0.45/events.d.ts#L301 captureRejectionSymbol
#
src/.fastpm/-/@types/node@17.0.45/events.d.ts#L306 captureRejections
– Sets or gets the default captureRejection value for all emitters.#
src/.fastpm/-/@types/node@17.0.45/events.d.ts#L300 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.
_construct(callback) =>
_destroy
(error, callback) #
error
null
| Error
_destroy(error, callback) =>
_final
(callback)
_final(callback) =>
_write
(chunk, encoding, callback) _write(chunk, encoding, callback) =>
_writev
(chunks, callback) { #
chunks
callback
(error) #
error
null
| Error
callback(error) =>
_writev(chunks, callback) =>
addListener
(event, listener) – Event emitter
+The defined events on documents including:
+1. close
+2. drain
+3. error
+4. finish
+5. pipe
+6. unpipeaddListener(event, listener) =>
event
"drain"
listener
()
listener() =>
addListener(event, listener) =>
event
"error"
listener
(err) Error#
err
listener(err) =>
addListener(event, listener) =>
event
"finish"
listener
()
listener() =>
addListener(event, listener) =>
event
"pipe"
addListener(event, listener) =>
event
"unpipe"
addListener(event, listener) =>
event
string | symbol
listener
(args) any []#
args
listener(args) =>
addListener(event, listener) =>
cork
() – The writable.cork()
method forces all written data to be buffered in memory.
+The buffered data will be flushed when either the {@link uncork} or {@link end} methods are called.
+ +The primary intent of `writable.cork()` is to accommodate a situation in which +several small chunks are written to the stream in rapid succession. Instead of +immediately forwarding them to the underlying destination, `writable.cork()`buffers all the chunks until `writable.uncork()` is called, which will pass them +all to `writable._writev()`, if present. This prevents a head-of-line blocking +situation where data is being buffered while waiting for the first small chunk +to be processed. However, use of `writable.cork()` without implementing`writable._writev()` may have an adverse effect on throughput. + +See also: `writable.uncork()`, `writable._writev()`. + +
+cork() =>
destroy
(error) – Destroy the stream. Optionally emit an 'error'
event, and emit a 'close'
event (unless emitClose
is set to false
). After this call, the writable
+stream has ended and subsequent calls to write()
or end()
will result in
+an ERR_STREAM_DESTROYED
error.
+This is a destructive and immediate way to destroy a stream. Previous calls towrite()
may not have drained, and may trigger an ERR_STREAM_DESTROYED
error.
+Use end()
instead of destroy if data should flush before close, or wait for
+the 'drain'
event before destroying the stream.
+ +Once `destroy()` has been called any further calls will be a no-op and no +further errors except from `_destroy()` may be emitted as `'error'`. + +Implementors should not override this method, +but instead implement `writable._destroy()`. + +
+error
– Optional, an error to emit with 'error'
event.
+Error
destroy(error) =>
emit
(event) – Synchronously calls each of the listeners registered for the event namedeventName
, in the order they were registered, passing the supplied arguments
+to each.
+ +Returns `true` if the event had listeners, `false` otherwise. + +```js +const EventEmitter = require('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 +``` + +
+event
"close"
emit(event) =>
event
"drain"
emit(event) =>
event
"error"
err
Error
emit(event, err) =>
event
"finish"
emit(event) =>
event
"pipe"
src
emit(event, src) =>
event
"unpipe"
src
emit(event, src) =>
event
string | symbol
args
any []
emit(event, args) =>
end
(cb) – Calling the writable.end()
method signals that no more data will be written
+to the Writable
. The optional chunk
and encoding
arguments allow one
+final additional chunk of data to be written immediately before closing the
+stream.
+ +Calling the {@link write} method after calling {@link end} will raise an error. + +```js +// Write 'hello, ' and then end with 'world!'. +const fs = require('fs') +const file = fs.createWriteStream('example.txt') +file.write('hello, ') +file.end('world!') +// Writing more now is not allowed! +``` + +
+cb
()
cb() =>
end(cb) =>
chunk
any
cb
()
cb() =>
end(chunk, cb) =>
chunk
any
encoding
cb
()
cb() =>
end(chunk, encoding, cb) =>
eventNames
() – Returns an array listing the events for which the emitter has registered
+listeners. The values in the array are strings or Symbol
s.
+ +```js +const EventEmitter = require('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) ] +``` + +
+eventNames() =>
getMaxListeners
() – Returns the current max listener value for the EventEmitter
which is either
+set by emitter.setMaxListeners(n)
or defaults to {@link defaultMaxListeners}.
getMaxListeners() =>
listenerCount
(eventName) – Returns the number of listeners listening to the event named eventName
. string | symbol#
eventName
– The name of the event being listened for
+
listenerCount(eventName) =>
listeners
(eventName) – Returns a copy of the array of listeners for the event named eventName
.
+ +```js +server.on('connection', stream => { + console.log('someone connected!') +}) +console.log(util.inspect(server.listeners('connection'))) +// Prints: [ [Function] ] +``` + +
+eventName
string | symbol
listeners(eventName) =>
off
(eventName, listener) – Alias for emitter.removeListener()
. string | symbol#
eventName
off(eventName, listener) =>
on
(event, listener) – 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.
+ +```js +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. + +```js +const myEE = new EventEmitter() +myEE.on('foo', () => console.log('a')) +myEE.prependListener('foo', () => console.log('b')) +myEE.emit('foo') +// Prints: +// b +// a +``` + +
+event
"close"
listener
()
listener() =>
on(event, listener) =>
event
"drain"
listener
()
listener() =>
on(event, listener) =>
event
"error"
listener
(err) Error#
err
listener(err) =>
on(event, listener) =>
event
"finish"
listener
()
listener() =>
on(event, listener) =>
event
"pipe"
on(event, listener) =>
event
"unpipe"
on(event, listener) =>
event
string | symbol
listener
(args) any []#
args
listener(args) =>
on(event, listener) =>
once
(event, listener) – Adds a one-timelistener
function for the event named eventName
. The
+next time eventName
is triggered, this listener is removed and then invoked.
+ +```js +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. + +```js +const myEE = new EventEmitter() +myEE.once('foo', () => console.log('a')) +myEE.prependOnceListener('foo', () => console.log('b')) +myEE.emit('foo') +// Prints: +// b +// a +``` + +
+event
"close"
listener
()
listener() =>
once(event, listener) =>
event
"drain"
listener
()
listener() =>
once(event, listener) =>
event
"error"
listener
(err) Error#
err
listener(err) =>
once(event, listener) =>
event
"finish"
listener
()
listener() =>
once(event, listener) =>
event
"pipe"
once(event, listener) =>
event
"unpipe"
once(event, listener) =>
event
string | symbol
listener
(args) any []#
args
listener(args) =>
once(event, listener) =>
pipe
(destination, { end }) { #
options
pipe<T extends WritableStream<T>>(destination, { end }) =>
prependListener
(event, listener) – 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.
+ +```js +server.prependListener('connection', stream => { + console.log('someone connected!') +}) +``` + +Returns a reference to the `EventEmitter`, so that calls can be chained. + +
+event
"close"
listener
()
listener() =>
prependListener(event, listener) =>
event
"drain"
listener
()
listener() =>
prependListener(event, listener) =>
event
"error"
listener
(err) Error#
err
listener(err) =>
prependListener(event, listener) =>
event
"finish"
listener
()
listener() =>
prependListener(event, listener) =>
event
"pipe"
prependListener(event, listener) =>
event
"unpipe"
prependListener(event, listener) =>
event
string | symbol
listener
(args) any []#
args
listener(args) =>
prependListener(event, listener) =>
prependOnceListener
(event, listener) – Adds a one-timelistener
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.
+ +```js +server.prependOnceListener('connection', stream => { + console.log('Ah, we have our first user!') +}) +``` + +Returns a reference to the `EventEmitter`, so that calls can be chained. + +
+event
"close"
listener
()
listener() =>
prependOnceListener(event, listener) =>
event
"drain"
listener
()
listener() =>
prependOnceListener(event, listener) =>
event
"error"
listener
(err) Error#
err
listener(err) =>
prependOnceListener(event, listener) =>
event
"finish"
listener
()
listener() =>
prependOnceListener(event, listener) =>
event
"pipe"
prependOnceListener(event, listener) =>
event
"unpipe"
prependOnceListener(event, listener) =>
event
string | symbol
listener
(args) any []#
args
listener(args) =>
prependOnceListener(event, listener) =>
rawListeners
(eventName) – Returns a copy of the array of listeners for the event named eventName
,
+including any wrappers (such as those created by .once()
).
+ +```js +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') +``` + +
+eventName
string | symbol
rawListeners(eventName) =>
removeAllListeners
(event) – 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. + +
+event
string | symbol
removeAllListeners(event) =>
removeListener
(event, listener) – Removes the specified listener
from the listener array for the event namedeventName
.
+ +```js +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. + +```js +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 indices 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: + +```js +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. + +
+event
"close"
listener
()
listener() =>
removeListener(event, listener) =>
event
"drain"
listener
()
listener() =>
removeListener(event, listener) =>
event
"error"
listener
(err) Error#
err
listener(err) =>
removeListener(event, listener) =>
event
"finish"
listener
()
listener() =>
removeListener(event, listener) =>
event
"pipe"
removeListener(event, listener) =>
event
"unpipe"
removeListener(event, listener) =>
event
string | symbol
listener
(args) any []#
args
listener(args) =>
removeListener(event, listener) =>
setDefaultEncoding
(encoding) – The writable.setDefaultEncoding()
method sets the default encoding
for a Writable
stream. #
encoding
– The new default encoding
+
setDefaultEncoding(encoding) =>
setMaxListeners
(n) – By default EventEmitter
s 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 toInfinity
(or 0
) to indicate an unlimited number of listeners.
+ +Returns a reference to the `EventEmitter`, so that calls can be chained. + +
+n
number
setMaxListeners(n) =>
uncork
() – The writable.uncork()
method flushes all data buffered since {@link cork} was called.
+ +When using `writable.cork()` and `writable.uncork()` to manage the buffering +of writes to a stream, it is recommended that calls to `writable.uncork()` be +deferred using `process.nextTick()`. Doing so allows batching of all`writable.write()` calls that occur within a given Node.js event loop phase. + +```js +stream.cork() +stream.write('some ') +stream.write('data ') +process.nextTick(() => stream.uncork()) +``` + +If the `writable.cork()` method is called multiple times on a stream, the +same number of calls to `writable.uncork()` must be called to flush the buffered +data. + +```js +stream.cork() +stream.write('some ') +stream.cork() +stream.write('data ') +process.nextTick(() => { + stream.uncork() + // The data will not be flushed until uncork() is called a second time. + stream.uncork() +}) +``` + +See also: `writable.cork()`. + +
+uncork() =>
write
(chunk, callback) – The writable.write()
method writes some data to the stream, and calls the
+supplied callback
once the data has been fully handled. If an error
+occurs, the callback
will be called with the error as its
+first argument. The callback
is called asynchronously and before 'error'
is
+emitted.
+ +The return value is `true` if the internal buffer is less than the`highWaterMark` configured when the stream was created after admitting `chunk`. +If `false` is returned, further attempts to write data to the stream should +stop until the `'drain'` event is emitted. + +While a stream is not draining, calls to `write()` will buffer `chunk`, and +return false. Once all currently buffered chunks are drained (accepted for +delivery by the operating system), the `'drain'` event will be emitted. +It is recommended that once `write()` returns false, no more chunks be written +until the `'drain'` event is emitted. While calling `write()` on a stream that +is not draining is allowed, Node.js will buffer all written chunks until +maximum memory usage occurs, at which point it will abort unconditionally. +Even before it aborts, high memory usage will cause poor garbage collector +performance and high RSS (which is not typically released back to the system, +even after the memory is no longer required). Since TCP sockets may never +drain if the remote peer does not read the data, writing a socket that is +not draining may lead to a remotely exploitable vulnerability. + +Writing data while the stream is not draining is particularly +problematic for a `Transform`, because the `Transform` streams are paused +by default until they are piped or a `'data'` or `'readable'` event handler +is added. + +If the data to be written can be generated or fetched on demand, it is +recommended to encapsulate the logic into a `Readable` and use {@link pipe}. However, if calling `write()` is preferred, it is +possible to respect backpressure and avoid memory issues using the `'drain'` event: + +```js +function write(data, cb) { + if (!stream.write(data)) { + stream.once('drain', cb) + } else { + process.nextTick(cb) + } +} + +// Wait for cb to be called before doing any other write. +write('hello', () => { + console.log('Write completed, do more writes now.') +}) +``` + +A `Writable` stream in object mode will always ignore the `encoding` argument. + +
+chunk
– Optional data to write. For streams not operating in object mode, chunk
must be a string, Buffer
or Uint8Array
. For object mode streams, chunk
may be any
+JavaScript value other than null
.any
callback
(error) undefined | #
error
null
| Error
callback(error) =>
write(chunk, callback) =>
chunk
any
encoding
callback
(error) undefined | #
error
null
| Error
callback(error) =>
write(chunk, encoding, callback) =>
getEventListeners
(emitter, name) – Returns a copy of the array of listeners for the event named eventName
.
+ +For `EventEmitter`s this behaves exactly the same as calling `.listeners` on +the emitter. + +For `EventTarget`s this is the only way to get the event listeners for the +event target. This is useful for debugging and diagnostic purposes. + +```js +const { getEventListeners, EventEmitter } = require('events') + +{ + const ee = new EventEmitter() + const listener = () => console.log('Events are fun') + ee.on('foo', listener) + getEventListeners(ee, 'foo') // [listener] +} +{ + const et = new EventTarget() + const listener = () => console.log('Events are fun') + et.addEventListener('foo', listener) + getEventListeners(et, 'foo') // [listener] +} +``` + +
+emitter
name
string | symbol
getEventListeners(emitter, name) =>
listenerCount
(emitter, eventName) – A class method that returns the number of listeners for the given eventName
registered on the given emitter
.
+ +```js +const { EventEmitter, listenerCount } = require('events') +const myEmitter = new EventEmitter() +myEmitter.on('event', () => {}) +myEmitter.on('event', () => {}) +console.log(listenerCount(myEmitter, 'event')) +// Prints: 2 +``` + +
+emitter
– The emitter to queryeventName
– The event name
+string | symbol
listenerCount(emitter, eventName) =>
on
(emitter, eventName, options) – ```js
+const { on, EventEmitter } = require('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: + +```js +const { on, EventEmitter } = require('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()); +```` + +
+emitter
eventName
– The name of the event being listened forstring
options
on(emitter, eventName, options) =>
once
(emitter, eventName, options) – 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](https://dom.spec.whatwg.org/#interface-eventtarget) interface, which has no special`'error'` event +semantics and does not listen to the `'error'` event. + +```js +const { once, EventEmitter } = require('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.log('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: + +```js +const { EventEmitter, once } = require('events') + +const ee = new EventEmitter() + +once(ee, 'error') + .then(([err]) => console.log('ok', err.message)) + .catch(err => console.log('error', err.message)) + +ee.emit('error', new Error('boom')) + +// Prints: ok boom +``` + +An `AbortSignal` can be used to cancel waiting for the event: + +```js +const { EventEmitter, once } = require('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() // Abort waiting for the event +ee.emit('foo') // Prints: Waiting for the event was canceled! +``` + +
+emitter
eventName
string | symbol
options
once(emitter, eventName, options) =>
emitter
eventName
string
options
once(emitter, eventName, options) =>
setMaxListeners
(n, eventTargets) – By default EventEmitter
s 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 EventEmitter.setMaxListeners()
method allows the default limit to be
+modified (if eventTargets is empty) or modify the limit specified in every EventTarget
| EventEmitter
passed as arguments.
+The value can be set toInfinity
(or 0
) to indicate an unlimited number of listeners.
+ +```js +EventEmitter.setMaxListeners(20) +// Equivalent to +EventEmitter.defaultMaxListeners = 20 + +const eventTarget = new EventTarget() +// Only way to increase limit for `EventTarget` instances +// as these doesn't expose its own `setMaxListeners` method +EventEmitter.setMaxListeners(20, eventTarget) +``` + +
+n
number
eventTargets
setMaxListeners(n, eventTargets) =>
DuplexOptions
AbortSignal#
src/.fastpm/-/@types/node@17.0.45/events.d.ts#L317 signal
– When provided the corresponding AbortController
can be used to cancel an asynchronous action.
construct(this, callback) =>
destroy
(this, error, callback) #
error
null
| Error
destroy(this, error, callback) =>
final
(this, callback)
final(this, callback) =>
write
(this, chunk, encoding, callback) write(this, chunk, encoding, callback) =>
writev
(this, chunks, callback) { #
chunks
callback
(error) #
error
null
| Error
callback(error) =>
writev(this, chunks, callback) =>
FinishedOptions
AbortSignal#
src/.fastpm/-/@types/node@17.0.45/events.d.ts#L317 signal
– When provided the corresponding AbortController
can be used to cancel an asynchronous action.
Pipe
close() => #
close
()
void
hasRef
()
hasRef() =>
ref
()
ref() =>
unref
()
unref() =>
PipelineOptions
ReadableOptions
AbortSignal#
src/.fastpm/-/@types/node@17.0.45/events.d.ts#L317 signal
– When provided the corresponding AbortController
can be used to cancel an asynchronous action.
construct(this, callback) =>
destroy
(this, error, callback) #
error
null
| Error
destroy(this, error, callback) =>
StreamOptions
AbortSignal#
src/.fastpm/-/@types/node@17.0.45/events.d.ts#L317 signal
– When provided the corresponding AbortController
can be used to cancel an asynchronous action.
construct(this, callback) =>
destroy
(this, error, callback) #
error
null
| Error
destroy(this, error, callback) =>
TransformOptions
AbortSignal#
src/.fastpm/-/@types/node@17.0.45/events.d.ts#L317 signal
– When provided the corresponding AbortController
can be used to cancel an asynchronous action.
construct(this, callback) =>
destroy
(this, error, callback) #
error
null
| Error
destroy(this, error, callback) =>
final
(this, callback)
final(this, callback) =>
flush
(this, callback) #
callback
flush(this, callback) =>
transform
(this, chunk, encoding, callback) write
(this, chunk, encoding, callback) write(this, chunk, encoding, callback) =>
writev
(this, chunks, callback) { #
chunks
callback
(error) #
error
null
| Error
callback(error) =>
writev(this, chunks, callback) =>
WritableOptions
AbortSignal#
src/.fastpm/-/@types/node@17.0.45/events.d.ts#L317 signal
– When provided the corresponding AbortController
can be used to cancel an asynchronous action.
construct(this, callback) =>
destroy
(this, error, callback) #
error
null
| Error
destroy(this, error, callback) =>
final
(this, callback)
final(this, callback) =>
write
(this, chunk, encoding, callback) write(this, chunk, encoding, callback) =>
writev
(this, chunks, callback) { #
chunks
callback
(error) #
error
null
| Error
callback(error) =>
writev(this, chunks, callback) =>
PipelineCallback
S extends PipelineDestinationPromiseFunction<any, inferred> ? NodeJS.ErrnoException | P (err, value) => # (err, value)
#
err
null
#
value
void
NodeJS.ErrnoException | #
err
null
(err) =>
PipelineDestination
S extends PipelineTransformSource<inferred> ? NodeJS.WritableStream | PipelineDestinationIterableFunction<ST> | PipelineDestinationPromiseFunction<ST, P> : never
PipelineDestinationIterableFunction
PipelineDestinationPromiseFunction
PipelinePromise
S extends PipelineDestinationPromiseFunction<any, inferred> ? Promise<P> : Promise<void>
PipelineSource
Iterable<T> | AsyncIterable<T> | NodeJS.ReadableStream | PipelineSourceFunction<T>
PipelineSourceFunction
PipelineTransform
NodeJS.ReadWriteStream | # (source)
(source) =>
PipelineTransformSource
PipelineSource<T> | PipelineTransform<any, T>
TransformCallback
consumers
typeof streamConsumers
promises
typeof streamPromises
addAbortSignal
(signal, stream) – Attaches an AbortSignal to a readable or writeable stream. This lets code
+control stream destruction using an AbortController
.
+ +Calling `abort` on the `AbortController` corresponding to the passed`AbortSignal` will behave the same way as calling `.destroy(new AbortError())`on the stream. + +```js +const fs = require('fs') + +const controller = new AbortController() +const read = addAbortSignal( + controller.signal, + fs.createReadStream('object.json') +) +// Later, abort the operation closing the stream +controller.abort() +``` + +Or using an `AbortSignal` with a readable stream as an async iterable: + +```js +const controller = new AbortController() +setTimeout(() => controller.abort(), 10_000) // set a timeout +const stream = addAbortSignal( + controller.signal, + fs.createReadStream('object.json') +) +;(async () => { + try { + for await (const chunk of stream) { + await process(chunk) + } + } catch (e) { + if (e.name === 'AbortError') { + // The operation was cancelled + } else { + throw e + } + } +})() +``` + +
+signal
– A signal representing possible cancellationAbortSignal
stream
– a stream to attach a signal to
+addAbortSignal<T extends Stream<T>>(signal, stream) =>
finished
(stream, options, callback) – A function to get notified when a stream is no longer readable, writable
+or has experienced an error or a premature close event.
+ +```js +const { finished } = require('stream') + +const rs = fs.createReadStream('archive.tar') + +finished(rs, err => { + if (err) { + console.error('Stream failed.', err) + } else { + console.log('Stream is done reading.') + } +}) + +rs.resume() // Drain the stream. +``` + +Especially useful in error handling scenarios where a stream is destroyed +prematurely (like an aborted HTTP request), and will not emit `'end'`or `'finish'`. + +The `finished` API provides promise version: + +```js +const { finished } = require('stream/promises') + +const rs = fs.createReadStream('archive.tar') + +async function run() { + await finished(rs) + console.log('Stream is done reading.') +} + +run().catch(console.error) +rs.resume() // Drain the stream. +``` + +`stream.finished()` leaves dangling event listeners (in particular`'error'`, `'end'`, `'finish'` and `'close'`) after `callback` has been +invoked. The reason for this is so that unexpected `'error'` events (due to +incorrect stream implementations) do not cause unexpected crashes. +If this is unwanted behavior then the returned cleanup function needs to be +invoked in the callback: + +```js +const cleanup = finished(rs, err => { + cleanup() + // ... +}) +``` + +
+stream
– A readable and/or writable stream.options
callback
(err) #
err
null
| ErrnoException
callback(err) =>
finished(stream, options, callback) =>
+ +```js +const { finished } = require('stream') + +const rs = fs.createReadStream('archive.tar') + +finished(rs, err => { + if (err) { + console.error('Stream failed.', err) + } else { + console.log('Stream is done reading.') + } +}) + +rs.resume() // Drain the stream. +``` + +Especially useful in error handling scenarios where a stream is destroyed +prematurely (like an aborted HTTP request), and will not emit `'end'`or `'finish'`. + +The `finished` API provides promise version: + +```js +const { finished } = require('stream/promises') + +const rs = fs.createReadStream('archive.tar') + +async function run() { + await finished(rs) + console.log('Stream is done reading.') +} + +run().catch(console.error) +rs.resume() // Drain the stream. +``` + +`stream.finished()` leaves dangling event listeners (in particular`'error'`, `'end'`, `'finish'` and `'close'`) after `callback` has been +invoked. The reason for this is so that unexpected `'error'` events (due to +incorrect stream implementations) do not cause unexpected crashes. +If this is unwanted behavior then the returned cleanup function needs to be +invoked in the callback: + +```js +const cleanup = finished(rs, err => { + cleanup() + // ... +}) +``` + +
+() =>
stream
callback
(err) #
err
null
| ErrnoException
callback(err) =>
finished(stream, callback) =>
() =>
pipeline
(source, destination, callback) – A module method to pipe between streams and generators forwarding errors and
+properly cleaning up and provide a callback when the pipeline is complete.
+ +```js +const { pipeline } = require('stream') +const fs = require('fs') +const zlib = require('zlib') + +// Use the pipeline API to easily pipe a series of streams +// together and get notified when the pipeline is fully done. + +// A pipeline to gzip a potentially huge tar file efficiently: + +pipeline( + fs.createReadStream('archive.tar'), + zlib.createGzip(), + fs.createWriteStream('archive.tar.gz'), + err => { + if (err) { + console.error('Pipeline failed.', err) + } else { + console.log('Pipeline succeeded.') + } + } +) +``` + +The `pipeline` API provides a promise version, which can also +receive an options argument as the last parameter with a`signal` `AbortSignal` property. When the signal is aborted,`destroy` will be called on the underlying pipeline, with +an`AbortError`. + +```js +const { pipeline } = require('stream/promises') + +async function run() { + await pipeline( + fs.createReadStream('archive.tar'), + zlib.createGzip(), + fs.createWriteStream('archive.tar.gz') + ) + console.log('Pipeline succeeded.') +} + +run().catch(console.error) +``` + +To use an `AbortSignal`, pass it inside an options object, +as the last argument: + +```js +const { pipeline } = require('stream/promises') + +async function run() { + const ac = new AbortController() + const signal = ac.signal + + setTimeout(() => ac.abort(), 1) + await pipeline( + fs.createReadStream('archive.tar'), + zlib.createGzip(), + fs.createWriteStream('archive.tar.gz'), + { signal } + ) +} + +run().catch(console.error) // AbortError +``` + +The `pipeline` API also supports async generators: + +```js +const { pipeline } = require('stream/promises') +const fs = require('fs') + +async function run() { + await pipeline( + fs.createReadStream('lowercase.txt'), + async function*(source, signal) { + source.setEncoding('utf8') // Work with strings rather than `Buffer`s. + for await (const chunk of source) { + yield await processChunk(chunk, { signal }) + } + }, + fs.createWriteStream('uppercase.txt') + ) + console.log('Pipeline succeeded.') +} + +run().catch(console.error) +``` + +Remember to handle the `signal` argument passed into the async generator. +Especially in the case where the async generator is the source for the +pipeline (i.e. first argument) or the pipeline will never complete. + +```js +const { pipeline } = require('stream/promises') +const fs = require('fs') + +async function run() { + await pipeline( + async function*(signal) { + await someLongRunningfn({ signal }) + yield 'asd' + }, + fs.createWriteStream('uppercase.txt') + ) + console.log('Pipeline succeeded.') +} + +run().catch(console.error) +``` + +`stream.pipeline()` will call `stream.destroy(err)` on all streams except: + +- `Readable` streams which have emitted `'end'` or `'close'`. +- `Writable` streams which have emitted `'finish'` or `'close'`. + +`stream.pipeline()` leaves dangling event listeners on the streams +after the `callback` has been invoked. In the case of reuse of streams after +failure, this can cause event listener leaks and swallowed errors. + +
+source
destination
callback
– Called when the pipeline is fully done.
+pipeline<A extends PipelineSource<any>, B>(source, destination, callback) =>
source
transform1
destination
callback
pipeline<A extends PipelineSource<any>, T1 extends PipelineTransform<A, any>, B>(source, transform1, destination, callback) =>
source
transform1
transform2
destination
callback
pipeline<A extends PipelineSource<any>, T1 extends PipelineTransform<A, any>, T2 extends PipelineTransform<T1, any>, B>(source, transform1, transform2, destination, callback) =>
source
transform1
transform2
transform3
destination
callback
pipeline<A extends PipelineSource<any>, T1 extends PipelineTransform<A, any>, T2 extends PipelineTransform<T1, any>, T3 extends PipelineTransform<T2, any>, B>(source, transform1, transform2, transform3, destination, callback) =>
source
transform1
transform2
transform3
transform4
destination
callback
pipeline<A extends PipelineSource<any>, T1 extends PipelineTransform<A, any>, T2 extends PipelineTransform<T1, any>, T3 extends PipelineTransform<T2, any>, T4 extends PipelineTransform<T3, any>, B>(source, transform1, transform2, transform3, transform4, destination, callback) =>
streams
readonly ReadableStream | WritableStream | ReadWriteStream []
callback
(err) #
err
null
| ErrnoException
callback(err) =>
pipeline(streams, callback) =>
stream1
stream2
streams
WritableStream | ReadWriteStream | (err) => # (err)
#
err
null
| ErrnoExceptionvoid
pipeline(stream1, stream2, streams) =>
InlineFunctions
OutputQuoteStyle
Agent
– An Agent
is responsible for managing connection persistence
+and reuse for HTTP clients. It maintains a queue of pending requests
+for a given host and port, reusing a single socket connection for each
+until the queue is empty, at which time the socket is either destroyed
+or put into a pool where it is kept to be used again for requests to the
+same host and port. Whether it is destroyed or pooled depends on thekeepAlive
option
.+ +Pooled connections have TCP Keep-Alive enabled for them, but servers may +still close idle connections, in which case they will be removed from the +pool and a new connection will be made when a new HTTP request is made for +that host and port. Servers may also refuse to allow multiple requests +over the same connection, in which case the connection will have to be +remade for every request and cannot be pooled. The `Agent` will still make +the requests to that server, but each one will occur over a new connection. + +When a connection is closed by the client or the server, it is removed +from the pool. Any unused sockets in the pool will be unrefed so as not +to keep the Node.js process running when there are no outstanding requests. +(see `socket.unref()`). + +It is good practice, to `destroy()` an `Agent` instance when it is no +longer in use, because unused sockets consume OS resources. + +Sockets are removed from an agent when the socket emits either +a `'close'` event or an `'agentRemove'` event. When intending to keep one +HTTP request open for a long time without keeping it in the agent, something +like the following may be done: + +```js +http.get(options, res => { + // Do stuff +}).on('socket', socket => { + socket.emit('agentRemove') +}) +``` + +An agent may also be used for an individual request. By providing`{agent: false}` as an option to the `http.get()` or `http.request()`functions, a one-time use `Agent` with default options +will be used +for the client connection. + +`agent:false`: + +```js +http.get({ + hostname: 'localhost', + port: 80, + path: '/', + agent: false, // Create a new agent just for this one request +}, res => { + // Do stuff with response +}) +``` + +
+ ReadOnlyDict<Socket []>
+
+Sockets in the `freeSockets` list will be automatically destroyed and
+removed from the array on `'timeout'`.
+
+ number number number ReadOnlyDict<Socket []>
+
+It is usually not necessary to do this. However, if using an
+agent with `keepAlive` enabled, then it is best to explicitly shut down
+the agent when it is no longer needed. Otherwise,
+sockets might stay open for quite a long time before the server
+terminates them.
+
+ destroy() => #
src/.fastpm/-/@types/node@17.0.45/http.d.ts#L1096 freeSockets
– An object which contains arrays of sockets currently awaiting use by
+the agent when keepAlive
is enabled. Do not modify.#
src/.fastpm/-/@types/node@17.0.45/http.d.ts#L1075 maxFreeSockets
– By default set to 256. For agents with keepAlive
enabled, this
+sets the maximum number of sockets that will be left open in the free
+state.#
src/.fastpm/-/@types/node@17.0.45/http.d.ts#L1081 maxSockets
– By default set to Infinity
. Determines how many concurrent sockets the agent
+can have open per origin. Origin is the returned value of agent.getName()
.#
src/.fastpm/-/@types/node@17.0.45/http.d.ts#L1087 maxTotalSockets
– By default set to Infinity
. Determines how many concurrent sockets the agent
+can have open. Unlike maxSockets
, this parameter applies across all origins.#
src/.fastpm/-/@types/node@17.0.45/http.d.ts#L1108 requests
– An object which contains queues of requests that have not yet been assigned to
+sockets. Do not modify.#
src/.fastpm/-/@types/node@17.0.45/http.d.ts#L1102 sockets
– An object which contains arrays of sockets currently in use by the
+agent. Do not modify.#
src/.fastpm/-/@types/node@17.0.45/http.d.ts#L1120 destroy
() – Destroy any sockets that are currently in use by the agent.
void
Blob
– A Blob
encapsulates immutable, raw data that can be safely shared across
+multiple worker threads.
+
+{ArrayBuffer}, {TypedArray}, {DataView}, and {Buffer} sources are copied into
+the 'Blob' and can therefore be safely modified after the 'Blob' is created.
+
+String sources are also copied into the `Blob`.
+
+ Blob | BinaryLike [] number arrayBuffer() => #
src/.fastpm/-/@types/node@17.0.45/buffer.d.ts#L138 constructor
(sources, options) – Creates a new Blob
object containing a concatenation of the given sources.
#
new Blob
() – Creates a new Blob
object containing a concatenation of the given sources.
#
sources
#
options
#
src/.fastpm/-/@types/node@17.0.45/buffer.d.ts#L124 size
– The total size of the Blob
in bytes.#
src/.fastpm/-/@types/node@17.0.45/buffer.d.ts#L144 arrayBuffer
() – Returns a promise that fulfills with an ArrayBuffer containing a copy of
+the Blob
data.
Promise<ArrayBuffer>
slice
(start, end, type) – Creates and returns a new Blob
containing a subset of this Blob
objects
+data. The original Blob
is not altered.stream
() – Returns a new ReadableStream
that allows the content of the Blob
to be read.
stream() =>
text
() – Returns a promise that fulfills with the contents of the Blob
decoded as a
+UTF-8 string.
text() =>
ClientRequest
– This object is created internally and returned from {@link request}. It
+represents an in-progress request whose header has already been queued. The
+header is still mutable using the setHeader(name, value)
,getHeader(name)
, removeHeader(name)
API. The actual header will
+be sent along with the first data chunk or when calling request.end()
.+ +To get the response, add a listener for `'response'` to the request object.`'response'` will be emitted from the request object when the response +headers have been received. The `'response'` event is executed with one +argument which is an instance of {@link IncomingMessage}. + +During the `'response'` event, one can add listeners to the +response object; particularly to listen for the `'data'` event. + +If no `'response'` handler is added, then the response will be +entirely discarded. However, if a `'response'` event handler is added, +then the data from the response object **must** be consumed, either by +calling `response.read()` whenever there is a `'readable'` event, or +by adding a `'data'` handler, or by calling the `.resume()` method. +Until the data is consumed, the `'end'` event will not fire. Also, until +the data is read it will consume memory that can eventually lead to a +'process out of memory' error. + +For backward compatibility, `res` will only emit `'error'` if there is an`'error'` listener registered. + +Node.js does not check whether Content-Length and the length of the +body which has been transmitted are equal or not. + +
+ #
src/.fastpm/-/@types/node@17.0.45/http.d.ts#L634 constructor
(url, cb)
aborted
– The request.aborted
property will be true
if the request has
+been aborted.boolean
chunkedEncoding
boolean
connection
– Aliases of outgoingMessage.socket
null
| Socket
destroyed
– Is true
after writable.destroy()
has been called.boolean
finished
boolean
headersSent
– Read-only. true
if the headers were sent, otherwise false
.boolean
host
– The request host.string
maxHeadersCount
– Limits maximum response headers count. If set to 0, no limit will be applied.number
method
– The request method.string
path
– The request path.string
protocol
– The request protocol.string
req
reusedSocket
– Whether the request is send through a reused socket.boolean
sendDate
boolean
shouldKeepAlive
boolean
socket
– Reference to the underlying socket. Usually, users will not want to access
+this property.null
| Socket
+ +After calling `outgoingMessage.end()`, this property will be nulled. + +
+useChunkedEncodingByDefault
boolean
writable
– Is true
if it is safe to call writable.write()
, which means
+the stream has not been destroyed, errored or ended.boolean
writableCorked
– Number of times writable.uncork()
needs to be
+called in order to fully uncork the stream.number
writableEnded
– Is true
after writable.end()
has been called. This property
+does not indicate whether the data has been flushed, for this use writable.writableFinished
instead.boolean
writableFinished
– Is set to true
immediately before the 'finish'
event is emitted.boolean
writableHighWaterMark
– Return the value of highWaterMark
passed when creating this Writable
.number
writableLength
– This property contains the number of bytes (or objects) in the queue
+ready to be written. The value provides introspection data regarding
+the status of the highWaterMark
.number
writableObjectMode
– Getter for the property objectMode
of a given Writable
stream.boolean
captureRejectionSymbol
typeof captureRejectionSymbol
captureRejections
– Sets or gets the default captureRejection value for all emitters.boolean
defaultMaxListeners
number
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.typeof errorMonitor
+ +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. + +
+_construct
(callback)
_construct(callback) =>
_destroy
(error, callback) #
error
null
| Error
_destroy(error, callback) =>
_final
(callback)
_final(callback) =>
_write
(chunk, encoding, callback) _write(chunk, encoding, callback) =>
_writev
(chunks, callback) { #
chunks
callback
(error) #
error
null
| Error
callback(error) =>
_writev(chunks, callback) =>
abort
() – Marks the request as aborting. Calling this will cause remaining data
+in the response to be dropped and the socket to be destroyed.
abort() =>
addListener
(event, listener) addListener(event, listener) =>
event
"connect"
listener
(response, socket, head) #
response
listener(response, socket, head) =>
addListener(event, listener) =>
event
"continue"
listener
()
listener() =>
addListener(event, listener) =>
event
"information"
listener
(info) #
info
listener(info) =>
addListener(event, listener) =>
event
"response"
listener
(response) #
response
listener(response) =>
addListener(event, listener) =>
event
"socket"
addListener(event, listener) =>
event
"timeout"
listener
()
listener() =>
addListener(event, listener) =>
event
"upgrade"
listener
(response, socket, head) #
response
listener(response, socket, head) =>
addListener(event, listener) =>
event
"close"
listener
()
listener() =>
addListener(event, listener) =>
event
"drain"
listener
()
listener() =>
addListener(event, listener) =>
event
"error"
listener
(err) Error#
err
listener(err) =>
addListener(event, listener) =>
event
"finish"
listener
()
listener() =>
addListener(event, listener) =>
event
"pipe"
addListener(event, listener) =>
event
"unpipe"
addListener(event, listener) =>
event
string | symbol
listener
(args) any []#
args
listener(args) =>
addListener(event, listener) =>
addTrailers
(headers) – Adds HTTP trailers (headers but at the end of the message) to the message.
+ +Trailers are **only** be emitted if the message is chunked encoded. If not, +the trailer will be silently discarded. + +HTTP requires the `Trailer` header to be sent to emit trailers, +with a list of header fields in its value, e.g. + +```js +message.writeHead(200, { 'Content-Type': 'text/plain', Trailer: 'Content-MD5' }) +message.write(fileData) +message.addTrailers({ 'Content-MD5': '7895bf4b8828b55ceaf47747b4bca667' }) +message.end() +``` + +Attempting to set a header field name or value that contains invalid characters +will result in a `TypeError` being thrown. + +
+headers
OutgoingHttpHeaders | readonly [ string, string ] []
addTrailers(headers) =>
cork
() – The writable.cork()
method forces all written data to be buffered in memory.
+The buffered data will be flushed when either the {@link uncork} or {@link end} methods are called.
+ +The primary intent of `writable.cork()` is to accommodate a situation in which +several small chunks are written to the stream in rapid succession. Instead of +immediately forwarding them to the underlying destination, `writable.cork()`buffers all the chunks until `writable.uncork()` is called, which will pass them +all to `writable._writev()`, if present. This prevents a head-of-line blocking +situation where data is being buffered while waiting for the first small chunk +to be processed. However, use of `writable.cork()` without implementing`writable._writev()` may have an adverse effect on throughput. + +See also: `writable.uncork()`, `writable._writev()`. + +
+cork() =>
destroy
(error) – Destroy the stream. Optionally emit an 'error'
event, and emit a 'close'
event (unless emitClose
is set to false
). After this call, the writable
+stream has ended and subsequent calls to write()
or end()
will result in
+an ERR_STREAM_DESTROYED
error.
+This is a destructive and immediate way to destroy a stream. Previous calls towrite()
may not have drained, and may trigger an ERR_STREAM_DESTROYED
error.
+Use end()
instead of destroy if data should flush before close, or wait for
+the 'drain'
event before destroying the stream.
+ +Once `destroy()` has been called any further calls will be a no-op and no +further errors except from `_destroy()` may be emitted as `'error'`. + +Implementors should not override this method, +but instead implement `writable._destroy()`. + +
+error
– Optional, an error to emit with 'error'
event.
+Error
destroy(error) =>
emit
(event) – Synchronously calls each of the listeners registered for the event namedeventName
, in the order they were registered, passing the supplied arguments
+to each.
+ +Returns `true` if the event had listeners, `false` otherwise. + +```js +const EventEmitter = require('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 +``` + +
+event
"close"
emit(event) =>
event
"drain"
emit(event) =>
event
"error"
err
Error
emit(event, err) =>
event
"finish"
emit(event) =>
event
"pipe"
src
emit(event, src) =>
event
"unpipe"
src
emit(event, src) =>
event
string | symbol
args
any []
emit(event, args) =>
end
(cb) – Calling the writable.end()
method signals that no more data will be written
+to the Writable
. The optional chunk
and encoding
arguments allow one
+final additional chunk of data to be written immediately before closing the
+stream.
+ +Calling the {@link write} method after calling {@link end} will raise an error. + +```js +// Write 'hello, ' and then end with 'world!'. +const fs = require('fs') +const file = fs.createWriteStream('example.txt') +file.write('hello, ') +file.end('world!') +// Writing more now is not allowed! +``` + +
+cb
()
cb() =>
end(cb) =>
chunk
any
cb
()
cb() =>
end(chunk, cb) =>
chunk
any
encoding
cb
()
cb() =>
end(chunk, encoding, cb) =>
eventNames
() – Returns an array listing the events for which the emitter has registered
+listeners. The values in the array are strings or Symbol
s.
+ +```js +const EventEmitter = require('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) ] +``` + +
+eventNames() =>
flushHeaders
() – Compulsorily flushes the message headers
+ +For efficiency reason, Node.js normally buffers the message headers +until `outgoingMessage.end()` is called or the first chunk of message data +is written. It then tries to pack the headers and data into a single TCP +packet. + +It is usually desired (it saves a TCP round-trip), but not when the first +data is not sent until possibly much later. `outgoingMessage.flushHeaders()`bypasses the optimization and kickstarts the request. + +
+flushHeaders() =>
getHeader
(name) – Gets the value of HTTP header with the given name. If such a name doesn't
+exist in message, it will be undefined
. string#
name
– Name of header
+
getHeader(name) =>
getHeaderNames
() – Returns an array of names of headers of the outgoing outgoingMessage. All
+names are lowercase.
getHeaderNames() =>
getHeaders
() – Returns a shallow copy of the current outgoing headers. Since a shallow
+copy is used, array values may be mutated without additional calls to
+various header-related HTTP module methods. The keys of the returned
+object are the header names and the values are the respective header
+values. All header names are lowercase.
+ +The object returned by the `outgoingMessage.getHeaders()` method does +not prototypically inherit from the JavaScript Object. This means that +typical Object methods such as `obj.toString()`, `obj.hasOwnProperty()`, +and others are not defined and will not work. + +```js +outgoingMessage.setHeader('Foo', 'bar') +outgoingMessage.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']) + +const headers = outgoingMessage.getHeaders() +// headers === { foo: 'bar', 'set-cookie': ['foo=bar', 'bar=baz'] } +``` + +
+getHeaders() =>
getMaxListeners
() – Returns the current max listener value for the EventEmitter
which is either
+set by emitter.setMaxListeners(n)
or defaults to {@link defaultMaxListeners}.
getMaxListeners() =>
getRawHeaderNames
() – Returns an array containing the unique names of the current outgoing raw
+headers. Header names are returned with their exact casing being set.
+ +```js +request.setHeader('Foo', 'bar') +request.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']) + +const headerNames = request.getRawHeaderNames() +// headerNames === ['Foo', 'Set-Cookie'] +``` + +
+getRawHeaderNames() =>
hasHeader
(name) – Returns true
if the header identified by name
is currently set in the
+outgoing headers. The header name is case-insensitive.
+ +```js +const hasContentType = outgoingMessage.hasHeader('content-type') +``` + +
+name
string
hasHeader(name) =>
listenerCount
(eventName) – Returns the number of listeners listening to the event named eventName
. string | symbol#
eventName
– The name of the event being listened for
+
listenerCount(eventName) =>
listeners
(eventName) – Returns a copy of the array of listeners for the event named eventName
.
+ +```js +server.on('connection', stream => { + console.log('someone connected!') +}) +console.log(util.inspect(server.listeners('connection'))) +// Prints: [ [Function] ] +``` + +
+eventName
string | symbol
listeners(eventName) =>
off
(eventName, listener) – Alias for emitter.removeListener()
. string | symbol#
eventName
off(eventName, listener) =>
on
(event, listener) on(event, listener) =>
event
"connect"
listener
(response, socket, head) #
response
listener(response, socket, head) =>
on(event, listener) =>
event
"continue"
listener
()
listener() =>
on(event, listener) =>
event
"information"
listener
(info) #
info
listener(info) =>
on(event, listener) =>
event
"response"
listener
(response) #
response
listener(response) =>
on(event, listener) =>
event
"socket"
on(event, listener) =>
event
"timeout"
listener
()
listener() =>
on(event, listener) =>
event
"upgrade"
listener
(response, socket, head) #
response
listener(response, socket, head) =>
on(event, listener) =>
event
"close"
listener
()
listener() =>
on(event, listener) =>
event
"drain"
listener
()
listener() =>
on(event, listener) =>
event
"error"
listener
(err) Error#
err
listener(err) =>
on(event, listener) =>
event
"finish"
listener
()
listener() =>
on(event, listener) =>
event
"pipe"
on(event, listener) =>
event
"unpipe"
on(event, listener) =>
event
string | symbol
listener
(args) any []#
args
listener(args) =>
on(event, listener) =>
onSocket
(socket)
onSocket(socket) =>
once
(event, listener) once(event, listener) =>
event
"connect"
listener
(response, socket, head) #
response
listener(response, socket, head) =>
once(event, listener) =>
event
"continue"
listener
()
listener() =>
once(event, listener) =>
event
"information"
listener
(info) #
info
listener(info) =>
once(event, listener) =>
event
"response"
listener
(response) #
response
listener(response) =>
once(event, listener) =>
event
"socket"
once(event, listener) =>
event
"timeout"
listener
()
listener() =>
once(event, listener) =>
event
"upgrade"
listener
(response, socket, head) #
response
listener(response, socket, head) =>
once(event, listener) =>
event
"close"
listener
()
listener() =>
once(event, listener) =>
event
"drain"
listener
()
listener() =>
once(event, listener) =>
event
"error"
listener
(err) Error#
err
listener(err) =>
once(event, listener) =>
event
"finish"
listener
()
listener() =>
once(event, listener) =>
event
"pipe"
once(event, listener) =>
event
"unpipe"
once(event, listener) =>
event
string | symbol
listener
(args) any []#
args
listener(args) =>
once(event, listener) =>
pipe
(destination, { end }) { #
options
pipe<T extends WritableStream<T>>(destination, { end }) =>
prependListener
(event, listener) prependListener(event, listener) =>
event
"connect"
listener
(response, socket, head) #
response
listener(response, socket, head) =>
prependListener(event, listener) =>
event
"continue"
listener
()
listener() =>
prependListener(event, listener) =>
event
"information"
listener
(info) #
info
listener(info) =>
prependListener(event, listener) =>
event
"response"
listener
(response) #
response
listener(response) =>
prependListener(event, listener) =>
event
"socket"
prependListener(event, listener) =>
event
"timeout"
listener
()
listener() =>
prependListener(event, listener) =>
event
"upgrade"
listener
(response, socket, head) #
response
listener(response, socket, head) =>
prependListener(event, listener) =>
event
"close"
listener
()
listener() =>
prependListener(event, listener) =>
event
"drain"
listener
()
listener() =>
prependListener(event, listener) =>
event
"error"
listener
(err) Error#
err
listener(err) =>
prependListener(event, listener) =>
event
"finish"
listener
()
listener() =>
prependListener(event, listener) =>
event
"pipe"
prependListener(event, listener) =>
event
"unpipe"
prependListener(event, listener) =>
event
string | symbol
listener
(args) any []#
args
listener(args) =>
prependListener(event, listener) =>
prependOnceListener
(event, listener) prependOnceListener(event, listener) =>
event
"connect"
listener
(response, socket, head) #
response
listener(response, socket, head) =>
prependOnceListener(event, listener) =>
event
"continue"
listener
()
listener() =>
prependOnceListener(event, listener) =>
event
"information"
listener
(info) #
info
listener(info) =>
prependOnceListener(event, listener) =>
event
"response"
listener
(response) #
response
listener(response) =>
prependOnceListener(event, listener) =>
event
"socket"
prependOnceListener(event, listener) =>
event
"timeout"
listener
()
listener() =>
prependOnceListener(event, listener) =>
event
"upgrade"
listener
(response, socket, head) #
response
listener(response, socket, head) =>
prependOnceListener(event, listener) =>
event
"close"
listener
()
listener() =>
prependOnceListener(event, listener) =>
event
"drain"
listener
()
listener() =>
prependOnceListener(event, listener) =>
event
"error"
listener
(err) Error#
err
listener(err) =>
prependOnceListener(event, listener) =>
event
"finish"
listener
()
listener() =>
prependOnceListener(event, listener) =>
event
"pipe"
prependOnceListener(event, listener) =>
event
"unpipe"
prependOnceListener(event, listener) =>
event
string | symbol
listener
(args) any []#
args
listener(args) =>
prependOnceListener(event, listener) =>
rawListeners
(eventName) – Returns a copy of the array of listeners for the event named eventName
,
+including any wrappers (such as those created by .once()
).
+ +```js +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') +``` + +
+eventName
string | symbol
rawListeners(eventName) =>
removeAllListeners
(event) – 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. + +
+event
string | symbol
removeAllListeners(event) =>
removeHeader
(name) – Removes a header that is queued for implicit sending.
+ +```js +outgoingMessage.removeHeader('Content-Encoding') +``` + +
+name
string
removeHeader(name) =>
removeListener
(event, listener) – Removes the specified listener
from the listener array for the event namedeventName
.
+ +```js +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. + +```js +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 indices 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: + +```js +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. + +
+event
"close"
listener
()
listener() =>
removeListener(event, listener) =>
event
"drain"
listener
()
listener() =>
removeListener(event, listener) =>
event
"error"
listener
(err) Error#
err
listener(err) =>
removeListener(event, listener) =>
event
"finish"
listener
()
listener() =>
removeListener(event, listener) =>
event
"pipe"
removeListener(event, listener) =>
event
"unpipe"
removeListener(event, listener) =>
event
string | symbol
listener
(args) any []#
args
listener(args) =>
removeListener(event, listener) =>
setDefaultEncoding
(encoding) – The writable.setDefaultEncoding()
method sets the default encoding
for a Writable
stream. #
encoding
– The new default encoding
+
setDefaultEncoding(encoding) =>
setHeader
(name, value) – Sets a single header value for the header object.setMaxListeners
(n) – By default EventEmitter
s 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 toInfinity
(or 0
) to indicate an unlimited number of listeners.
+ +Returns a reference to the `EventEmitter`, so that calls can be chained. + +
+n
number
setMaxListeners(n) =>
setNoDelay
(noDelay) – Once a socket is assigned to this request and is connected socket.setNoDelay()
will be called. boolean#
noDelay
setNoDelay(noDelay) =>
setSocketKeepAlive
(enable, initialDelay) – Once a socket is assigned to this request and is connected socket.setKeepAlive()
will be called.setTimeout
(timeout, callback) – Once a socket is assigned to this request and is connected socket.setTimeout()
will be called.setTimeout(timeout, callback) =>
uncork
() – The writable.uncork()
method flushes all data buffered since {@link cork} was called.
+ +When using `writable.cork()` and `writable.uncork()` to manage the buffering +of writes to a stream, it is recommended that calls to `writable.uncork()` be +deferred using `process.nextTick()`. Doing so allows batching of all`writable.write()` calls that occur within a given Node.js event loop phase. + +```js +stream.cork() +stream.write('some ') +stream.write('data ') +process.nextTick(() => stream.uncork()) +``` + +If the `writable.cork()` method is called multiple times on a stream, the +same number of calls to `writable.uncork()` must be called to flush the buffered +data. + +```js +stream.cork() +stream.write('some ') +stream.cork() +stream.write('data ') +process.nextTick(() => { + stream.uncork() + // The data will not be flushed until uncork() is called a second time. + stream.uncork() +}) +``` + +See also: `writable.cork()`. + +
+uncork() =>
write
(chunk, callback) – The writable.write()
method writes some data to the stream, and calls the
+supplied callback
once the data has been fully handled. If an error
+occurs, the callback
will be called with the error as its
+first argument. The callback
is called asynchronously and before 'error'
is
+emitted.
+ +The return value is `true` if the internal buffer is less than the`highWaterMark` configured when the stream was created after admitting `chunk`. +If `false` is returned, further attempts to write data to the stream should +stop until the `'drain'` event is emitted. + +While a stream is not draining, calls to `write()` will buffer `chunk`, and +return false. Once all currently buffered chunks are drained (accepted for +delivery by the operating system), the `'drain'` event will be emitted. +It is recommended that once `write()` returns false, no more chunks be written +until the `'drain'` event is emitted. While calling `write()` on a stream that +is not draining is allowed, Node.js will buffer all written chunks until +maximum memory usage occurs, at which point it will abort unconditionally. +Even before it aborts, high memory usage will cause poor garbage collector +performance and high RSS (which is not typically released back to the system, +even after the memory is no longer required). Since TCP sockets may never +drain if the remote peer does not read the data, writing a socket that is +not draining may lead to a remotely exploitable vulnerability. + +Writing data while the stream is not draining is particularly +problematic for a `Transform`, because the `Transform` streams are paused +by default until they are piped or a `'data'` or `'readable'` event handler +is added. + +If the data to be written can be generated or fetched on demand, it is +recommended to encapsulate the logic into a `Readable` and use {@link pipe}. However, if calling `write()` is preferred, it is +possible to respect backpressure and avoid memory issues using the `'drain'` event: + +```js +function write(data, cb) { + if (!stream.write(data)) { + stream.once('drain', cb) + } else { + process.nextTick(cb) + } +} + +// Wait for cb to be called before doing any other write. +write('hello', () => { + console.log('Write completed, do more writes now.') +}) +``` + +A `Writable` stream in object mode will always ignore the `encoding` argument. + +
+chunk
– Optional data to write. For streams not operating in object mode, chunk
must be a string, Buffer
or Uint8Array
. For object mode streams, chunk
may be any
+JavaScript value other than null
.any
callback
(error) undefined | #
error
null
| Error
callback(error) =>
write(chunk, callback) =>
chunk
any
encoding
callback
(error) undefined | #
error
null
| Error
callback(error) =>
write(chunk, encoding, callback) =>
getEventListeners
(emitter, name) – Returns a copy of the array of listeners for the event named eventName
.
+ +For `EventEmitter`s this behaves exactly the same as calling `.listeners` on +the emitter. + +For `EventTarget`s this is the only way to get the event listeners for the +event target. This is useful for debugging and diagnostic purposes. + +```js +const { getEventListeners, EventEmitter } = require('events') + +{ + const ee = new EventEmitter() + const listener = () => console.log('Events are fun') + ee.on('foo', listener) + getEventListeners(ee, 'foo') // [listener] +} +{ + const et = new EventTarget() + const listener = () => console.log('Events are fun') + et.addEventListener('foo', listener) + getEventListeners(et, 'foo') // [listener] +} +``` + +
+emitter
name
string | symbol
getEventListeners(emitter, name) =>
listenerCount
(emitter, eventName) – A class method that returns the number of listeners for the given eventName
registered on the given emitter
.
+ +```js +const { EventEmitter, listenerCount } = require('events') +const myEmitter = new EventEmitter() +myEmitter.on('event', () => {}) +myEmitter.on('event', () => {}) +console.log(listenerCount(myEmitter, 'event')) +// Prints: 2 +``` + +
+emitter
– The emitter to queryeventName
– The event name
+string | symbol
listenerCount(emitter, eventName) =>
on
(emitter, eventName, options) – ```js
+const { on, EventEmitter } = require('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: + +```js +const { on, EventEmitter } = require('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()); +```` + +
+emitter
eventName
– The name of the event being listened forstring
options
on(emitter, eventName, options) =>
once
(emitter, eventName, options) – 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](https://dom.spec.whatwg.org/#interface-eventtarget) interface, which has no special`'error'` event +semantics and does not listen to the `'error'` event. + +```js +const { once, EventEmitter } = require('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.log('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: + +```js +const { EventEmitter, once } = require('events') + +const ee = new EventEmitter() + +once(ee, 'error') + .then(([err]) => console.log('ok', err.message)) + .catch(err => console.log('error', err.message)) + +ee.emit('error', new Error('boom')) + +// Prints: ok boom +``` + +An `AbortSignal` can be used to cancel waiting for the event: + +```js +const { EventEmitter, once } = require('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() // Abort waiting for the event +ee.emit('foo') // Prints: Waiting for the event was canceled! +``` + +
+emitter
eventName
string | symbol
options
once(emitter, eventName, options) =>
emitter
eventName
string
options
once(emitter, eventName, options) =>
setMaxListeners
(n, eventTargets) – By default EventEmitter
s 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 EventEmitter.setMaxListeners()
method allows the default limit to be
+modified (if eventTargets is empty) or modify the limit specified in every EventTarget
| EventEmitter
passed as arguments.
+The value can be set toInfinity
(or 0
) to indicate an unlimited number of listeners.
+ +```js +EventEmitter.setMaxListeners(20) +// Equivalent to +EventEmitter.defaultMaxListeners = 20 + +const eventTarget = new EventTarget() +// Only way to increase limit for `EventTarget` instances +// as these doesn't expose its own `setMaxListeners` method +EventEmitter.setMaxListeners(20, eventTarget) +``` + +
+n
number
eventTargets
setMaxListeners(n, eventTargets) =>
CryptoKey
Duplex
– Duplex streams are streams that implement both the Readable
and Writable
interfaces.+ +Examples of `Duplex` streams include: + +- `TCP sockets` +- `zlib streams` +- `crypto streams` + +
+ boolean
+
+This can be changed manually to change the half-open behavior of an existing`Duplex` stream instance, but must be changed before the `'end'` event is
+emitted.
+
+ boolean boolean boolean boolean boolean number number boolean typeof captureRejectionSymbol boolean typeof errorMonitor
+
+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.
+
+ [asyncIterator]() => #
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L819 allowHalfOpen
– If false
then the stream will automatically end the writable side when the
+readable side ends. Set initially by the allowHalfOpen
constructor option,
+which defaults to false
.#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L115 destroyed
– Is true
after readable.destroy()
has been called.#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L71 readable
– Is true
if it is safe to call readable.read()
, which means
+the stream has not been destroyed or emitted 'error'
or 'end'
.#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L65 readableAborted
– Returns whether the stream was destroyed or errored before emitting 'end'
.#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L77 readableDidRead
– Returns whether 'data'
has been emitted.#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L82 readableEncoding
– Getter for the property encoding
of a given Readable
stream. The encoding
property can be set using the readable.setEncoding()
method.null
| BufferEncoding#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L87 readableEnded
– Becomes true
when 'end'
event is emitted.#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L93 readableFlowing
– This property reflects the current state of a Readable
stream as described
+in the Three states
section.null
| boolean#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L98 readableHighWaterMark
– Returns the value of highWaterMark
passed when creating this Readable
.#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L105 readableLength
– This property contains the number of bytes (or objects) in the queue
+ready to be read. The value provides introspection data regarding
+the status of the highWaterMark
.#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L110 readableObjectMode
– Getter for the property objectMode
of a given Readable
stream.#
src/.fastpm/-/@types/node@17.0.45/events.d.ts#L301 captureRejectionSymbol
#
src/.fastpm/-/@types/node@17.0.45/events.d.ts#L306 captureRejections
– Sets or gets the default captureRejection value for all emitters.#
src/.fastpm/-/@types/node@17.0.45/events.d.ts#L300 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.#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L479 [asyncIterator]
()
AsyncIterableIterator<any>
_construct
(callback)
_construct(callback) =>
_destroy
(error, callback) #
error
null
| Error
_destroy(error, callback) =>
_final
(callback)
_final(callback) =>
_read
(size) number#
size
_read(size) =>
_write
(chunk, encoding, callback) _write(chunk, encoding, callback) =>
_writev
(chunks, callback) { #
chunks
callback
(error) #
error
null
| Error
callback(error) =>
_writev(chunks, callback) =>
addListener
(event, listener) – Event emitter
+The defined events on documents including:
+1. close
+2. data
+3. end
+4. error
+5. pause
+6. readable
+7. resumeaddListener(event, listener) =>
event
"data"
listener
(chunk) any#
chunk
listener(chunk) =>
addListener(event, listener) =>
event
"end"
listener
()
listener() =>
addListener(event, listener) =>
event
"error"
listener
(err) Error#
err
listener(err) =>
addListener(event, listener) =>
event
"pause"
listener
()
listener() =>
addListener(event, listener) =>
event
"readable"
listener
()
listener() =>
addListener(event, listener) =>
event
"resume"
listener
()
listener() =>
addListener(event, listener) =>
event
string | symbol
listener
(args) any []#
args
listener(args) =>
addListener(event, listener) =>
cork
()
cork() =>
destroy
(error) – Destroy the stream. Optionally emit an 'error'
event, and emit a 'close'
event (unless emitClose
is set to false
). After this call, the readable
+stream will release any internal resources and subsequent calls to push()
will be ignored.
+ +Once `destroy()` has been called any further calls will be a no-op and no +further errors except from `_destroy()` may be emitted as `'error'`. + +Implementors should not override this method, but instead implement `readable._destroy()`. + +
+error
– Error which will be passed as payload in 'error'
event
+Error
destroy(error) =>
emit
(event) – Synchronously calls each of the listeners registered for the event namedeventName
, in the order they were registered, passing the supplied arguments
+to each.
+ +Returns `true` if the event had listeners, `false` otherwise. + +```js +const EventEmitter = require('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 +``` + +
+event
"close"
emit(event) =>
event
"data"
chunk
any
emit(event, chunk) =>
event
"end"
emit(event) =>
event
"error"
err
Error
emit(event, err) =>
event
"pause"
emit(event) =>
event
"readable"
emit(event) =>
event
"resume"
emit(event) =>
event
string | symbol
args
any []
emit(event, args) =>
end
(cb) cb() => #
cb
()
void
end(cb) =>
chunk
any
cb
()
cb() =>
end(chunk, cb) =>
chunk
any
encoding
cb
()
cb() =>
end(chunk, encoding, cb) =>
eventNames
() – Returns an array listing the events for which the emitter has registered
+listeners. The values in the array are strings or Symbol
s.
+ +```js +const EventEmitter = require('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) ] +``` + +
+eventNames() =>
getMaxListeners
() – Returns the current max listener value for the EventEmitter
which is either
+set by emitter.setMaxListeners(n)
or defaults to {@link defaultMaxListeners}.
getMaxListeners() =>
isPaused
() – The readable.isPaused()
method returns the current operating state of theReadable
. This is used primarily by the mechanism that underlies thereadable.pipe()
method. In most
+typical cases, there will be no reason to
+use this method directly.
+ +```js +const readable = new stream.Readable() + +readable.isPaused() // === false +readable.pause() +readable.isPaused() // === true +readable.resume() +readable.isPaused() // === false +``` + +
+isPaused() =>
listenerCount
(eventName) – Returns the number of listeners listening to the event named eventName
. string | symbol#
eventName
– The name of the event being listened for
+
listenerCount(eventName) =>
listeners
(eventName) – Returns a copy of the array of listeners for the event named eventName
.
+ +```js +server.on('connection', stream => { + console.log('someone connected!') +}) +console.log(util.inspect(server.listeners('connection'))) +// Prints: [ [Function] ] +``` + +
+eventName
string | symbol
listeners(eventName) =>
off
(eventName, listener) – Alias for emitter.removeListener()
. string | symbol#
eventName
off(eventName, listener) =>
on
(event, listener) – 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.
+ +```js +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. + +```js +const myEE = new EventEmitter() +myEE.on('foo', () => console.log('a')) +myEE.prependListener('foo', () => console.log('b')) +myEE.emit('foo') +// Prints: +// b +// a +``` + +
+event
"close"
listener
()
listener() =>
on(event, listener) =>
event
"data"
listener
(chunk) any#
chunk
listener(chunk) =>
on(event, listener) =>
event
"end"
listener
()
listener() =>
on(event, listener) =>
event
"error"
listener
(err) Error#
err
listener(err) =>
on(event, listener) =>
event
"pause"
listener
()
listener() =>
on(event, listener) =>
event
"readable"
listener
()
listener() =>
on(event, listener) =>
event
"resume"
listener
()
listener() =>
on(event, listener) =>
event
string | symbol
listener
(args) any []#
args
listener(args) =>
on(event, listener) =>
once
(event, listener) – Adds a one-timelistener
function for the event named eventName
. The
+next time eventName
is triggered, this listener is removed and then invoked.
+ +```js +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. + +```js +const myEE = new EventEmitter() +myEE.once('foo', () => console.log('a')) +myEE.prependOnceListener('foo', () => console.log('b')) +myEE.emit('foo') +// Prints: +// b +// a +``` + +
+event
"close"
listener
()
listener() =>
once(event, listener) =>
event
"data"
listener
(chunk) any#
chunk
listener(chunk) =>
once(event, listener) =>
event
"end"
listener
()
listener() =>
once(event, listener) =>
event
"error"
listener
(err) Error#
err
listener(err) =>
once(event, listener) =>
event
"pause"
listener
()
listener() =>
once(event, listener) =>
event
"readable"
listener
()
listener() =>
once(event, listener) =>
event
"resume"
listener
()
listener() =>
once(event, listener) =>
event
string | symbol
listener
(args) any []#
args
listener(args) =>
once(event, listener) =>
pause
() – The readable.pause()
method will cause a stream in flowing mode to stop
+emitting 'data'
events, switching out of flowing mode. Any data that
+becomes available will remain in the internal buffer.
+ +```js +const readable = getReadableStreamSomehow() +readable.on('data', chunk => { + console.log(`Received ${chunk.length} bytes of data.`) + readable.pause() + console.log('There will be no additional data for 1 second.') + setTimeout(() => { + console.log('Now data will start flowing again.') + readable.resume() + }, 1000) +}) +``` + +The `readable.pause()` method has no effect if there is a `'readable'`event listener. + +
+pause() =>
pipe
(destination, { end }) { #
options
pipe<T extends WritableStream<T>>(destination, { end }) =>
prependListener
(event, listener) – 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.
+ +```js +server.prependListener('connection', stream => { + console.log('someone connected!') +}) +``` + +Returns a reference to the `EventEmitter`, so that calls can be chained. + +
+event
"close"
listener
()
listener() =>
prependListener(event, listener) =>
event
"data"
listener
(chunk) any#
chunk
listener(chunk) =>
prependListener(event, listener) =>
event
"end"
listener
()
listener() =>
prependListener(event, listener) =>
event
"error"
listener
(err) Error#
err
listener(err) =>
prependListener(event, listener) =>
event
"pause"
listener
()
listener() =>
prependListener(event, listener) =>
event
"readable"
listener
()
listener() =>
prependListener(event, listener) =>
event
"resume"
listener
()
listener() =>
prependListener(event, listener) =>
event
string | symbol
listener
(args) any []#
args
listener(args) =>
prependListener(event, listener) =>
prependOnceListener
(event, listener) – Adds a one-timelistener
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.
+ +```js +server.prependOnceListener('connection', stream => { + console.log('Ah, we have our first user!') +}) +``` + +Returns a reference to the `EventEmitter`, so that calls can be chained. + +
+event
"close"
listener
()
listener() =>
prependOnceListener(event, listener) =>
event
"data"
listener
(chunk) any#
chunk
listener(chunk) =>
prependOnceListener(event, listener) =>
event
"end"
listener
()
listener() =>
prependOnceListener(event, listener) =>
event
"error"
listener
(err) Error#
err
listener(err) =>
prependOnceListener(event, listener) =>
event
"pause"
listener
()
listener() =>
prependOnceListener(event, listener) =>
event
"readable"
listener
()
listener() =>
prependOnceListener(event, listener) =>
event
"resume"
listener
()
listener() =>
prependOnceListener(event, listener) =>
event
string | symbol
listener
(args) any []#
args
listener(args) =>
prependOnceListener(event, listener) =>
push
(chunk, encoding) push(chunk, encoding) =>
rawListeners
(eventName) – Returns a copy of the array of listeners for the event named eventName
,
+including any wrappers (such as those created by .once()
).
+ +```js +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') +``` + +
+eventName
string | symbol
rawListeners(eventName) =>
read
(size) – The readable.read()
method pulls some data out of the internal buffer and
+returns it. If no data available to be read, null
is returned. By default,
+the data will be returned as a Buffer
object unless an encoding has been
+specified using the readable.setEncoding()
method or the stream is operating
+in object mode.
+ +The optional `size` argument specifies a specific number of bytes to read. If`size` bytes are not available to be read, `null` will be returned _unless_the stream has ended, in which +case all of the data remaining in the internal +buffer will be returned. + +If the `size` argument is not specified, all of the data contained in the +internal buffer will be returned. + +The `size` argument must be less than or equal to 1 GiB. + +The `readable.read()` method should only be called on `Readable` streams +operating in paused mode. In flowing mode, `readable.read()` is called +automatically until the internal buffer is fully drained. + +```js +const readable = getReadableStreamSomehow() + +// 'readable' may be triggered multiple times as data is buffered in +readable.on('readable', () => { + let chunk + console.log('Stream is readable (new data received in buffer)') + // Use a loop to make sure we read all currently available data + while (null !== (chunk = readable.read())) { + console.log(`Read ${chunk.length} bytes of data...`) + } +}) + +// 'end' will be triggered once when there is no more data available +readable.on('end', () => { + console.log('Reached end of stream.') +}) +``` + +Each call to `readable.read()` returns a chunk of data, or `null`. The chunks +are not concatenated. A `while` loop is necessary to consume all data +currently in the buffer. When reading a large file `.read()` may return `null`, +having consumed all buffered content so far, but there is still more data to +come not yet buffered. In this case a new `'readable'` event will be emitted +when there is more data in the buffer. Finally the `'end'` event will be +emitted when there is no more data to come. + +Therefore to read a file's whole contents from a `readable`, it is necessary +to collect chunks across multiple `'readable'` events: + +```js +const chunks = [] + +readable.on('readable', () => { + let chunk + while (null !== (chunk = readable.read())) { + chunks.push(chunk) + } +}) + +readable.on('end', () => { + const content = chunks.join('') +}) +``` + +A `Readable` stream in object mode will always return a single item from +a call to `readable.read(size)`, regardless of the value of the`size` argument. + +If the `readable.read()` method returns a chunk of data, a `'data'` event will +also be emitted. + +Calling {@link read} after the `'end'` event has +been emitted will return `null`. No runtime error will be raised. + +
+size
– Optional argument to specify how much data to read.
+number
read(size) =>
removeAllListeners
(event) – 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. + +
+event
string | symbol
removeAllListeners(event) =>
removeListener
(event, listener) – Removes the specified listener
from the listener array for the event namedeventName
.
+ +```js +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. + +```js +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 indices 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: + +```js +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. + +
+event
"close"
listener
()
listener() =>
removeListener(event, listener) =>
event
"data"
listener
(chunk) any#
chunk
listener(chunk) =>
removeListener(event, listener) =>
event
"end"
listener
()
listener() =>
removeListener(event, listener) =>
event
"error"
listener
(err) Error#
err
listener(err) =>
removeListener(event, listener) =>
event
"pause"
listener
()
listener() =>
removeListener(event, listener) =>
event
"readable"
listener
()
listener() =>
removeListener(event, listener) =>
event
"resume"
listener
()
listener() =>
removeListener(event, listener) =>
event
string | symbol
listener
(args) any []#
args
listener(args) =>
removeListener(event, listener) =>
resume
() – The readable.resume()
method causes an explicitly paused Readable
stream to
+resume emitting 'data'
events, switching the stream into flowing mode.
+ +The `readable.resume()` method can be used to fully consume the data from a +stream without actually processing any of that data: + +```js +getReadableStreamSomehow() + .resume() + .on('end', () => { + console.log('Reached the end, but did not read anything.') + }) +``` + +The `readable.resume()` method has no effect if there is a `'readable'`event listener. + +
+resume() =>
setDefaultEncoding
(encoding) #
encoding
setDefaultEncoding(encoding) =>
setEncoding
(encoding) – The readable.setEncoding()
method sets the character encoding for
+data read from the Readable
stream.
+ +By default, no encoding is assigned and stream data will be returned as`Buffer` objects. Setting an encoding causes the stream data +to be returned as strings of the specified encoding rather than as `Buffer`objects. For instance, calling `readable.setEncoding('utf8')` will cause the +output data to be interpreted as UTF-8 data, and passed as strings. Calling`readable.setEncoding('hex')` will cause the data to be encoded in hexadecimal +string format. + +The `Readable` stream will properly handle multi-byte characters delivered +through the stream that would otherwise become improperly decoded if simply +pulled from the stream as `Buffer` objects. + +```js +const readable = getReadableStreamSomehow() +readable.setEncoding('utf8') +readable.on('data', chunk => { + assert.equal(typeof chunk, 'string') + console.log('Got %d characters of string data:', chunk.length) +}) +``` + +
+encoding
– The encoding to use.
+setEncoding(encoding) =>
setMaxListeners
(n) – By default EventEmitter
s 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 toInfinity
(or 0
) to indicate an unlimited number of listeners.
+ +Returns a reference to the `EventEmitter`, so that calls can be chained. + +
+n
number
setMaxListeners(n) =>
uncork
()
uncork() =>
unpipe
(destination) – The readable.unpipe()
method detaches a Writable
stream previously attached
+using the {@link pipe} method.
+ +If the `destination` is not specified, then _all_ pipes are detached. + +If the `destination` is specified, but no pipe is set up for it, then +the method does nothing. + +```js +const fs = require('fs') +const readable = getReadableStreamSomehow() +const writable = fs.createWriteStream('file.txt') +// All the data from readable goes into 'file.txt', +// but only for the first second. +readable.pipe(writable) +setTimeout(() => { + console.log('Stop writing to file.txt.') + readable.unpipe(writable) + console.log('Manually close the file stream.') + writable.end() +}, 1000) +``` + +
+destination
– Optional specific stream to unpipe
+unpipe(destination) =>
unshift
(chunk, encoding) – Passing chunk
as null
signals the end of the stream (EOF) and behaves the
+same as readable.push(null)
, after which no more data can be written. The EOF
+signal is put at the end of the buffer and any buffered data will still be
+flushed.
+ +The `readable.unshift()` method pushes a chunk of data back into the internal +buffer. This is useful in certain situations where a stream is being consumed by +code that needs to "un-consume" some amount of data that it has optimistically +pulled out of the source, so that the data can be passed on to some other party. + +The `stream.unshift(chunk)` method cannot be called after the `'end'` event +has been emitted or a runtime error will be thrown. + +Developers using `stream.unshift()` often should consider switching to +use of a `Transform` stream instead. See the `API for stream implementers` section for more information. + +```js +// Pull off a header delimited by \n\n. +// Use unshift() if we get too much. +// Call the callback with (error, header, stream). +const { StringDecoder } = require('string_decoder') +function parseHeader(stream, callback) { + stream.on('error', callback) + stream.on('readable', onReadable) + const decoder = new StringDecoder('utf8') + let header = '' + function onReadable() { + let chunk + while (null !== (chunk = stream.read())) { + const str = decoder.write(chunk) + if (str.match(/\n\n/)) { + // Found the header boundary. + const split = str.split(/\n\n/) + header += split.shift() + const remaining = split.join('\n\n') + const buf = Buffer.from(remaining, 'utf8') + stream.removeListener('error', callback) + // Remove the 'readable' listener before unshifting. + stream.removeListener('readable', onReadable) + if (buf.length) + stream.unshift(buf) + // Now the body of the message can be read from the stream. + callback(null, header, stream) + } else { + // Still reading the header. + header += str + } + } + } +} +``` + +Unlike {@link push}, `stream.unshift(chunk)` will not +end the reading process by resetting the internal reading state of the stream. +This can cause unexpected results if `readable.unshift()` is called during a +read (i.e. from within a {@link _read} implementation on a +custom stream). Following the call to `readable.unshift()` with an immediate {@link push} will reset the reading state appropriately, +however it is best to simply avoid calling `readable.unshift()` while in the +process of performing a read. + +
+chunk
– Chunk of data to unshift onto the read queue. For streams not operating in object mode, chunk
must be a string, Buffer
, Uint8Array
or null
. For object mode
+streams, chunk
may be any JavaScript value.any
encoding
– Encoding of string chunks. Must be a valid Buffer
encoding, such as 'utf8'
or 'ascii'
.
+unshift(chunk, encoding) =>
wrap
(stream) – Prior to Node.js 0.10, streams did not implement the entire stream
module API
+as it is currently defined. (See Compatibility
for more information.)
+ +When using an older Node.js library that emits `'data'` events and has a {@link pause} method that is advisory only, the`readable.wrap()` method can be used to create a `Readable` +stream that uses +the old stream as its data source. + +It will rarely be necessary to use `readable.wrap()` but the method has been +provided as a convenience for interacting with older Node.js applications and +libraries. + +```js +const { OldReader } = require('./old-api-module.js') +const { Readable } = require('stream') +const oreader = new OldReader() +const myReader = new Readable().wrap(oreader) + +myReader.on('readable', () => { + myReader.read() // etc. +}) +``` + +
+stream
– An "old style" readable stream
+wrap(stream) =>
write
(chunk, encoding, cb) write(chunk, encoding, cb) =>
chunk
any
cb
(error) undefined | #
error
null
| Error
cb(error) =>
write(chunk, cb) =>
from
(src) – A utility method for creating duplex streams.
+ +- `Stream` converts writable stream into writable `Duplex` and readable stream + to `Duplex`. +- `Blob` converts into readable `Duplex`. +- `string` converts into readable `Duplex`. +- `ArrayBuffer` converts into readable `Duplex`. +- `AsyncIterable` converts into a readable `Duplex`. Cannot yield `null`. +- `AsyncGeneratorFunction` converts into a readable/writable transform + `Duplex`. Must take a source `AsyncIterable` as first parameter. Cannot yield + `null`. +- `AsyncFunction` converts into a writable `Duplex`. Must return + either `null` or `undefined` +- `Object ({ writable, readable })` converts `readable` and + `writable` into `Stream` and then combines them into `Duplex` where the + `Duplex` will write to the `writable` and read from the `readable`. +- `Promise` converts into readable `Duplex`. Value `null` is ignored. + +
+src
string | Object | Stream | Iterable<any> | AsyncIterable<any> | Blob | ArrayBuffer | AsyncGeneratorFunction | Promise<any>
from(src) =>
getEventListeners
(emitter, name) – Returns a copy of the array of listeners for the event named eventName
.
+ +For `EventEmitter`s this behaves exactly the same as calling `.listeners` on +the emitter. + +For `EventTarget`s this is the only way to get the event listeners for the +event target. This is useful for debugging and diagnostic purposes. + +```js +const { getEventListeners, EventEmitter } = require('events') + +{ + const ee = new EventEmitter() + const listener = () => console.log('Events are fun') + ee.on('foo', listener) + getEventListeners(ee, 'foo') // [listener] +} +{ + const et = new EventTarget() + const listener = () => console.log('Events are fun') + et.addEventListener('foo', listener) + getEventListeners(et, 'foo') // [listener] +} +``` + +
+emitter
name
string | symbol
getEventListeners(emitter, name) =>
isDisturbed
(stream) – Returns whether the stream has been read from or cancelled. #
stream
isDisturbed(stream) =>
listenerCount
(emitter, eventName) – A class method that returns the number of listeners for the given eventName
registered on the given emitter
.
+ +```js +const { EventEmitter, listenerCount } = require('events') +const myEmitter = new EventEmitter() +myEmitter.on('event', () => {}) +myEmitter.on('event', () => {}) +console.log(listenerCount(myEmitter, 'event')) +// Prints: 2 +``` + +
+emitter
– The emitter to queryeventName
– The event name
+string | symbol
listenerCount(emitter, eventName) =>
on
(emitter, eventName, options) – ```js
+const { on, EventEmitter } = require('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: + +```js +const { on, EventEmitter } = require('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()); +```` + +
+emitter
eventName
– The name of the event being listened forstring
options
on(emitter, eventName, options) =>
once
(emitter, eventName, options) – 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](https://dom.spec.whatwg.org/#interface-eventtarget) interface, which has no special`'error'` event +semantics and does not listen to the `'error'` event. + +```js +const { once, EventEmitter } = require('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.log('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: + +```js +const { EventEmitter, once } = require('events') + +const ee = new EventEmitter() + +once(ee, 'error') + .then(([err]) => console.log('ok', err.message)) + .catch(err => console.log('error', err.message)) + +ee.emit('error', new Error('boom')) + +// Prints: ok boom +``` + +An `AbortSignal` can be used to cancel waiting for the event: + +```js +const { EventEmitter, once } = require('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() // Abort waiting for the event +ee.emit('foo') // Prints: Waiting for the event was canceled! +``` + +
+emitter
eventName
string | symbol
options
once(emitter, eventName, options) =>
emitter
eventName
string
options
once(emitter, eventName, options) =>
setMaxListeners
(n, eventTargets) – By default EventEmitter
s 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 EventEmitter.setMaxListeners()
method allows the default limit to be
+modified (if eventTargets is empty) or modify the limit specified in every EventTarget
| EventEmitter
passed as arguments.
+The value can be set toInfinity
(or 0
) to indicate an unlimited number of listeners.
+ +```js +EventEmitter.setMaxListeners(20) +// Equivalent to +EventEmitter.defaultMaxListeners = 20 + +const eventTarget = new EventTarget() +// Only way to increase limit for `EventTarget` instances +// as these doesn't expose its own `setMaxListeners` method +EventEmitter.setMaxListeners(20, eventTarget) +``` + +
+n
number
eventTargets
setMaxListeners(n, eventTargets) =>
EventEmitter
– The EventEmitter
class is defined and exposed by the events
module:+ +```js +const EventEmitter = require('events') +``` + +All `EventEmitter`s emit the event `'newListener'` when new listeners are +added and `'removeListener'` when existing listeners are removed. + +It supports the following option: + +
+ typeof captureRejectionSymbol boolean typeof errorMonitor
+
+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.
+
+#
src/.fastpm/-/@types/node@17.0.45/events.d.ts#L74 constructor
(options)
#
src/.fastpm/-/@types/node@17.0.45/events.d.ts#L301 captureRejectionSymbol
#
src/.fastpm/-/@types/node@17.0.45/events.d.ts#L306 captureRejections
– Sets or gets the default captureRejection value for all emitters.#
src/.fastpm/-/@types/node@17.0.45/events.d.ts#L300 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.
addListener(eventName, listener) =>
emit
(eventName, args) – Synchronously calls each of the listeners registered for the event namedeventName
, in the order they were registered, passing the supplied arguments
+to each.
+ +Returns `true` if the event had listeners, `false` otherwise. + +```js +const EventEmitter = require('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 +``` + +
+eventName
string | symbol
args
any []
emit(eventName, args) =>
eventNames
() – Returns an array listing the events for which the emitter has registered
+listeners. The values in the array are strings or Symbol
s.
+ +```js +const EventEmitter = require('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) ] +``` + +
+eventNames() =>
getMaxListeners
() – Returns the current max listener value for the EventEmitter
which is either
+set by emitter.setMaxListeners(n)
or defaults to {@link defaultMaxListeners}.
getMaxListeners() =>
listenerCount
(eventName) – Returns the number of listeners listening to the event named eventName
. string | symbol#
eventName
– The name of the event being listened for
+
listenerCount(eventName) =>
listeners
(eventName) – Returns a copy of the array of listeners for the event named eventName
.
+ +```js +server.on('connection', stream => { + console.log('someone connected!') +}) +console.log(util.inspect(server.listeners('connection'))) +// Prints: [ [Function] ] +``` + +
+eventName
string | symbol
listeners(eventName) =>
off
(eventName, listener) – Alias for emitter.removeListener()
. string | symbol#
eventName
off(eventName, listener) =>
on
(eventName, listener) – 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.
+ +```js +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. + +```js +const myEE = new EventEmitter() +myEE.on('foo', () => console.log('a')) +myEE.prependListener('foo', () => console.log('b')) +myEE.emit('foo') +// Prints: +// b +// a +``` + +
+eventName
– The name of the event.string | symbol
listener
(args) any []#
args
listener(args) =>
on(eventName, listener) =>
once
(eventName, listener) – Adds a one-timelistener
function for the event named eventName
. The
+next time eventName
is triggered, this listener is removed and then invoked.
+ +```js +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. + +```js +const myEE = new EventEmitter() +myEE.once('foo', () => console.log('a')) +myEE.prependOnceListener('foo', () => console.log('b')) +myEE.emit('foo') +// Prints: +// b +// a +``` + +
+eventName
– The name of the event.string | symbol
listener
(args) any []#
args
listener(args) =>
once(eventName, listener) =>
prependListener
(eventName, listener) – 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.
+ +```js +server.prependListener('connection', stream => { + console.log('someone connected!') +}) +``` + +Returns a reference to the `EventEmitter`, so that calls can be chained. + +
+eventName
– The name of the event.string | symbol
listener
(args) any []#
args
listener(args) =>
prependListener(eventName, listener) =>
prependOnceListener
(eventName, listener) – Adds a one-timelistener
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.
+ +```js +server.prependOnceListener('connection', stream => { + console.log('Ah, we have our first user!') +}) +``` + +Returns a reference to the `EventEmitter`, so that calls can be chained. + +
+eventName
– The name of the event.string | symbol
listener
(args) any []#
args
listener(args) =>
prependOnceListener(eventName, listener) =>
rawListeners
(eventName) – Returns a copy of the array of listeners for the event named eventName
,
+including any wrappers (such as those created by .once()
).
+ +```js +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') +``` + +
+eventName
string | symbol
rawListeners(eventName) =>
removeAllListeners
(event) – 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. + +
+event
string | symbol
removeAllListeners(event) =>
removeListener
(eventName, listener) – Removes the specified listener
from the listener array for the event namedeventName
.
+ +```js +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. + +```js +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 indices 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: + +```js +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. + +
+eventName
string | symbol
listener
(args) any []#
args
listener(args) =>
removeListener(eventName, listener) =>
setMaxListeners
(n) – By default EventEmitter
s 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 toInfinity
(or 0
) to indicate an unlimited number of listeners.
+ +Returns a reference to the `EventEmitter`, so that calls can be chained. + +
+n
number
setMaxListeners(n) =>
getEventListeners
(emitter, name) – Returns a copy of the array of listeners for the event named eventName
.
+ +For `EventEmitter`s this behaves exactly the same as calling `.listeners` on +the emitter. + +For `EventTarget`s this is the only way to get the event listeners for the +event target. This is useful for debugging and diagnostic purposes. + +```js +const { getEventListeners, EventEmitter } = require('events') + +{ + const ee = new EventEmitter() + const listener = () => console.log('Events are fun') + ee.on('foo', listener) + getEventListeners(ee, 'foo') // [listener] +} +{ + const et = new EventTarget() + const listener = () => console.log('Events are fun') + et.addEventListener('foo', listener) + getEventListeners(et, 'foo') // [listener] +} +``` + +
+emitter
name
string | symbol
getEventListeners(emitter, name) =>
listenerCount
(emitter, eventName) – A class method that returns the number of listeners for the given eventName
registered on the given emitter
.
+ +```js +const { EventEmitter, listenerCount } = require('events') +const myEmitter = new EventEmitter() +myEmitter.on('event', () => {}) +myEmitter.on('event', () => {}) +console.log(listenerCount(myEmitter, 'event')) +// Prints: 2 +``` + +
+emitter
– The emitter to queryeventName
– The event name
+string | symbol
listenerCount(emitter, eventName) =>
on
(emitter, eventName, options) – ```js
+const { on, EventEmitter } = require('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: + +```js +const { on, EventEmitter } = require('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()); +```` + +
+emitter
eventName
– The name of the event being listened forstring
options
on(emitter, eventName, options) =>
once
(emitter, eventName, options) – 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](https://dom.spec.whatwg.org/#interface-eventtarget) interface, which has no special`'error'` event +semantics and does not listen to the `'error'` event. + +```js +const { once, EventEmitter } = require('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.log('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: + +```js +const { EventEmitter, once } = require('events') + +const ee = new EventEmitter() + +once(ee, 'error') + .then(([err]) => console.log('ok', err.message)) + .catch(err => console.log('error', err.message)) + +ee.emit('error', new Error('boom')) + +// Prints: ok boom +``` + +An `AbortSignal` can be used to cancel waiting for the event: + +```js +const { EventEmitter, once } = require('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() // Abort waiting for the event +ee.emit('foo') // Prints: Waiting for the event was canceled! +``` + +
+emitter
eventName
string | symbol
options
once(emitter, eventName, options) =>
emitter
eventName
string
options
once(emitter, eventName, options) =>
setMaxListeners
(n, eventTargets) – By default EventEmitter
s 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 EventEmitter.setMaxListeners()
method allows the default limit to be
+modified (if eventTargets is empty) or modify the limit specified in every EventTarget
| EventEmitter
passed as arguments.
+The value can be set toInfinity
(or 0
) to indicate an unlimited number of listeners.
+ +```js +EventEmitter.setMaxListeners(20) +// Equivalent to +EventEmitter.defaultMaxListeners = 20 + +const eventTarget = new EventTarget() +// Only way to increase limit for `EventTarget` instances +// as these doesn't expose its own `setMaxListeners` method +EventEmitter.setMaxListeners(20, eventTarget) +``` + +
+n
number
eventTargets
setMaxListeners(n, eventTargets) =>
FSWatcher
typeof captureRejectionSymbol boolean typeof errorMonitor
+
+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.
+
+#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L749 constructor
(options) – Constructs a new FSWatcher instance with optional WatchOptions parameter.
#
src/.fastpm/-/@types/node@17.0.45/events.d.ts#L301 captureRejectionSymbol
#
src/.fastpm/-/@types/node@17.0.45/events.d.ts#L306 captureRejections
– Sets or gets the default captureRejection value for all emitters.#
src/.fastpm/-/@types/node@17.0.45/events.d.ts#L300 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.#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L755 add
(paths) – Add files, directories, or glob patterns for tracking. Takes an array of strings or just one
+string.
addListener
(eventName, listener) – Alias for emitter.on(eventName, listener)
. string | symbol#
eventName
addListener(eventName, listener) =>
close
() – Removes all listeners from watched files.
close() =>
emit
(eventName, args) – Synchronously calls each of the listeners registered for the event namedeventName
, in the order they were registered, passing the supplied arguments
+to each.
+ +Returns `true` if the event had listeners, `false` otherwise. + +```js +const EventEmitter = require('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 +``` + +
+eventName
string | symbol
args
any []
emit(eventName, args) =>
eventNames
() – Returns an array listing the events for which the emitter has registered
+listeners. The values in the array are strings or Symbol
s.
+ +```js +const EventEmitter = require('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) ] +``` + +
+eventNames() =>
getMaxListeners
() – Returns the current max listener value for the EventEmitter
which is either
+set by emitter.setMaxListeners(n)
or defaults to {@link defaultMaxListeners}.
getMaxListeners() =>
getWatched
() – Returns an object representing all the paths on the file system being watched by this
+FSWatcher
instance. The object's keys are all the directories (using absolute paths unless
+the cwd
option was used), and the values are arrays of the names of the items contained in
+each directory.
getWatched() =>
listenerCount
(eventName) – Returns the number of listeners listening to the event named eventName
. string | symbol#
eventName
– The name of the event being listened for
+
listenerCount(eventName) =>
listeners
(eventName) – Returns a copy of the array of listeners for the event named eventName
.
+ +```js +server.on('connection', stream => { + console.log('someone connected!') +}) +console.log(util.inspect(server.listeners('connection'))) +// Prints: [ [Function] ] +``` + +
+eventName
string | symbol
listeners(eventName) =>
off
(eventName, listener) – Alias for emitter.removeListener()
. string | symbol#
eventName
off(eventName, listener) =>
on
(event, listener) – 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.
+ +```js +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. + +```js +const myEE = new EventEmitter() +myEE.on('foo', () => console.log('a')) +myEE.prependListener('foo', () => console.log('b')) +myEE.emit('foo') +// Prints: +// b +// a +``` + +
+event
"add"
| "addDir"
| "change"
on(event, listener) =>
event
"all"
listener
(eventName, path, stats) on(event, listener) =>
event
"error"
listener
(error) Error#
error
listener(error) =>
on(event, listener) =>
event
"raw"
listener
(eventName, path, details) on(event, listener) =>
event
"ready"
listener
()
listener() =>
on(event, listener) =>
event
"unlink"
| "unlinkDir"
listener
(path) string#
path
listener(path) =>
on(event, listener) =>
event
string
listener
(args) any []#
args
listener(args) =>
on(event, listener) =>
once
(eventName, listener) – Adds a one-timelistener
function for the event named eventName
. The
+next time eventName
is triggered, this listener is removed and then invoked.
+ +```js +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. + +```js +const myEE = new EventEmitter() +myEE.once('foo', () => console.log('a')) +myEE.prependOnceListener('foo', () => console.log('b')) +myEE.emit('foo') +// Prints: +// b +// a +``` + +
+eventName
– The name of the event.string | symbol
listener
(args) any []#
args
listener(args) =>
once(eventName, listener) =>
prependListener
(eventName, listener) – 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.
+ +```js +server.prependListener('connection', stream => { + console.log('someone connected!') +}) +``` + +Returns a reference to the `EventEmitter`, so that calls can be chained. + +
+eventName
– The name of the event.string | symbol
listener
(args) any []#
args
listener(args) =>
prependListener(eventName, listener) =>
prependOnceListener
(eventName, listener) – Adds a one-timelistener
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.
+ +```js +server.prependOnceListener('connection', stream => { + console.log('Ah, we have our first user!') +}) +``` + +Returns a reference to the `EventEmitter`, so that calls can be chained. + +
+eventName
– The name of the event.string | symbol
listener
(args) any []#
args
listener(args) =>
prependOnceListener(eventName, listener) =>
rawListeners
(eventName) – Returns a copy of the array of listeners for the event named eventName
,
+including any wrappers (such as those created by .once()
).
+ +```js +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') +``` + +
+eventName
string | symbol
rawListeners(eventName) =>
removeAllListeners
(event) – 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. + +
+event
string | symbol
removeAllListeners(event) =>
removeListener
(eventName, listener) – Removes the specified listener
from the listener array for the event namedeventName
.
+ +```js +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. + +```js +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 indices 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: + +```js +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. + +
+eventName
string | symbol
listener
(args) any []#
args
listener(args) =>
removeListener(eventName, listener) =>
setMaxListeners
(n) – By default EventEmitter
s 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 toInfinity
(or 0
) to indicate an unlimited number of listeners.
+ +Returns a reference to the `EventEmitter`, so that calls can be chained. + +
+n
number
setMaxListeners(n) =>
unwatch
(paths) – Stop watching files, directories, or glob patterns. Takes an array of strings or just one
+string. string | readonly string []#
paths
unwatch(paths) =>
getEventListeners
(emitter, name) – Returns a copy of the array of listeners for the event named eventName
.
+ +For `EventEmitter`s this behaves exactly the same as calling `.listeners` on +the emitter. + +For `EventTarget`s this is the only way to get the event listeners for the +event target. This is useful for debugging and diagnostic purposes. + +```js +const { getEventListeners, EventEmitter } = require('events') + +{ + const ee = new EventEmitter() + const listener = () => console.log('Events are fun') + ee.on('foo', listener) + getEventListeners(ee, 'foo') // [listener] +} +{ + const et = new EventTarget() + const listener = () => console.log('Events are fun') + et.addEventListener('foo', listener) + getEventListeners(et, 'foo') // [listener] +} +``` + +
+emitter
name
string | symbol
getEventListeners(emitter, name) =>
listenerCount
(emitter, eventName) – A class method that returns the number of listeners for the given eventName
registered on the given emitter
.
+ +```js +const { EventEmitter, listenerCount } = require('events') +const myEmitter = new EventEmitter() +myEmitter.on('event', () => {}) +myEmitter.on('event', () => {}) +console.log(listenerCount(myEmitter, 'event')) +// Prints: 2 +``` + +
+emitter
– The emitter to queryeventName
– The event name
+string | symbol
listenerCount(emitter, eventName) =>
on
(emitter, eventName, options) – ```js
+const { on, EventEmitter } = require('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: + +```js +const { on, EventEmitter } = require('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()); +```` + +
+emitter
eventName
– The name of the event being listened forstring
options
on(emitter, eventName, options) =>
once
(emitter, eventName, options) – 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](https://dom.spec.whatwg.org/#interface-eventtarget) interface, which has no special`'error'` event +semantics and does not listen to the `'error'` event. + +```js +const { once, EventEmitter } = require('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.log('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: + +```js +const { EventEmitter, once } = require('events') + +const ee = new EventEmitter() + +once(ee, 'error') + .then(([err]) => console.log('ok', err.message)) + .catch(err => console.log('error', err.message)) + +ee.emit('error', new Error('boom')) + +// Prints: ok boom +``` + +An `AbortSignal` can be used to cancel waiting for the event: + +```js +const { EventEmitter, once } = require('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() // Abort waiting for the event +ee.emit('foo') // Prints: Waiting for the event was canceled! +``` + +
+emitter
eventName
string | symbol
options
once(emitter, eventName, options) =>
emitter
eventName
string
options
once(emitter, eventName, options) =>
setMaxListeners
(n, eventTargets) – By default EventEmitter
s 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 EventEmitter.setMaxListeners()
method allows the default limit to be
+modified (if eventTargets is empty) or modify the limit specified in every EventTarget
| EventEmitter
passed as arguments.
+The value can be set toInfinity
(or 0
) to indicate an unlimited number of listeners.
+ +```js +EventEmitter.setMaxListeners(20) +// Equivalent to +EventEmitter.defaultMaxListeners = 20 + +const eventTarget = new EventTarget() +// Only way to increase limit for `EventTarget` instances +// as these doesn't expose its own `setMaxListeners` method +EventEmitter.setMaxListeners(20, eventTarget) +``` + +
+n
number
eventTargets
setMaxListeners(n, eventTargets) =>
IncomingMessage
boolean boolean
+
+This property is particularly useful as a means of determining if a client or
+server fully transmitted a message before a connection was terminated:
+
+```js
+const req = http.request({
+ host: '127.0.0.1',
+ port: 8080,
+ method: 'POST',
+}, res => {
+ res.resume()
+ res.on('end', () => {
+ if (!res.complete)
+ console.error(
+ 'The connection was terminated while the message was still being sent'
+ )
+ })
+})
+```
+
+ boolean
+
+Key-value pairs of header names and values. Header names are lower-cased.
+
+```js
+// Prints something like:
+//
+// { 'user-agent': 'curl/7.22.0',
+// host: '127.0.0.1:8000',
+// accept: '*' }
+console.log(request.headers)
+```
+
+Duplicates in raw headers are handled in the following ways, depending on the
+header name:
+
+- Duplicates of `age`, `authorization`, `content-length`, `content-type`,`etag`, `expires`, `from`, `host`, `if-modified-since`, `if-unmodified-since`,`last-modified`, `location`,
+ `max-forwards`, `proxy-authorization`, `referer`,`retry-after`, `server`, or `user-agent` are discarded.
+- `set-cookie` is always an array. Duplicates are added to the array.
+- For duplicate `cookie` headers, the values are joined together with '; '.
+- For all other headers, the values are joined together with ', '.
+
+ string
+
+Also `message.httpVersionMajor` is the first integer and`message.httpVersionMinor` is the second.
+
+ string
+
+The request method as a string. Read only. Examples: `'GET'`, `'DELETE'`.
+
+ string []
+
+The keys and values are in the same list. It is _not_ a
+list of tuples. So, the even-numbered offsets are key values, and the
+odd-numbered offsets are the associated values.
+
+Header names are not lowercased, and duplicates are not merged.
+
+```js
+// Prints something like:
+//
+// [ 'user-agent',
+// 'this is invalid because there can be only one',
+// 'User-Agent',
+// 'curl/7.22.0',
+// 'Host',
+// '127.0.0.1:8000',
+// 'ACCEPT',
+// '*' ]
+console.log(request.rawHeaders)
+```
+
+ string [] boolean boolean boolean boolean number number boolean
+
+With HTTPS support, use `request.socket.getPeerCertificate()` to obtain the
+client's authentication details.
+
+This property is guaranteed to be an instance of the `net.Socket` class,
+a subclass of `stream.Duplex`, unless the user specified a socket
+type other than `net.Socket`.
+
+ number
+
+The 3-digit HTTP response status code. E.G. `404`.
+
+ string
+
+The HTTP response status message (reason phrase). E.G. `OK` or `Internal Server Error`.
+
+ Dict<string> string
+
+Request URL string. This contains only the URL that is present in the actual
+HTTP request. Take the following request:
+
+```http
+GET /status?name=ryan HTTP/1.1
+Accept: text/plain
+```
+
+To parse the URL into its parts:
+
+```js
+new URL(request.url, `http://${request.headers.host}`)
+```
+
+When `request.url` is `'/status?name=ryan'` and`request.headers.host` is `'localhost:3000'`:
+
+```console
+$ node
+> new URL(request.url, `http://${request.headers.host}`)
+URL {
+ href: 'http://localhost:3000/status?name=ryan',
+ origin: 'http://localhost:3000',
+ protocol: 'http:',
+ username: '',
+ password: '',
+ host: 'localhost:3000',
+ hostname: 'localhost',
+ port: '3000',
+ pathname: '/status',
+ search: '?name=ryan',
+ searchParams: URLSearchParams { 'name' => 'ryan' },
+ hash: ''
+}
+```
+
+ typeof captureRejectionSymbol boolean typeof errorMonitor
+
+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.
+
+ [asyncIterator]() => #
src/.fastpm/-/@types/node@17.0.45/http.d.ts#L793 aborted
– The message.aborted
property will be true
if the request has
+been aborted.#
src/.fastpm/-/@types/node@17.0.45/http.d.ts#L828 complete
– The message.complete
property will be true
if a complete HTTP message has
+been received and successfully parsed.#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L115 destroyed
– Is true
after readable.destroy()
has been called.#
src/.fastpm/-/@types/node@17.0.45/http.d.ts#L871 headers
– The request/response headers object.
#
src/.fastpm/-/@types/node@17.0.45/http.d.ts#L802 httpVersion
– In case of server request, the HTTP version sent by the client. In the case of
+client response, the HTTP version of the connected-to server.
+Probably either '1.1'
or '1.0'
.#
src/.fastpm/-/@types/node@17.0.45/http.d.ts#L919 method
– Only valid for request obtained from {@link Server}.#
src/.fastpm/-/@types/node@17.0.45/http.d.ts#L896 rawHeaders
– The raw request/response headers list exactly as they were received.#
src/.fastpm/-/@types/node@17.0.45/http.d.ts#L907 rawTrailers
– The raw request/response trailer keys and values exactly as they were
+received. Only populated at the 'end'
event.#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L71 readable
– Is true
if it is safe to call readable.read()
, which means
+the stream has not been destroyed or emitted 'error'
or 'end'
.#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L65 readableAborted
– Returns whether the stream was destroyed or errored before emitting 'end'
.#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L77 readableDidRead
– Returns whether 'data'
has been emitted.#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L82 readableEncoding
– Getter for the property encoding
of a given Readable
stream. The encoding
property can be set using the readable.setEncoding()
method.null
| BufferEncoding#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L87 readableEnded
– Becomes true
when 'end'
event is emitted.#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L93 readableFlowing
– This property reflects the current state of a Readable
stream as described
+in the Three states
section.null
| boolean#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L98 readableHighWaterMark
– Returns the value of highWaterMark
passed when creating this Readable
.#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L105 readableLength
– This property contains the number of bytes (or objects) in the queue
+ready to be read. The value provides introspection data regarding
+the status of the highWaterMark
.#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L110 readableObjectMode
– Getter for the property objectMode
of a given Readable
stream.#
src/.fastpm/-/@types/node@17.0.45/http.d.ts#L846 socket
– The net.Socket
object associated with the connection.
#
src/.fastpm/-/@types/node@17.0.45/http.d.ts#L966 statusCode
– Only valid for response obtained from {@link ClientRequest}.#
src/.fastpm/-/@types/node@17.0.45/http.d.ts#L973 statusMessage
– Only valid for response obtained from {@link ClientRequest}.#
src/.fastpm/-/@types/node@17.0.45/http.d.ts#L901 trailers
– The request/response trailers object. Only populated at the 'end'
event.#
src/.fastpm/-/@types/node@17.0.45/http.d.ts#L959 url
– Only valid for request obtained from {@link Server}.#
src/.fastpm/-/@types/node@17.0.45/events.d.ts#L301 captureRejectionSymbol
#
src/.fastpm/-/@types/node@17.0.45/events.d.ts#L306 captureRejections
– Sets or gets the default captureRejection value for all emitters.#
src/.fastpm/-/@types/node@17.0.45/events.d.ts#L300 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.#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L479 [asyncIterator]
()
AsyncIterableIterator<any>
_construct
(callback)
_construct(callback) =>
_destroy
(error, callback) #
error
null
| Error
_destroy(error, callback) =>
_read
(size) number#
size
_read(size) =>
addListener
(event, listener) – Event emitter
+The defined events on documents including:
+1. close
+2. data
+3. end
+4. error
+5. pause
+6. readable
+7. resumeaddListener(event, listener) =>
event
"data"
listener
(chunk) any#
chunk
listener(chunk) =>
addListener(event, listener) =>
event
"end"
listener
()
listener() =>
addListener(event, listener) =>
event
"error"
listener
(err) Error#
err
listener(err) =>
addListener(event, listener) =>
event
"pause"
listener
()
listener() =>
addListener(event, listener) =>
event
"readable"
listener
()
listener() =>
addListener(event, listener) =>
event
"resume"
listener
()
listener() =>
addListener(event, listener) =>
event
string | symbol
listener
(args) any []#
args
listener(args) =>
addListener(event, listener) =>
destroy
(error) – Calls destroy()
on the socket that received the IncomingMessage
. If error
is provided, an 'error'
event is emitted on the socket and error
is passed
+as an argument to any listeners on the event. Error#
error
destroy(error) =>
emit
(event) – Synchronously calls each of the listeners registered for the event namedeventName
, in the order they were registered, passing the supplied arguments
+to each.
+ +Returns `true` if the event had listeners, `false` otherwise. + +```js +const EventEmitter = require('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 +``` + +
+event
"close"
emit(event) =>
event
"data"
chunk
any
emit(event, chunk) =>
event
"end"
emit(event) =>
event
"error"
err
Error
emit(event, err) =>
event
"pause"
emit(event) =>
event
"readable"
emit(event) =>
event
"resume"
emit(event) =>
event
string | symbol
args
any []
emit(event, args) =>
eventNames
() – Returns an array listing the events for which the emitter has registered
+listeners. The values in the array are strings or Symbol
s.
+ +```js +const EventEmitter = require('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) ] +``` + +
+eventNames() =>
getMaxListeners
() – Returns the current max listener value for the EventEmitter
which is either
+set by emitter.setMaxListeners(n)
or defaults to {@link defaultMaxListeners}.
getMaxListeners() =>
isPaused
() – The readable.isPaused()
method returns the current operating state of theReadable
. This is used primarily by the mechanism that underlies thereadable.pipe()
method. In most
+typical cases, there will be no reason to
+use this method directly.
+ +```js +const readable = new stream.Readable() + +readable.isPaused() // === false +readable.pause() +readable.isPaused() // === true +readable.resume() +readable.isPaused() // === false +``` + +
+isPaused() =>
listenerCount
(eventName) – Returns the number of listeners listening to the event named eventName
. string | symbol#
eventName
– The name of the event being listened for
+
listenerCount(eventName) =>
listeners
(eventName) – Returns a copy of the array of listeners for the event named eventName
.
+ +```js +server.on('connection', stream => { + console.log('someone connected!') +}) +console.log(util.inspect(server.listeners('connection'))) +// Prints: [ [Function] ] +``` + +
+eventName
string | symbol
listeners(eventName) =>
off
(eventName, listener) – Alias for emitter.removeListener()
. string | symbol#
eventName
off(eventName, listener) =>
on
(event, listener) – 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.
+ +```js +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. + +```js +const myEE = new EventEmitter() +myEE.on('foo', () => console.log('a')) +myEE.prependListener('foo', () => console.log('b')) +myEE.emit('foo') +// Prints: +// b +// a +``` + +
+event
"close"
listener
()
listener() =>
on(event, listener) =>
event
"data"
listener
(chunk) any#
chunk
listener(chunk) =>
on(event, listener) =>
event
"end"
listener
()
listener() =>
on(event, listener) =>
event
"error"
listener
(err) Error#
err
listener(err) =>
on(event, listener) =>
event
"pause"
listener
()
listener() =>
on(event, listener) =>
event
"readable"
listener
()
listener() =>
on(event, listener) =>
event
"resume"
listener
()
listener() =>
on(event, listener) =>
event
string | symbol
listener
(args) any []#
args
listener(args) =>
on(event, listener) =>
once
(event, listener) – Adds a one-timelistener
function for the event named eventName
. The
+next time eventName
is triggered, this listener is removed and then invoked.
+ +```js +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. + +```js +const myEE = new EventEmitter() +myEE.once('foo', () => console.log('a')) +myEE.prependOnceListener('foo', () => console.log('b')) +myEE.emit('foo') +// Prints: +// b +// a +``` + +
+event
"close"
listener
()
listener() =>
once(event, listener) =>
event
"data"
listener
(chunk) any#
chunk
listener(chunk) =>
once(event, listener) =>
event
"end"
listener
()
listener() =>
once(event, listener) =>
event
"error"
listener
(err) Error#
err
listener(err) =>
once(event, listener) =>
event
"pause"
listener
()
listener() =>
once(event, listener) =>
event
"readable"
listener
()
listener() =>
once(event, listener) =>
event
"resume"
listener
()
listener() =>
once(event, listener) =>
event
string | symbol
listener
(args) any []#
args
listener(args) =>
once(event, listener) =>
pause
() – The readable.pause()
method will cause a stream in flowing mode to stop
+emitting 'data'
events, switching out of flowing mode. Any data that
+becomes available will remain in the internal buffer.
+ +```js +const readable = getReadableStreamSomehow() +readable.on('data', chunk => { + console.log(`Received ${chunk.length} bytes of data.`) + readable.pause() + console.log('There will be no additional data for 1 second.') + setTimeout(() => { + console.log('Now data will start flowing again.') + readable.resume() + }, 1000) +}) +``` + +The `readable.pause()` method has no effect if there is a `'readable'`event listener. + +
+pause() =>
pipe
(destination, { end }) { #
options
pipe<T extends WritableStream<T>>(destination, { end }) =>
prependListener
(event, listener) – 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.
+ +```js +server.prependListener('connection', stream => { + console.log('someone connected!') +}) +``` + +Returns a reference to the `EventEmitter`, so that calls can be chained. + +
+event
"close"
listener
()
listener() =>
prependListener(event, listener) =>
event
"data"
listener
(chunk) any#
chunk
listener(chunk) =>
prependListener(event, listener) =>
event
"end"
listener
()
listener() =>
prependListener(event, listener) =>
event
"error"
listener
(err) Error#
err
listener(err) =>
prependListener(event, listener) =>
event
"pause"
listener
()
listener() =>
prependListener(event, listener) =>
event
"readable"
listener
()
listener() =>
prependListener(event, listener) =>
event
"resume"
listener
()
listener() =>
prependListener(event, listener) =>
event
string | symbol
listener
(args) any []#
args
listener(args) =>
prependListener(event, listener) =>
prependOnceListener
(event, listener) – Adds a one-timelistener
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.
+ +```js +server.prependOnceListener('connection', stream => { + console.log('Ah, we have our first user!') +}) +``` + +Returns a reference to the `EventEmitter`, so that calls can be chained. + +
+event
"close"
listener
()
listener() =>
prependOnceListener(event, listener) =>
event
"data"
listener
(chunk) any#
chunk
listener(chunk) =>
prependOnceListener(event, listener) =>
event
"end"
listener
()
listener() =>
prependOnceListener(event, listener) =>
event
"error"
listener
(err) Error#
err
listener(err) =>
prependOnceListener(event, listener) =>
event
"pause"
listener
()
listener() =>
prependOnceListener(event, listener) =>
event
"readable"
listener
()
listener() =>
prependOnceListener(event, listener) =>
event
"resume"
listener
()
listener() =>
prependOnceListener(event, listener) =>
event
string | symbol
listener
(args) any []#
args
listener(args) =>
prependOnceListener(event, listener) =>
push
(chunk, encoding) push(chunk, encoding) =>
rawListeners
(eventName) – Returns a copy of the array of listeners for the event named eventName
,
+including any wrappers (such as those created by .once()
).
+ +```js +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') +``` + +
+eventName
string | symbol
rawListeners(eventName) =>
read
(size) – The readable.read()
method pulls some data out of the internal buffer and
+returns it. If no data available to be read, null
is returned. By default,
+the data will be returned as a Buffer
object unless an encoding has been
+specified using the readable.setEncoding()
method or the stream is operating
+in object mode.
+ +The optional `size` argument specifies a specific number of bytes to read. If`size` bytes are not available to be read, `null` will be returned _unless_the stream has ended, in which +case all of the data remaining in the internal +buffer will be returned. + +If the `size` argument is not specified, all of the data contained in the +internal buffer will be returned. + +The `size` argument must be less than or equal to 1 GiB. + +The `readable.read()` method should only be called on `Readable` streams +operating in paused mode. In flowing mode, `readable.read()` is called +automatically until the internal buffer is fully drained. + +```js +const readable = getReadableStreamSomehow() + +// 'readable' may be triggered multiple times as data is buffered in +readable.on('readable', () => { + let chunk + console.log('Stream is readable (new data received in buffer)') + // Use a loop to make sure we read all currently available data + while (null !== (chunk = readable.read())) { + console.log(`Read ${chunk.length} bytes of data...`) + } +}) + +// 'end' will be triggered once when there is no more data available +readable.on('end', () => { + console.log('Reached end of stream.') +}) +``` + +Each call to `readable.read()` returns a chunk of data, or `null`. The chunks +are not concatenated. A `while` loop is necessary to consume all data +currently in the buffer. When reading a large file `.read()` may return `null`, +having consumed all buffered content so far, but there is still more data to +come not yet buffered. In this case a new `'readable'` event will be emitted +when there is more data in the buffer. Finally the `'end'` event will be +emitted when there is no more data to come. + +Therefore to read a file's whole contents from a `readable`, it is necessary +to collect chunks across multiple `'readable'` events: + +```js +const chunks = [] + +readable.on('readable', () => { + let chunk + while (null !== (chunk = readable.read())) { + chunks.push(chunk) + } +}) + +readable.on('end', () => { + const content = chunks.join('') +}) +``` + +A `Readable` stream in object mode will always return a single item from +a call to `readable.read(size)`, regardless of the value of the`size` argument. + +If the `readable.read()` method returns a chunk of data, a `'data'` event will +also be emitted. + +Calling {@link read} after the `'end'` event has +been emitted will return `null`. No runtime error will be raised. + +
+size
– Optional argument to specify how much data to read.
+number
read(size) =>
removeAllListeners
(event) – 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. + +
+event
string | symbol
removeAllListeners(event) =>
removeListener
(event, listener) – Removes the specified listener
from the listener array for the event namedeventName
.
+ +```js +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. + +```js +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 indices 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: + +```js +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. + +
+event
"close"
listener
()
listener() =>
removeListener(event, listener) =>
event
"data"
listener
(chunk) any#
chunk
listener(chunk) =>
removeListener(event, listener) =>
event
"end"
listener
()
listener() =>
removeListener(event, listener) =>
event
"error"
listener
(err) Error#
err
listener(err) =>
removeListener(event, listener) =>
event
"pause"
listener
()
listener() =>
removeListener(event, listener) =>
event
"readable"
listener
()
listener() =>
removeListener(event, listener) =>
event
"resume"
listener
()
listener() =>
removeListener(event, listener) =>
event
string | symbol
listener
(args) any []#
args
listener(args) =>
removeListener(event, listener) =>
resume
() – The readable.resume()
method causes an explicitly paused Readable
stream to
+resume emitting 'data'
events, switching the stream into flowing mode.
+ +The `readable.resume()` method can be used to fully consume the data from a +stream without actually processing any of that data: + +```js +getReadableStreamSomehow() + .resume() + .on('end', () => { + console.log('Reached the end, but did not read anything.') + }) +``` + +The `readable.resume()` method has no effect if there is a `'readable'`event listener. + +
+resume() =>
setEncoding
(encoding) – The readable.setEncoding()
method sets the character encoding for
+data read from the Readable
stream.
+ +By default, no encoding is assigned and stream data will be returned as`Buffer` objects. Setting an encoding causes the stream data +to be returned as strings of the specified encoding rather than as `Buffer`objects. For instance, calling `readable.setEncoding('utf8')` will cause the +output data to be interpreted as UTF-8 data, and passed as strings. Calling`readable.setEncoding('hex')` will cause the data to be encoded in hexadecimal +string format. + +The `Readable` stream will properly handle multi-byte characters delivered +through the stream that would otherwise become improperly decoded if simply +pulled from the stream as `Buffer` objects. + +```js +const readable = getReadableStreamSomehow() +readable.setEncoding('utf8') +readable.on('data', chunk => { + assert.equal(typeof chunk, 'string') + console.log('Got %d characters of string data:', chunk.length) +}) +``` + +
+encoding
– The encoding to use.
+setEncoding(encoding) =>
setMaxListeners
(n) – By default EventEmitter
s 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 toInfinity
(or 0
) to indicate an unlimited number of listeners.
+ +Returns a reference to the `EventEmitter`, so that calls can be chained. + +
+n
number
setMaxListeners(n) =>
setTimeout
(msecs, callback) – Calls message.socket.setTimeout(msecs, callback)
.setTimeout(msecs, callback) =>
unpipe
(destination) – The readable.unpipe()
method detaches a Writable
stream previously attached
+using the {@link pipe} method.
+ +If the `destination` is not specified, then _all_ pipes are detached. + +If the `destination` is specified, but no pipe is set up for it, then +the method does nothing. + +```js +const fs = require('fs') +const readable = getReadableStreamSomehow() +const writable = fs.createWriteStream('file.txt') +// All the data from readable goes into 'file.txt', +// but only for the first second. +readable.pipe(writable) +setTimeout(() => { + console.log('Stop writing to file.txt.') + readable.unpipe(writable) + console.log('Manually close the file stream.') + writable.end() +}, 1000) +``` + +
+destination
– Optional specific stream to unpipe
+unpipe(destination) =>
unshift
(chunk, encoding) – Passing chunk
as null
signals the end of the stream (EOF) and behaves the
+same as readable.push(null)
, after which no more data can be written. The EOF
+signal is put at the end of the buffer and any buffered data will still be
+flushed.
+ +The `readable.unshift()` method pushes a chunk of data back into the internal +buffer. This is useful in certain situations where a stream is being consumed by +code that needs to "un-consume" some amount of data that it has optimistically +pulled out of the source, so that the data can be passed on to some other party. + +The `stream.unshift(chunk)` method cannot be called after the `'end'` event +has been emitted or a runtime error will be thrown. + +Developers using `stream.unshift()` often should consider switching to +use of a `Transform` stream instead. See the `API for stream implementers` section for more information. + +```js +// Pull off a header delimited by \n\n. +// Use unshift() if we get too much. +// Call the callback with (error, header, stream). +const { StringDecoder } = require('string_decoder') +function parseHeader(stream, callback) { + stream.on('error', callback) + stream.on('readable', onReadable) + const decoder = new StringDecoder('utf8') + let header = '' + function onReadable() { + let chunk + while (null !== (chunk = stream.read())) { + const str = decoder.write(chunk) + if (str.match(/\n\n/)) { + // Found the header boundary. + const split = str.split(/\n\n/) + header += split.shift() + const remaining = split.join('\n\n') + const buf = Buffer.from(remaining, 'utf8') + stream.removeListener('error', callback) + // Remove the 'readable' listener before unshifting. + stream.removeListener('readable', onReadable) + if (buf.length) + stream.unshift(buf) + // Now the body of the message can be read from the stream. + callback(null, header, stream) + } else { + // Still reading the header. + header += str + } + } + } +} +``` + +Unlike {@link push}, `stream.unshift(chunk)` will not +end the reading process by resetting the internal reading state of the stream. +This can cause unexpected results if `readable.unshift()` is called during a +read (i.e. from within a {@link _read} implementation on a +custom stream). Following the call to `readable.unshift()` with an immediate {@link push} will reset the reading state appropriately, +however it is best to simply avoid calling `readable.unshift()` while in the +process of performing a read. + +
+chunk
– Chunk of data to unshift onto the read queue. For streams not operating in object mode, chunk
must be a string, Buffer
, Uint8Array
or null
. For object mode
+streams, chunk
may be any JavaScript value.any
encoding
– Encoding of string chunks. Must be a valid Buffer
encoding, such as 'utf8'
or 'ascii'
.
+unshift(chunk, encoding) =>
wrap
(stream) – Prior to Node.js 0.10, streams did not implement the entire stream
module API
+as it is currently defined. (See Compatibility
for more information.)
+ +When using an older Node.js library that emits `'data'` events and has a {@link pause} method that is advisory only, the`readable.wrap()` method can be used to create a `Readable` +stream that uses +the old stream as its data source. + +It will rarely be necessary to use `readable.wrap()` but the method has been +provided as a convenience for interacting with older Node.js applications and +libraries. + +```js +const { OldReader } = require('./old-api-module.js') +const { Readable } = require('stream') +const oreader = new OldReader() +const myReader = new Readable().wrap(oreader) + +myReader.on('readable', () => { + myReader.read() // etc. +}) +``` + +
+stream
– An "old style" readable stream
+wrap(stream) =>
from
(iterable, options) – A utility method for creating Readable Streams out of iterators.getEventListeners
(emitter, name) – Returns a copy of the array of listeners for the event named eventName
.
+ +For `EventEmitter`s this behaves exactly the same as calling `.listeners` on +the emitter. + +For `EventTarget`s this is the only way to get the event listeners for the +event target. This is useful for debugging and diagnostic purposes. + +```js +const { getEventListeners, EventEmitter } = require('events') + +{ + const ee = new EventEmitter() + const listener = () => console.log('Events are fun') + ee.on('foo', listener) + getEventListeners(ee, 'foo') // [listener] +} +{ + const et = new EventTarget() + const listener = () => console.log('Events are fun') + et.addEventListener('foo', listener) + getEventListeners(et, 'foo') // [listener] +} +``` + +
+emitter
name
string | symbol
getEventListeners(emitter, name) =>
isDisturbed
(stream) – Returns whether the stream has been read from or cancelled. #
stream
isDisturbed(stream) =>
listenerCount
(emitter, eventName) – A class method that returns the number of listeners for the given eventName
registered on the given emitter
.
+ +```js +const { EventEmitter, listenerCount } = require('events') +const myEmitter = new EventEmitter() +myEmitter.on('event', () => {}) +myEmitter.on('event', () => {}) +console.log(listenerCount(myEmitter, 'event')) +// Prints: 2 +``` + +
+emitter
– The emitter to queryeventName
– The event name
+string | symbol
listenerCount(emitter, eventName) =>
on
(emitter, eventName, options) – ```js
+const { on, EventEmitter } = require('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: + +```js +const { on, EventEmitter } = require('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()); +```` + +
+emitter
eventName
– The name of the event being listened forstring
options
on(emitter, eventName, options) =>
once
(emitter, eventName, options) – 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](https://dom.spec.whatwg.org/#interface-eventtarget) interface, which has no special`'error'` event +semantics and does not listen to the `'error'` event. + +```js +const { once, EventEmitter } = require('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.log('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: + +```js +const { EventEmitter, once } = require('events') + +const ee = new EventEmitter() + +once(ee, 'error') + .then(([err]) => console.log('ok', err.message)) + .catch(err => console.log('error', err.message)) + +ee.emit('error', new Error('boom')) + +// Prints: ok boom +``` + +An `AbortSignal` can be used to cancel waiting for the event: + +```js +const { EventEmitter, once } = require('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() // Abort waiting for the event +ee.emit('foo') // Prints: Waiting for the event was canceled! +``` + +
+emitter
eventName
string | symbol
options
once(emitter, eventName, options) =>
emitter
eventName
string
options
once(emitter, eventName, options) =>
setMaxListeners
(n, eventTargets) – By default EventEmitter
s 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 EventEmitter.setMaxListeners()
method allows the default limit to be
+modified (if eventTargets is empty) or modify the limit specified in every EventTarget
| EventEmitter
passed as arguments.
+The value can be set toInfinity
(or 0
) to indicate an unlimited number of listeners.
+ +```js +EventEmitter.setMaxListeners(20) +// Equivalent to +EventEmitter.defaultMaxListeners = 20 + +const eventTarget = new EventTarget() +// Only way to increase limit for `EventTarget` instances +// as these doesn't expose its own `setMaxListeners` method +EventEmitter.setMaxListeners(20, eventTarget) +``` + +
+n
number
eventTargets
setMaxListeners(n, eventTargets) =>
IncomingMessage
– An IncomingMessage
object is created by {@link Server} or {@link ClientRequest} and passed as the first argument to the 'request'
and 'response'
event respectively. It may be used to
+access response
+status, headers and data.+ +Different from its `socket` value which is a subclass of `stream.Duplex`, the`IncomingMessage` itself extends `stream.Readable` and is created separately to +parse and emit the incoming HTTP headers and payload, as the underlying socket +may be reused multiple times in case of keep-alive. + +
+ boolean boolean
+
+This property is particularly useful as a means of determining if a client or
+server fully transmitted a message before a connection was terminated:
+
+```js
+const req = http.request({
+ host: '127.0.0.1',
+ port: 8080,
+ method: 'POST',
+}, res => {
+ res.resume()
+ res.on('end', () => {
+ if (!res.complete)
+ console.error(
+ 'The connection was terminated while the message was still being sent'
+ )
+ })
+})
+```
+
+ boolean
+
+Key-value pairs of header names and values. Header names are lower-cased.
+
+```js
+// Prints something like:
+//
+// { 'user-agent': 'curl/7.22.0',
+// host: '127.0.0.1:8000',
+// accept: '*' }
+console.log(request.headers)
+```
+
+Duplicates in raw headers are handled in the following ways, depending on the
+header name:
+
+- Duplicates of `age`, `authorization`, `content-length`, `content-type`,`etag`, `expires`, `from`, `host`, `if-modified-since`, `if-unmodified-since`,`last-modified`, `location`,
+ `max-forwards`, `proxy-authorization`, `referer`,`retry-after`, `server`, or `user-agent` are discarded.
+- `set-cookie` is always an array. Duplicates are added to the array.
+- For duplicate `cookie` headers, the values are joined together with '; '.
+- For all other headers, the values are joined together with ', '.
+
+ string
+
+Also `message.httpVersionMajor` is the first integer and`message.httpVersionMinor` is the second.
+
+ string
+
+The request method as a string. Read only. Examples: `'GET'`, `'DELETE'`.
+
+ string []
+
+The keys and values are in the same list. It is _not_ a
+list of tuples. So, the even-numbered offsets are key values, and the
+odd-numbered offsets are the associated values.
+
+Header names are not lowercased, and duplicates are not merged.
+
+```js
+// Prints something like:
+//
+// [ 'user-agent',
+// 'this is invalid because there can be only one',
+// 'User-Agent',
+// 'curl/7.22.0',
+// 'Host',
+// '127.0.0.1:8000',
+// 'ACCEPT',
+// '*' ]
+console.log(request.rawHeaders)
+```
+
+ string [] boolean boolean boolean boolean number number boolean
+
+With HTTPS support, use `request.socket.getPeerCertificate()` to obtain the
+client's authentication details.
+
+This property is guaranteed to be an instance of the `net.Socket` class,
+a subclass of `stream.Duplex`, unless the user specified a socket
+type other than `net.Socket`.
+
+ number
+
+The 3-digit HTTP response status code. E.G. `404`.
+
+ string
+
+The HTTP response status message (reason phrase). E.G. `OK` or `Internal Server Error`.
+
+ Dict<string> string
+
+Request URL string. This contains only the URL that is present in the actual
+HTTP request. Take the following request:
+
+```http
+GET /status?name=ryan HTTP/1.1
+Accept: text/plain
+```
+
+To parse the URL into its parts:
+
+```js
+new URL(request.url, `http://${request.headers.host}`)
+```
+
+When `request.url` is `'/status?name=ryan'` and`request.headers.host` is `'localhost:3000'`:
+
+```console
+$ node
+> new URL(request.url, `http://${request.headers.host}`)
+URL {
+ href: 'http://localhost:3000/status?name=ryan',
+ origin: 'http://localhost:3000',
+ protocol: 'http:',
+ username: '',
+ password: '',
+ host: 'localhost:3000',
+ hostname: 'localhost',
+ port: '3000',
+ pathname: '/status',
+ search: '?name=ryan',
+ searchParams: URLSearchParams { 'name' => 'ryan' },
+ hash: ''
+}
+```
+
+ typeof captureRejectionSymbol boolean typeof errorMonitor
+
+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.
+
+ [asyncIterator]() => #
src/.fastpm/-/@types/node@17.0.45/http.d.ts#L793 aborted
– The message.aborted
property will be true
if the request has
+been aborted.#
src/.fastpm/-/@types/node@17.0.45/http.d.ts#L828 complete
– The message.complete
property will be true
if a complete HTTP message has
+been received and successfully parsed.#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L115 destroyed
– Is true
after readable.destroy()
has been called.#
src/.fastpm/-/@types/node@17.0.45/http.d.ts#L871 headers
– The request/response headers object.
#
src/.fastpm/-/@types/node@17.0.45/http.d.ts#L802 httpVersion
– In case of server request, the HTTP version sent by the client. In the case of
+client response, the HTTP version of the connected-to server.
+Probably either '1.1'
or '1.0'
.#
src/.fastpm/-/@types/node@17.0.45/http.d.ts#L919 method
– Only valid for request obtained from {@link Server}.#
src/.fastpm/-/@types/node@17.0.45/http.d.ts#L896 rawHeaders
– The raw request/response headers list exactly as they were received.#
src/.fastpm/-/@types/node@17.0.45/http.d.ts#L907 rawTrailers
– The raw request/response trailer keys and values exactly as they were
+received. Only populated at the 'end'
event.#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L71 readable
– Is true
if it is safe to call readable.read()
, which means
+the stream has not been destroyed or emitted 'error'
or 'end'
.#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L65 readableAborted
– Returns whether the stream was destroyed or errored before emitting 'end'
.#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L77 readableDidRead
– Returns whether 'data'
has been emitted.#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L82 readableEncoding
– Getter for the property encoding
of a given Readable
stream. The encoding
property can be set using the readable.setEncoding()
method.null
| BufferEncoding#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L87 readableEnded
– Becomes true
when 'end'
event is emitted.#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L93 readableFlowing
– This property reflects the current state of a Readable
stream as described
+in the Three states
section.null
| boolean#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L98 readableHighWaterMark
– Returns the value of highWaterMark
passed when creating this Readable
.#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L105 readableLength
– This property contains the number of bytes (or objects) in the queue
+ready to be read. The value provides introspection data regarding
+the status of the highWaterMark
.#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L110 readableObjectMode
– Getter for the property objectMode
of a given Readable
stream.#
src/.fastpm/-/@types/node@17.0.45/http.d.ts#L846 socket
– The net.Socket
object associated with the connection.
#
src/.fastpm/-/@types/node@17.0.45/http.d.ts#L966 statusCode
– Only valid for response obtained from {@link ClientRequest}.#
src/.fastpm/-/@types/node@17.0.45/http.d.ts#L973 statusMessage
– Only valid for response obtained from {@link ClientRequest}.#
src/.fastpm/-/@types/node@17.0.45/http.d.ts#L901 trailers
– The request/response trailers object. Only populated at the 'end'
event.#
src/.fastpm/-/@types/node@17.0.45/http.d.ts#L959 url
– Only valid for request obtained from {@link Server}.#
src/.fastpm/-/@types/node@17.0.45/events.d.ts#L301 captureRejectionSymbol
#
src/.fastpm/-/@types/node@17.0.45/events.d.ts#L306 captureRejections
– Sets or gets the default captureRejection value for all emitters.#
src/.fastpm/-/@types/node@17.0.45/events.d.ts#L300 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.#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L479 [asyncIterator]
()
AsyncIterableIterator<any>
_construct
(callback)
_construct(callback) =>
_destroy
(error, callback) #
error
null
| Error
_destroy(error, callback) =>
_read
(size) number#
size
_read(size) =>
addListener
(event, listener) – Event emitter
+The defined events on documents including:
+1. close
+2. data
+3. end
+4. error
+5. pause
+6. readable
+7. resumeaddListener(event, listener) =>
event
"data"
listener
(chunk) any#
chunk
listener(chunk) =>
addListener(event, listener) =>
event
"end"
listener
()
listener() =>
addListener(event, listener) =>
event
"error"
listener
(err) Error#
err
listener(err) =>
addListener(event, listener) =>
event
"pause"
listener
()
listener() =>
addListener(event, listener) =>
event
"readable"
listener
()
listener() =>
addListener(event, listener) =>
event
"resume"
listener
()
listener() =>
addListener(event, listener) =>
event
string | symbol
listener
(args) any []#
args
listener(args) =>
addListener(event, listener) =>
destroy
(error) – Calls destroy()
on the socket that received the IncomingMessage
. If error
is provided, an 'error'
event is emitted on the socket and error
is passed
+as an argument to any listeners on the event. Error#
error
destroy(error) =>
emit
(event) – Synchronously calls each of the listeners registered for the event namedeventName
, in the order they were registered, passing the supplied arguments
+to each.
+ +Returns `true` if the event had listeners, `false` otherwise. + +```js +const EventEmitter = require('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 +``` + +
+event
"close"
emit(event) =>
event
"data"
chunk
any
emit(event, chunk) =>
event
"end"
emit(event) =>
event
"error"
err
Error
emit(event, err) =>
event
"pause"
emit(event) =>
event
"readable"
emit(event) =>
event
"resume"
emit(event) =>
event
string | symbol
args
any []
emit(event, args) =>
eventNames
() – Returns an array listing the events for which the emitter has registered
+listeners. The values in the array are strings or Symbol
s.
+ +```js +const EventEmitter = require('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) ] +``` + +
+eventNames() =>
getMaxListeners
() – Returns the current max listener value for the EventEmitter
which is either
+set by emitter.setMaxListeners(n)
or defaults to {@link defaultMaxListeners}.
getMaxListeners() =>
isPaused
() – The readable.isPaused()
method returns the current operating state of theReadable
. This is used primarily by the mechanism that underlies thereadable.pipe()
method. In most
+typical cases, there will be no reason to
+use this method directly.
+ +```js +const readable = new stream.Readable() + +readable.isPaused() // === false +readable.pause() +readable.isPaused() // === true +readable.resume() +readable.isPaused() // === false +``` + +
+isPaused() =>
listenerCount
(eventName) – Returns the number of listeners listening to the event named eventName
. string | symbol#
eventName
– The name of the event being listened for
+
listenerCount(eventName) =>
listeners
(eventName) – Returns a copy of the array of listeners for the event named eventName
.
+ +```js +server.on('connection', stream => { + console.log('someone connected!') +}) +console.log(util.inspect(server.listeners('connection'))) +// Prints: [ [Function] ] +``` + +
+eventName
string | symbol
listeners(eventName) =>
off
(eventName, listener) – Alias for emitter.removeListener()
. string | symbol#
eventName
off(eventName, listener) =>
on
(event, listener) – 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.
+ +```js +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. + +```js +const myEE = new EventEmitter() +myEE.on('foo', () => console.log('a')) +myEE.prependListener('foo', () => console.log('b')) +myEE.emit('foo') +// Prints: +// b +// a +``` + +
+event
"close"
listener
()
listener() =>
on(event, listener) =>
event
"data"
listener
(chunk) any#
chunk
listener(chunk) =>
on(event, listener) =>
event
"end"
listener
()
listener() =>
on(event, listener) =>
event
"error"
listener
(err) Error#
err
listener(err) =>
on(event, listener) =>
event
"pause"
listener
()
listener() =>
on(event, listener) =>
event
"readable"
listener
()
listener() =>
on(event, listener) =>
event
"resume"
listener
()
listener() =>
on(event, listener) =>
event
string | symbol
listener
(args) any []#
args
listener(args) =>
on(event, listener) =>
once
(event, listener) – Adds a one-timelistener
function for the event named eventName
. The
+next time eventName
is triggered, this listener is removed and then invoked.
+ +```js +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. + +```js +const myEE = new EventEmitter() +myEE.once('foo', () => console.log('a')) +myEE.prependOnceListener('foo', () => console.log('b')) +myEE.emit('foo') +// Prints: +// b +// a +``` + +
+event
"close"
listener
()
listener() =>
once(event, listener) =>
event
"data"
listener
(chunk) any#
chunk
listener(chunk) =>
once(event, listener) =>
event
"end"
listener
()
listener() =>
once(event, listener) =>
event
"error"
listener
(err) Error#
err
listener(err) =>
once(event, listener) =>
event
"pause"
listener
()
listener() =>
once(event, listener) =>
event
"readable"
listener
()
listener() =>
once(event, listener) =>
event
"resume"
listener
()
listener() =>
once(event, listener) =>
event
string | symbol
listener
(args) any []#
args
listener(args) =>
once(event, listener) =>
pause
() – The readable.pause()
method will cause a stream in flowing mode to stop
+emitting 'data'
events, switching out of flowing mode. Any data that
+becomes available will remain in the internal buffer.
+ +```js +const readable = getReadableStreamSomehow() +readable.on('data', chunk => { + console.log(`Received ${chunk.length} bytes of data.`) + readable.pause() + console.log('There will be no additional data for 1 second.') + setTimeout(() => { + console.log('Now data will start flowing again.') + readable.resume() + }, 1000) +}) +``` + +The `readable.pause()` method has no effect if there is a `'readable'`event listener. + +
+pause() =>
pipe
(destination, { end }) { #
options
pipe<T extends WritableStream<T>>(destination, { end }) =>
prependListener
(event, listener) – 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.
+ +```js +server.prependListener('connection', stream => { + console.log('someone connected!') +}) +``` + +Returns a reference to the `EventEmitter`, so that calls can be chained. + +
+event
"close"
listener
()
listener() =>
prependListener(event, listener) =>
event
"data"
listener
(chunk) any#
chunk
listener(chunk) =>
prependListener(event, listener) =>
event
"end"
listener
()
listener() =>
prependListener(event, listener) =>
event
"error"
listener
(err) Error#
err
listener(err) =>
prependListener(event, listener) =>
event
"pause"
listener
()
listener() =>
prependListener(event, listener) =>
event
"readable"
listener
()
listener() =>
prependListener(event, listener) =>
event
"resume"
listener
()
listener() =>
prependListener(event, listener) =>
event
string | symbol
listener
(args) any []#
args
listener(args) =>
prependListener(event, listener) =>
prependOnceListener
(event, listener) – Adds a one-timelistener
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.
+ +```js +server.prependOnceListener('connection', stream => { + console.log('Ah, we have our first user!') +}) +``` + +Returns a reference to the `EventEmitter`, so that calls can be chained. + +
+event
"close"
listener
()
listener() =>
prependOnceListener(event, listener) =>
event
"data"
listener
(chunk) any#
chunk
listener(chunk) =>
prependOnceListener(event, listener) =>
event
"end"
listener
()
listener() =>
prependOnceListener(event, listener) =>
event
"error"
listener
(err) Error#
err
listener(err) =>
prependOnceListener(event, listener) =>
event
"pause"
listener
()
listener() =>
prependOnceListener(event, listener) =>
event
"readable"
listener
()
listener() =>
prependOnceListener(event, listener) =>
event
"resume"
listener
()
listener() =>
prependOnceListener(event, listener) =>
event
string | symbol
listener
(args) any []#
args
listener(args) =>
prependOnceListener(event, listener) =>
push
(chunk, encoding) push(chunk, encoding) =>
rawListeners
(eventName) – Returns a copy of the array of listeners for the event named eventName
,
+including any wrappers (such as those created by .once()
).
+ +```js +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') +``` + +
+eventName
string | symbol
rawListeners(eventName) =>
read
(size) – The readable.read()
method pulls some data out of the internal buffer and
+returns it. If no data available to be read, null
is returned. By default,
+the data will be returned as a Buffer
object unless an encoding has been
+specified using the readable.setEncoding()
method or the stream is operating
+in object mode.
+ +The optional `size` argument specifies a specific number of bytes to read. If`size` bytes are not available to be read, `null` will be returned _unless_the stream has ended, in which +case all of the data remaining in the internal +buffer will be returned. + +If the `size` argument is not specified, all of the data contained in the +internal buffer will be returned. + +The `size` argument must be less than or equal to 1 GiB. + +The `readable.read()` method should only be called on `Readable` streams +operating in paused mode. In flowing mode, `readable.read()` is called +automatically until the internal buffer is fully drained. + +```js +const readable = getReadableStreamSomehow() + +// 'readable' may be triggered multiple times as data is buffered in +readable.on('readable', () => { + let chunk + console.log('Stream is readable (new data received in buffer)') + // Use a loop to make sure we read all currently available data + while (null !== (chunk = readable.read())) { + console.log(`Read ${chunk.length} bytes of data...`) + } +}) + +// 'end' will be triggered once when there is no more data available +readable.on('end', () => { + console.log('Reached end of stream.') +}) +``` + +Each call to `readable.read()` returns a chunk of data, or `null`. The chunks +are not concatenated. A `while` loop is necessary to consume all data +currently in the buffer. When reading a large file `.read()` may return `null`, +having consumed all buffered content so far, but there is still more data to +come not yet buffered. In this case a new `'readable'` event will be emitted +when there is more data in the buffer. Finally the `'end'` event will be +emitted when there is no more data to come. + +Therefore to read a file's whole contents from a `readable`, it is necessary +to collect chunks across multiple `'readable'` events: + +```js +const chunks = [] + +readable.on('readable', () => { + let chunk + while (null !== (chunk = readable.read())) { + chunks.push(chunk) + } +}) + +readable.on('end', () => { + const content = chunks.join('') +}) +``` + +A `Readable` stream in object mode will always return a single item from +a call to `readable.read(size)`, regardless of the value of the`size` argument. + +If the `readable.read()` method returns a chunk of data, a `'data'` event will +also be emitted. + +Calling {@link read} after the `'end'` event has +been emitted will return `null`. No runtime error will be raised. + +
+size
– Optional argument to specify how much data to read.
+number
read(size) =>
removeAllListeners
(event) – 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. + +
+event
string | symbol
removeAllListeners(event) =>
removeListener
(event, listener) – Removes the specified listener
from the listener array for the event namedeventName
.
+ +```js +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. + +```js +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 indices 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: + +```js +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. + +
+event
"close"
listener
()
listener() =>
removeListener(event, listener) =>
event
"data"
listener
(chunk) any#
chunk
listener(chunk) =>
removeListener(event, listener) =>
event
"end"
listener
()
listener() =>
removeListener(event, listener) =>
event
"error"
listener
(err) Error#
err
listener(err) =>
removeListener(event, listener) =>
event
"pause"
listener
()
listener() =>
removeListener(event, listener) =>
event
"readable"
listener
()
listener() =>
removeListener(event, listener) =>
event
"resume"
listener
()
listener() =>
removeListener(event, listener) =>
event
string | symbol
listener
(args) any []#
args
listener(args) =>
removeListener(event, listener) =>
resume
() – The readable.resume()
method causes an explicitly paused Readable
stream to
+resume emitting 'data'
events, switching the stream into flowing mode.
+ +The `readable.resume()` method can be used to fully consume the data from a +stream without actually processing any of that data: + +```js +getReadableStreamSomehow() + .resume() + .on('end', () => { + console.log('Reached the end, but did not read anything.') + }) +``` + +The `readable.resume()` method has no effect if there is a `'readable'`event listener. + +
+resume() =>
setEncoding
(encoding) – The readable.setEncoding()
method sets the character encoding for
+data read from the Readable
stream.
+ +By default, no encoding is assigned and stream data will be returned as`Buffer` objects. Setting an encoding causes the stream data +to be returned as strings of the specified encoding rather than as `Buffer`objects. For instance, calling `readable.setEncoding('utf8')` will cause the +output data to be interpreted as UTF-8 data, and passed as strings. Calling`readable.setEncoding('hex')` will cause the data to be encoded in hexadecimal +string format. + +The `Readable` stream will properly handle multi-byte characters delivered +through the stream that would otherwise become improperly decoded if simply +pulled from the stream as `Buffer` objects. + +```js +const readable = getReadableStreamSomehow() +readable.setEncoding('utf8') +readable.on('data', chunk => { + assert.equal(typeof chunk, 'string') + console.log('Got %d characters of string data:', chunk.length) +}) +``` + +
+encoding
– The encoding to use.
+setEncoding(encoding) =>
setMaxListeners
(n) – By default EventEmitter
s 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 toInfinity
(or 0
) to indicate an unlimited number of listeners.
+ +Returns a reference to the `EventEmitter`, so that calls can be chained. + +
+n
number
setMaxListeners(n) =>
setTimeout
(msecs, callback) – Calls message.socket.setTimeout(msecs, callback)
.setTimeout(msecs, callback) =>
unpipe
(destination) – The readable.unpipe()
method detaches a Writable
stream previously attached
+using the {@link pipe} method.
+ +If the `destination` is not specified, then _all_ pipes are detached. + +If the `destination` is specified, but no pipe is set up for it, then +the method does nothing. + +```js +const fs = require('fs') +const readable = getReadableStreamSomehow() +const writable = fs.createWriteStream('file.txt') +// All the data from readable goes into 'file.txt', +// but only for the first second. +readable.pipe(writable) +setTimeout(() => { + console.log('Stop writing to file.txt.') + readable.unpipe(writable) + console.log('Manually close the file stream.') + writable.end() +}, 1000) +``` + +
+destination
– Optional specific stream to unpipe
+unpipe(destination) =>
unshift
(chunk, encoding) – Passing chunk
as null
signals the end of the stream (EOF) and behaves the
+same as readable.push(null)
, after which no more data can be written. The EOF
+signal is put at the end of the buffer and any buffered data will still be
+flushed.
+ +The `readable.unshift()` method pushes a chunk of data back into the internal +buffer. This is useful in certain situations where a stream is being consumed by +code that needs to "un-consume" some amount of data that it has optimistically +pulled out of the source, so that the data can be passed on to some other party. + +The `stream.unshift(chunk)` method cannot be called after the `'end'` event +has been emitted or a runtime error will be thrown. + +Developers using `stream.unshift()` often should consider switching to +use of a `Transform` stream instead. See the `API for stream implementers` section for more information. + +```js +// Pull off a header delimited by \n\n. +// Use unshift() if we get too much. +// Call the callback with (error, header, stream). +const { StringDecoder } = require('string_decoder') +function parseHeader(stream, callback) { + stream.on('error', callback) + stream.on('readable', onReadable) + const decoder = new StringDecoder('utf8') + let header = '' + function onReadable() { + let chunk + while (null !== (chunk = stream.read())) { + const str = decoder.write(chunk) + if (str.match(/\n\n/)) { + // Found the header boundary. + const split = str.split(/\n\n/) + header += split.shift() + const remaining = split.join('\n\n') + const buf = Buffer.from(remaining, 'utf8') + stream.removeListener('error', callback) + // Remove the 'readable' listener before unshifting. + stream.removeListener('readable', onReadable) + if (buf.length) + stream.unshift(buf) + // Now the body of the message can be read from the stream. + callback(null, header, stream) + } else { + // Still reading the header. + header += str + } + } + } +} +``` + +Unlike {@link push}, `stream.unshift(chunk)` will not +end the reading process by resetting the internal reading state of the stream. +This can cause unexpected results if `readable.unshift()` is called during a +read (i.e. from within a {@link _read} implementation on a +custom stream). Following the call to `readable.unshift()` with an immediate {@link push} will reset the reading state appropriately, +however it is best to simply avoid calling `readable.unshift()` while in the +process of performing a read. + +
+chunk
– Chunk of data to unshift onto the read queue. For streams not operating in object mode, chunk
must be a string, Buffer
, Uint8Array
or null
. For object mode
+streams, chunk
may be any JavaScript value.any
encoding
– Encoding of string chunks. Must be a valid Buffer
encoding, such as 'utf8'
or 'ascii'
.
+unshift(chunk, encoding) =>
wrap
(stream) – Prior to Node.js 0.10, streams did not implement the entire stream
module API
+as it is currently defined. (See Compatibility
for more information.)
+ +When using an older Node.js library that emits `'data'` events and has a {@link pause} method that is advisory only, the`readable.wrap()` method can be used to create a `Readable` +stream that uses +the old stream as its data source. + +It will rarely be necessary to use `readable.wrap()` but the method has been +provided as a convenience for interacting with older Node.js applications and +libraries. + +```js +const { OldReader } = require('./old-api-module.js') +const { Readable } = require('stream') +const oreader = new OldReader() +const myReader = new Readable().wrap(oreader) + +myReader.on('readable', () => { + myReader.read() // etc. +}) +``` + +
+stream
– An "old style" readable stream
+wrap(stream) =>
from
(iterable, options) – A utility method for creating Readable Streams out of iterators.getEventListeners
(emitter, name) – Returns a copy of the array of listeners for the event named eventName
.
+ +For `EventEmitter`s this behaves exactly the same as calling `.listeners` on +the emitter. + +For `EventTarget`s this is the only way to get the event listeners for the +event target. This is useful for debugging and diagnostic purposes. + +```js +const { getEventListeners, EventEmitter } = require('events') + +{ + const ee = new EventEmitter() + const listener = () => console.log('Events are fun') + ee.on('foo', listener) + getEventListeners(ee, 'foo') // [listener] +} +{ + const et = new EventTarget() + const listener = () => console.log('Events are fun') + et.addEventListener('foo', listener) + getEventListeners(et, 'foo') // [listener] +} +``` + +
+emitter
name
string | symbol
getEventListeners(emitter, name) =>
isDisturbed
(stream) – Returns whether the stream has been read from or cancelled. #
stream
isDisturbed(stream) =>
listenerCount
(emitter, eventName) – A class method that returns the number of listeners for the given eventName
registered on the given emitter
.
+ +```js +const { EventEmitter, listenerCount } = require('events') +const myEmitter = new EventEmitter() +myEmitter.on('event', () => {}) +myEmitter.on('event', () => {}) +console.log(listenerCount(myEmitter, 'event')) +// Prints: 2 +``` + +
+emitter
– The emitter to queryeventName
– The event name
+string | symbol
listenerCount(emitter, eventName) =>
on
(emitter, eventName, options) – ```js
+const { on, EventEmitter } = require('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: + +```js +const { on, EventEmitter } = require('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()); +```` + +
+emitter
eventName
– The name of the event being listened forstring
options
on(emitter, eventName, options) =>
once
(emitter, eventName, options) – 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](https://dom.spec.whatwg.org/#interface-eventtarget) interface, which has no special`'error'` event +semantics and does not listen to the `'error'` event. + +```js +const { once, EventEmitter } = require('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.log('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: + +```js +const { EventEmitter, once } = require('events') + +const ee = new EventEmitter() + +once(ee, 'error') + .then(([err]) => console.log('ok', err.message)) + .catch(err => console.log('error', err.message)) + +ee.emit('error', new Error('boom')) + +// Prints: ok boom +``` + +An `AbortSignal` can be used to cancel waiting for the event: + +```js +const { EventEmitter, once } = require('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() // Abort waiting for the event +ee.emit('foo') // Prints: Waiting for the event was canceled! +``` + +
+emitter
eventName
string | symbol
options
once(emitter, eventName, options) =>
emitter
eventName
string
options
once(emitter, eventName, options) =>
setMaxListeners
(n, eventTargets) – By default EventEmitter
s 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 EventEmitter.setMaxListeners()
method allows the default limit to be
+modified (if eventTargets is empty) or modify the limit specified in every EventTarget
| EventEmitter
passed as arguments.
+The value can be set toInfinity
(or 0
) to indicate an unlimited number of listeners.
+ +```js +EventEmitter.setMaxListeners(20) +// Equivalent to +EventEmitter.defaultMaxListeners = 20 + +const eventTarget = new EventTarget() +// Only way to increase limit for `EventTarget` instances +// as these doesn't expose its own `setMaxListeners` method +EventEmitter.setMaxListeners(20, eventTarget) +``` + +
+n
number
eventTargets
setMaxListeners(n, eventTargets) =>
KeyObject
– Node.js uses a KeyObject
class to represent a symmetric or asymmetric key,
+and each kind of key exposes different functions. The {@link createSecretKey}, {@link createPublicKey} and {@link createPrivateKey} methods are used to create KeyObject
instances. KeyObject
+objects are not to be created directly using the new
keyword.+ +Most applications should consider using the new `KeyObject` API instead of +passing keys as strings or `Buffer`s due to improved security features. + +`KeyObject` instances can be passed to other threads via `postMessage()`. +The receiver obtains a cloned `KeyObject`, and the `KeyObject` does not need to +be listed in the `transferList` argument. + +
+
+
+For RSA-PSS keys, if the key material contains a `RSASSA-PSS-params` sequence,
+the `hashAlgorithm`, `mgf1HashAlgorithm`, and `saltLength` properties will be
+set.
+
+Other key details might be exposed via this API using additional attributes.
+
+ number
+
+- `'rsa'` (OID 1.2.840.113549.1.1.1)
+- `'rsa-pss'` (OID 1.2.840.113549.1.1.10)
+- `'dsa'` (OID 1.2.840.10040.4.1)
+- `'ec'` (OID 1.2.840.10045.2.1)
+- `'x25519'` (OID 1.3.101.110)
+- `'x448'` (OID 1.3.101.111)
+- `'ed25519'` (OID 1.3.101.112)
+- `'ed448'` (OID 1.3.101.113)
+- `'dh'` (OID 1.2.840.113549.1.3.1)
+
+This property is `undefined` for unrecognized `KeyObject` types and symmetric
+keys.
+
+ number
+
+For public keys, the following encoding options can be used:
+
+For private keys, the following encoding options can be used:
+
+The result type depends on the selected encoding format, when PEM the
+result is a string, when DER it will be a buffer containing the data
+encoded as DER, when [JWK](https://tools.ietf.org/html/rfc7517) it will be an object.
+
+When [JWK](https://tools.ietf.org/html/rfc7517) encoding format was selected, all other encoding options are
+ignored.
+
+PKCS#1, SEC1, and PKCS#8 type keys can be encrypted by using a combination of
+the `cipher` and `format` options. The PKCS#8 `type` can be used with any`format` to encrypt any key algorithm (RSA, EC, or DH) by specifying a`cipher`. PKCS#1 and SEC1 can only be
+encrypted by specifying a `cipher`when the PEM `format` is used. For maximum compatibility, use PKCS#8 for
+encrypted private keys. Since PKCS#8 defines its own
+encryption mechanism, PEM-level encryption is not supported when encrypting
+a PKCS#8 key. See [RFC 5208](https://www.rfc-editor.org/rfc/rfc5208.txt) for PKCS#8 encryption and [RFC 1421](https://www.rfc-editor.org/rfc/rfc1421.txt) for
+PKCS#1 and SEC1 encryption.
+
+ KeyExportOptions< export(options) => #
src/.fastpm/-/@types/node@17.0.45/crypto.d.ts#L607 asymmetricKeyDetails
– This property exists only on asymmetric keys. Depending on the type of the key,
+this object contains information about the key. None of the information obtained
+through this property can be used to uniquely identify a key or to compromise
+the security of the key.
#
src/.fastpm/-/@types/node@17.0.45/crypto.d.ts#L593 asymmetricKeySize
– For asymmetric keys, this property represents the size of the embedded key in
+bytes. This property is undefined
for symmetric keys.#
src/.fastpm/-/@types/node@17.0.45/crypto.d.ts#L588 asymmetricKeyType
– For asymmetric keys, this property represents the type of the key. Supported key
+types are:
#
src/.fastpm/-/@types/node@17.0.45/crypto.d.ts#L639 symmetricKeySize
– For secret keys, this property represents the size of the key in bytes. This
+property is undefined
for asymmetric keys.#
src/.fastpm/-/@types/node@17.0.45/crypto.d.ts#L645 type
– Depending on the type of this KeyObject
, this property is either'secret'
for secret (symmetric) keys, 'public'
for public (asymmetric) keys
+or 'private'
for private (asymmetric) keys.#
src/.fastpm/-/@types/node@17.0.45/crypto.d.ts#L631 export
(options) – For symmetric keys, the following encoding options can be used:
#
options
"pem"
>string | Buffer
options
KeyExportOptions<"der"
>
export(options) =>
options
export(options) =>
from
(key) – Example: Converting a CryptoKey
instance to a KeyObject
:
+ +```js +const { webcrypto, KeyObject } = await import('crypto') +const { subtle } = webcrypto + +const key = await subtle.generateKey( + { + name: 'HMAC', + hash: 'SHA-256', + length: 256, + }, + true, + ['sign', 'verify'] +) + +const keyObject = KeyObject.from(key) +console.log(keyObject.symmetricKeySize) +// Prints: 32 (symmetric key size in bytes) +``` + +
+key
from(key) =>
ModuleGraph
resolveId(url, ssr) => #
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L1342 constructor
(resolveId)
#
new ModuleGraph
()
#
resolveId
(url, ssr)
Promise<
null
| PartialResolvedId>
fileToModulesMap
Map<string, Set<ModuleNode>>
idToModuleMap
Map<string, ModuleNode>
safeModulesPath
Set<string>
urlToModuleMap
Map<string, ModuleNode>
createFileOnlyEntry
(file) string#
file
createFileOnlyEntry(file) =>
ensureEntryFromUrl
(rawUrl, ssr, setIsSelfAccepting) getModuleById
(id) string#
id
getModuleById(id) =>
getModuleByUrl
(rawUrl, ssr) getModulesByFile
(file) string#
file
getModulesByFile(file) =>
invalidateAll
()
invalidateAll() =>
invalidateModule
(mod, seen, timestamp) Set<ModuleNode> number#
mod
#
seen
#
timestamp
invalidateModule(mod, seen, timestamp) =>
onFileChange
(file) string#
file
onFileChange(file) =>
resolveUrl
(url, ssr) updateModuleInfo
(mod, importedModules, importedBindings, acceptedModules, acceptedExports, isSelfAccepting, ssr) – Update the module graph based on a module's updated imports information
+If there are dependencies that no longer have any importers, they are
+returned as a Set. Set<string | ModuleNode> Set<string | ModuleNode> boolean boolean#
mod
#
importedModules
#
importedBindings
null
| Map<string, Set<string>>#
acceptedModules
#
acceptedExports
null
| Set<string>#
isSelfAccepting
#
ssr
updateModuleInfo(mod, importedModules, importedBindings, acceptedModules, acceptedExports, isSelfAccepting, ssr) =>
ModuleNode
string#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L1388 constructor
(url, setIsSelfAccepting)
#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L1368 id
– Resolved file system path + querynull
| string#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L1377 importedBindings
null
| Map<string, Set<string>>#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L1364 url
– Public served url path, starts with /
OutgoingMessage
– This class serves as the parent class of {@link ClientRequest} and {@link ServerResponse}. It is an abstract of outgoing message from
+the perspective of the participants of HTTP transaction. boolean boolean
+
+After calling `outgoingMessage.end()`, this property will be nulled.
+
+ boolean number boolean boolean number number boolean typeof captureRejectionSymbol boolean typeof errorMonitor
+
+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.
+
+#
src/.fastpm/-/@types/node@17.0.45/http.d.ts#L346 connection
– Aliases of outgoingMessage.socket
null
| Socket#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L543 destroyed
– Is true
after writable.destroy()
has been called.#
src/.fastpm/-/@types/node@17.0.45/http.d.ts#L340 headersSent
– Read-only. true
if the headers were sent, otherwise false
.#
src/.fastpm/-/@types/node@17.0.45/http.d.ts#L354 socket
– Reference to the underlying socket. Usually, users will not want to access
+this property.null
| Socket#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L504 writable
– Is true
if it is safe to call writable.write()
, which means
+the stream has not been destroyed, errored or ended.#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L538 writableCorked
– Number of times writable.uncork()
needs to be
+called in order to fully uncork the stream.#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L510 writableEnded
– Is true
after writable.end()
has been called. This property
+does not indicate whether the data has been flushed, for this use writable.writableFinished
instead.#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L515 writableFinished
– Is set to true
immediately before the 'finish'
event is emitted.#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L520 writableHighWaterMark
– Return the value of highWaterMark
passed when creating this Writable
.#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L527 writableLength
– This property contains the number of bytes (or objects) in the queue
+ready to be written. The value provides introspection data regarding
+the status of the highWaterMark
.#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L532 writableObjectMode
– Getter for the property objectMode
of a given Writable
stream.#
src/.fastpm/-/@types/node@17.0.45/events.d.ts#L301 captureRejectionSymbol
#
src/.fastpm/-/@types/node@17.0.45/events.d.ts#L306 captureRejections
– Sets or gets the default captureRejection value for all emitters.#
src/.fastpm/-/@types/node@17.0.45/events.d.ts#L300 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.
_construct(callback) =>
_destroy
(error, callback) #
error
null
| Error
_destroy(error, callback) =>
_final
(callback)
_final(callback) =>
_write
(chunk, encoding, callback) _write(chunk, encoding, callback) =>
_writev
(chunks, callback) { #
chunks
callback
(error) #
error
null
| Error
callback(error) =>
_writev(chunks, callback) =>
addListener
(event, listener) – Event emitter
+The defined events on documents including:
+1. close
+2. drain
+3. error
+4. finish
+5. pipe
+6. unpipeaddListener(event, listener) =>
event
"drain"
listener
()
listener() =>
addListener(event, listener) =>
event
"error"
listener
(err) Error#
err
listener(err) =>
addListener(event, listener) =>
event
"finish"
listener
()
listener() =>
addListener(event, listener) =>
event
"pipe"
addListener(event, listener) =>
event
"unpipe"
addListener(event, listener) =>
event
string | symbol
listener
(args) any []#
args
listener(args) =>
addListener(event, listener) =>
addTrailers
(headers) – Adds HTTP trailers (headers but at the end of the message) to the message.
+ +Trailers are **only** be emitted if the message is chunked encoded. If not, +the trailer will be silently discarded. + +HTTP requires the `Trailer` header to be sent to emit trailers, +with a list of header fields in its value, e.g. + +```js +message.writeHead(200, { 'Content-Type': 'text/plain', Trailer: 'Content-MD5' }) +message.write(fileData) +message.addTrailers({ 'Content-MD5': '7895bf4b8828b55ceaf47747b4bca667' }) +message.end() +``` + +Attempting to set a header field name or value that contains invalid characters +will result in a `TypeError` being thrown. + +
+headers
OutgoingHttpHeaders | readonly [ string, string ] []
addTrailers(headers) =>
cork
() – The writable.cork()
method forces all written data to be buffered in memory.
+The buffered data will be flushed when either the {@link uncork} or {@link end} methods are called.
+ +The primary intent of `writable.cork()` is to accommodate a situation in which +several small chunks are written to the stream in rapid succession. Instead of +immediately forwarding them to the underlying destination, `writable.cork()`buffers all the chunks until `writable.uncork()` is called, which will pass them +all to `writable._writev()`, if present. This prevents a head-of-line blocking +situation where data is being buffered while waiting for the first small chunk +to be processed. However, use of `writable.cork()` without implementing`writable._writev()` may have an adverse effect on throughput. + +See also: `writable.uncork()`, `writable._writev()`. + +
+cork() =>
destroy
(error) – Destroy the stream. Optionally emit an 'error'
event, and emit a 'close'
event (unless emitClose
is set to false
). After this call, the writable
+stream has ended and subsequent calls to write()
or end()
will result in
+an ERR_STREAM_DESTROYED
error.
+This is a destructive and immediate way to destroy a stream. Previous calls towrite()
may not have drained, and may trigger an ERR_STREAM_DESTROYED
error.
+Use end()
instead of destroy if data should flush before close, or wait for
+the 'drain'
event before destroying the stream.
+ +Once `destroy()` has been called any further calls will be a no-op and no +further errors except from `_destroy()` may be emitted as `'error'`. + +Implementors should not override this method, +but instead implement `writable._destroy()`. + +
+error
– Optional, an error to emit with 'error'
event.
+Error
destroy(error) =>
emit
(event) – Synchronously calls each of the listeners registered for the event namedeventName
, in the order they were registered, passing the supplied arguments
+to each.
+ +Returns `true` if the event had listeners, `false` otherwise. + +```js +const EventEmitter = require('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 +``` + +
+event
"close"
emit(event) =>
event
"drain"
emit(event) =>
event
"error"
err
Error
emit(event, err) =>
event
"finish"
emit(event) =>
event
"pipe"
src
emit(event, src) =>
event
"unpipe"
src
emit(event, src) =>
event
string | symbol
args
any []
emit(event, args) =>
end
(cb) – Calling the writable.end()
method signals that no more data will be written
+to the Writable
. The optional chunk
and encoding
arguments allow one
+final additional chunk of data to be written immediately before closing the
+stream.
+ +Calling the {@link write} method after calling {@link end} will raise an error. + +```js +// Write 'hello, ' and then end with 'world!'. +const fs = require('fs') +const file = fs.createWriteStream('example.txt') +file.write('hello, ') +file.end('world!') +// Writing more now is not allowed! +``` + +
+cb
()
cb() =>
end(cb) =>
chunk
any
cb
()
cb() =>
end(chunk, cb) =>
chunk
any
encoding
cb
()
cb() =>
end(chunk, encoding, cb) =>
eventNames
() – Returns an array listing the events for which the emitter has registered
+listeners. The values in the array are strings or Symbol
s.
+ +```js +const EventEmitter = require('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) ] +``` + +
+eventNames() =>
flushHeaders
() – Compulsorily flushes the message headers
+ +For efficiency reason, Node.js normally buffers the message headers +until `outgoingMessage.end()` is called or the first chunk of message data +is written. It then tries to pack the headers and data into a single TCP +packet. + +It is usually desired (it saves a TCP round-trip), but not when the first +data is not sent until possibly much later. `outgoingMessage.flushHeaders()`bypasses the optimization and kickstarts the request. + +
+flushHeaders() =>
getHeader
(name) – Gets the value of HTTP header with the given name. If such a name doesn't
+exist in message, it will be undefined
. string#
name
– Name of header
+
getHeader(name) =>
getHeaderNames
() – Returns an array of names of headers of the outgoing outgoingMessage. All
+names are lowercase.
getHeaderNames() =>
getHeaders
() – Returns a shallow copy of the current outgoing headers. Since a shallow
+copy is used, array values may be mutated without additional calls to
+various header-related HTTP module methods. The keys of the returned
+object are the header names and the values are the respective header
+values. All header names are lowercase.
+ +The object returned by the `outgoingMessage.getHeaders()` method does +not prototypically inherit from the JavaScript Object. This means that +typical Object methods such as `obj.toString()`, `obj.hasOwnProperty()`, +and others are not defined and will not work. + +```js +outgoingMessage.setHeader('Foo', 'bar') +outgoingMessage.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']) + +const headers = outgoingMessage.getHeaders() +// headers === { foo: 'bar', 'set-cookie': ['foo=bar', 'bar=baz'] } +``` + +
+getHeaders() =>
getMaxListeners
() – Returns the current max listener value for the EventEmitter
which is either
+set by emitter.setMaxListeners(n)
or defaults to {@link defaultMaxListeners}.
getMaxListeners() =>
hasHeader
(name) – Returns true
if the header identified by name
is currently set in the
+outgoing headers. The header name is case-insensitive.
+ +```js +const hasContentType = outgoingMessage.hasHeader('content-type') +``` + +
+name
string
hasHeader(name) =>
listenerCount
(eventName) – Returns the number of listeners listening to the event named eventName
. string | symbol#
eventName
– The name of the event being listened for
+
listenerCount(eventName) =>
listeners
(eventName) – Returns a copy of the array of listeners for the event named eventName
.
+ +```js +server.on('connection', stream => { + console.log('someone connected!') +}) +console.log(util.inspect(server.listeners('connection'))) +// Prints: [ [Function] ] +``` + +
+eventName
string | symbol
listeners(eventName) =>
off
(eventName, listener) – Alias for emitter.removeListener()
. string | symbol#
eventName
off(eventName, listener) =>
on
(event, listener) – 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.
+ +```js +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. + +```js +const myEE = new EventEmitter() +myEE.on('foo', () => console.log('a')) +myEE.prependListener('foo', () => console.log('b')) +myEE.emit('foo') +// Prints: +// b +// a +``` + +
+event
"close"
listener
()
listener() =>
on(event, listener) =>
event
"drain"
listener
()
listener() =>
on(event, listener) =>
event
"error"
listener
(err) Error#
err
listener(err) =>
on(event, listener) =>
event
"finish"
listener
()
listener() =>
on(event, listener) =>
event
"pipe"
on(event, listener) =>
event
"unpipe"
on(event, listener) =>
event
string | symbol
listener
(args) any []#
args
listener(args) =>
on(event, listener) =>
once
(event, listener) – Adds a one-timelistener
function for the event named eventName
. The
+next time eventName
is triggered, this listener is removed and then invoked.
+ +```js +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. + +```js +const myEE = new EventEmitter() +myEE.once('foo', () => console.log('a')) +myEE.prependOnceListener('foo', () => console.log('b')) +myEE.emit('foo') +// Prints: +// b +// a +``` + +
+event
"close"
listener
()
listener() =>
once(event, listener) =>
event
"drain"
listener
()
listener() =>
once(event, listener) =>
event
"error"
listener
(err) Error#
err
listener(err) =>
once(event, listener) =>
event
"finish"
listener
()
listener() =>
once(event, listener) =>
event
"pipe"
once(event, listener) =>
event
"unpipe"
once(event, listener) =>
event
string | symbol
listener
(args) any []#
args
listener(args) =>
once(event, listener) =>
pipe
(destination, { end }) { #
options
pipe<T extends WritableStream<T>>(destination, { end }) =>
prependListener
(event, listener) – 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.
+ +```js +server.prependListener('connection', stream => { + console.log('someone connected!') +}) +``` + +Returns a reference to the `EventEmitter`, so that calls can be chained. + +
+event
"close"
listener
()
listener() =>
prependListener(event, listener) =>
event
"drain"
listener
()
listener() =>
prependListener(event, listener) =>
event
"error"
listener
(err) Error#
err
listener(err) =>
prependListener(event, listener) =>
event
"finish"
listener
()
listener() =>
prependListener(event, listener) =>
event
"pipe"
prependListener(event, listener) =>
event
"unpipe"
prependListener(event, listener) =>
event
string | symbol
listener
(args) any []#
args
listener(args) =>
prependListener(event, listener) =>
prependOnceListener
(event, listener) – Adds a one-timelistener
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.
+ +```js +server.prependOnceListener('connection', stream => { + console.log('Ah, we have our first user!') +}) +``` + +Returns a reference to the `EventEmitter`, so that calls can be chained. + +
+event
"close"
listener
()
listener() =>
prependOnceListener(event, listener) =>
event
"drain"
listener
()
listener() =>
prependOnceListener(event, listener) =>
event
"error"
listener
(err) Error#
err
listener(err) =>
prependOnceListener(event, listener) =>
event
"finish"
listener
()
listener() =>
prependOnceListener(event, listener) =>
event
"pipe"
prependOnceListener(event, listener) =>
event
"unpipe"
prependOnceListener(event, listener) =>
event
string | symbol
listener
(args) any []#
args
listener(args) =>
prependOnceListener(event, listener) =>
rawListeners
(eventName) – Returns a copy of the array of listeners for the event named eventName
,
+including any wrappers (such as those created by .once()
).
+ +```js +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') +``` + +
+eventName
string | symbol
rawListeners(eventName) =>
removeAllListeners
(event) – 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. + +
+event
string | symbol
removeAllListeners(event) =>
removeHeader
(name) – Removes a header that is queued for implicit sending.
+ +```js +outgoingMessage.removeHeader('Content-Encoding') +``` + +
+name
string
removeHeader(name) =>
removeListener
(event, listener) – Removes the specified listener
from the listener array for the event namedeventName
.
+ +```js +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. + +```js +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 indices 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: + +```js +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. + +
+event
"close"
listener
()
listener() =>
removeListener(event, listener) =>
event
"drain"
listener
()
listener() =>
removeListener(event, listener) =>
event
"error"
listener
(err) Error#
err
listener(err) =>
removeListener(event, listener) =>
event
"finish"
listener
()
listener() =>
removeListener(event, listener) =>
event
"pipe"
removeListener(event, listener) =>
event
"unpipe"
removeListener(event, listener) =>
event
string | symbol
listener
(args) any []#
args
listener(args) =>
removeListener(event, listener) =>
setDefaultEncoding
(encoding) – The writable.setDefaultEncoding()
method sets the default encoding
for a Writable
stream. #
encoding
– The new default encoding
+
setDefaultEncoding(encoding) =>
setHeader
(name, value) – Sets a single header value for the header object.setMaxListeners
(n) – By default EventEmitter
s 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 toInfinity
(or 0
) to indicate an unlimited number of listeners.
+ +Returns a reference to the `EventEmitter`, so that calls can be chained. + +
+n
number
setMaxListeners(n) =>
setTimeout
(msecs, callback) – Once a socket is associated with the message and is connected,socket.setTimeout()
will be called with msecs
as the first parameter.setTimeout(msecs, callback) =>
uncork
() – The writable.uncork()
method flushes all data buffered since {@link cork} was called.
+ +When using `writable.cork()` and `writable.uncork()` to manage the buffering +of writes to a stream, it is recommended that calls to `writable.uncork()` be +deferred using `process.nextTick()`. Doing so allows batching of all`writable.write()` calls that occur within a given Node.js event loop phase. + +```js +stream.cork() +stream.write('some ') +stream.write('data ') +process.nextTick(() => stream.uncork()) +``` + +If the `writable.cork()` method is called multiple times on a stream, the +same number of calls to `writable.uncork()` must be called to flush the buffered +data. + +```js +stream.cork() +stream.write('some ') +stream.cork() +stream.write('data ') +process.nextTick(() => { + stream.uncork() + // The data will not be flushed until uncork() is called a second time. + stream.uncork() +}) +``` + +See also: `writable.cork()`. + +
+uncork() =>
write
(chunk, callback) – The writable.write()
method writes some data to the stream, and calls the
+supplied callback
once the data has been fully handled. If an error
+occurs, the callback
will be called with the error as its
+first argument. The callback
is called asynchronously and before 'error'
is
+emitted.
+ +The return value is `true` if the internal buffer is less than the`highWaterMark` configured when the stream was created after admitting `chunk`. +If `false` is returned, further attempts to write data to the stream should +stop until the `'drain'` event is emitted. + +While a stream is not draining, calls to `write()` will buffer `chunk`, and +return false. Once all currently buffered chunks are drained (accepted for +delivery by the operating system), the `'drain'` event will be emitted. +It is recommended that once `write()` returns false, no more chunks be written +until the `'drain'` event is emitted. While calling `write()` on a stream that +is not draining is allowed, Node.js will buffer all written chunks until +maximum memory usage occurs, at which point it will abort unconditionally. +Even before it aborts, high memory usage will cause poor garbage collector +performance and high RSS (which is not typically released back to the system, +even after the memory is no longer required). Since TCP sockets may never +drain if the remote peer does not read the data, writing a socket that is +not draining may lead to a remotely exploitable vulnerability. + +Writing data while the stream is not draining is particularly +problematic for a `Transform`, because the `Transform` streams are paused +by default until they are piped or a `'data'` or `'readable'` event handler +is added. + +If the data to be written can be generated or fetched on demand, it is +recommended to encapsulate the logic into a `Readable` and use {@link pipe}. However, if calling `write()` is preferred, it is +possible to respect backpressure and avoid memory issues using the `'drain'` event: + +```js +function write(data, cb) { + if (!stream.write(data)) { + stream.once('drain', cb) + } else { + process.nextTick(cb) + } +} + +// Wait for cb to be called before doing any other write. +write('hello', () => { + console.log('Write completed, do more writes now.') +}) +``` + +A `Writable` stream in object mode will always ignore the `encoding` argument. + +
+chunk
– Optional data to write. For streams not operating in object mode, chunk
must be a string, Buffer
or Uint8Array
. For object mode streams, chunk
may be any
+JavaScript value other than null
.any
callback
(error) undefined | #
error
null
| Error
callback(error) =>
write(chunk, callback) =>
chunk
any
encoding
callback
(error) undefined | #
error
null
| Error
callback(error) =>
write(chunk, encoding, callback) =>
getEventListeners
(emitter, name) – Returns a copy of the array of listeners for the event named eventName
.
+ +For `EventEmitter`s this behaves exactly the same as calling `.listeners` on +the emitter. + +For `EventTarget`s this is the only way to get the event listeners for the +event target. This is useful for debugging and diagnostic purposes. + +```js +const { getEventListeners, EventEmitter } = require('events') + +{ + const ee = new EventEmitter() + const listener = () => console.log('Events are fun') + ee.on('foo', listener) + getEventListeners(ee, 'foo') // [listener] +} +{ + const et = new EventTarget() + const listener = () => console.log('Events are fun') + et.addEventListener('foo', listener) + getEventListeners(et, 'foo') // [listener] +} +``` + +
+emitter
name
string | symbol
getEventListeners(emitter, name) =>
listenerCount
(emitter, eventName) – A class method that returns the number of listeners for the given eventName
registered on the given emitter
.
+ +```js +const { EventEmitter, listenerCount } = require('events') +const myEmitter = new EventEmitter() +myEmitter.on('event', () => {}) +myEmitter.on('event', () => {}) +console.log(listenerCount(myEmitter, 'event')) +// Prints: 2 +``` + +
+emitter
– The emitter to queryeventName
– The event name
+string | symbol
listenerCount(emitter, eventName) =>
on
(emitter, eventName, options) – ```js
+const { on, EventEmitter } = require('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: + +```js +const { on, EventEmitter } = require('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()); +```` + +
+emitter
eventName
– The name of the event being listened forstring
options
on(emitter, eventName, options) =>
once
(emitter, eventName, options) – 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](https://dom.spec.whatwg.org/#interface-eventtarget) interface, which has no special`'error'` event +semantics and does not listen to the `'error'` event. + +```js +const { once, EventEmitter } = require('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.log('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: + +```js +const { EventEmitter, once } = require('events') + +const ee = new EventEmitter() + +once(ee, 'error') + .then(([err]) => console.log('ok', err.message)) + .catch(err => console.log('error', err.message)) + +ee.emit('error', new Error('boom')) + +// Prints: ok boom +``` + +An `AbortSignal` can be used to cancel waiting for the event: + +```js +const { EventEmitter, once } = require('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() // Abort waiting for the event +ee.emit('foo') // Prints: Waiting for the event was canceled! +``` + +
+emitter
eventName
string | symbol
options
once(emitter, eventName, options) =>
emitter
eventName
string
options
once(emitter, eventName, options) =>
setMaxListeners
(n, eventTargets) – By default EventEmitter
s 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 EventEmitter.setMaxListeners()
method allows the default limit to be
+modified (if eventTargets is empty) or modify the limit specified in every EventTarget
| EventEmitter
passed as arguments.
+The value can be set toInfinity
(or 0
) to indicate an unlimited number of listeners.
+ +```js +EventEmitter.setMaxListeners(20) +// Equivalent to +EventEmitter.defaultMaxListeners = 20 + +const eventTarget = new EventTarget() +// Only way to increase limit for `EventTarget` instances +// as these doesn't expose its own `setMaxListeners` method +EventEmitter.setMaxListeners(20, eventTarget) +``` + +
+n
number
eventTargets
setMaxListeners(n, eventTargets) =>
Readable
boolean boolean boolean boolean boolean number number boolean typeof captureRejectionSymbol boolean typeof errorMonitor
+
+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.
+
+ [asyncIterator]() => #
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L115 destroyed
– Is true
after readable.destroy()
has been called.#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L71 readable
– Is true
if it is safe to call readable.read()
, which means
+the stream has not been destroyed or emitted 'error'
or 'end'
.#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L65 readableAborted
– Returns whether the stream was destroyed or errored before emitting 'end'
.#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L77 readableDidRead
– Returns whether 'data'
has been emitted.#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L82 readableEncoding
– Getter for the property encoding
of a given Readable
stream. The encoding
property can be set using the readable.setEncoding()
method.null
| BufferEncoding#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L87 readableEnded
– Becomes true
when 'end'
event is emitted.#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L93 readableFlowing
– This property reflects the current state of a Readable
stream as described
+in the Three states
section.null
| boolean#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L98 readableHighWaterMark
– Returns the value of highWaterMark
passed when creating this Readable
.#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L105 readableLength
– This property contains the number of bytes (or objects) in the queue
+ready to be read. The value provides introspection data regarding
+the status of the highWaterMark
.#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L110 readableObjectMode
– Getter for the property objectMode
of a given Readable
stream.#
src/.fastpm/-/@types/node@17.0.45/events.d.ts#L301 captureRejectionSymbol
#
src/.fastpm/-/@types/node@17.0.45/events.d.ts#L306 captureRejections
– Sets or gets the default captureRejection value for all emitters.#
src/.fastpm/-/@types/node@17.0.45/events.d.ts#L300 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.#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L479 [asyncIterator]
()
AsyncIterableIterator<any>
_construct
(callback)
_construct(callback) =>
_destroy
(error, callback) #
error
null
| Error
_destroy(error, callback) =>
_read
(size) number#
size
_read(size) =>
addListener
(event, listener) – Event emitter
+The defined events on documents including:
+1. close
+2. data
+3. end
+4. error
+5. pause
+6. readable
+7. resumeaddListener(event, listener) =>
event
"data"
listener
(chunk) any#
chunk
listener(chunk) =>
addListener(event, listener) =>
event
"end"
listener
()
listener() =>
addListener(event, listener) =>
event
"error"
listener
(err) Error#
err
listener(err) =>
addListener(event, listener) =>
event
"pause"
listener
()
listener() =>
addListener(event, listener) =>
event
"readable"
listener
()
listener() =>
addListener(event, listener) =>
event
"resume"
listener
()
listener() =>
addListener(event, listener) =>
event
string | symbol
listener
(args) any []#
args
listener(args) =>
addListener(event, listener) =>
destroy
(error) – Destroy the stream. Optionally emit an 'error'
event, and emit a 'close'
event (unless emitClose
is set to false
). After this call, the readable
+stream will release any internal resources and subsequent calls to push()
will be ignored.
+ +Once `destroy()` has been called any further calls will be a no-op and no +further errors except from `_destroy()` may be emitted as `'error'`. + +Implementors should not override this method, but instead implement `readable._destroy()`. + +
+error
– Error which will be passed as payload in 'error'
event
+Error
destroy(error) =>
emit
(event) – Synchronously calls each of the listeners registered for the event namedeventName
, in the order they were registered, passing the supplied arguments
+to each.
+ +Returns `true` if the event had listeners, `false` otherwise. + +```js +const EventEmitter = require('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 +``` + +
+event
"close"
emit(event) =>
event
"data"
chunk
any
emit(event, chunk) =>
event
"end"
emit(event) =>
event
"error"
err
Error
emit(event, err) =>
event
"pause"
emit(event) =>
event
"readable"
emit(event) =>
event
"resume"
emit(event) =>
event
string | symbol
args
any []
emit(event, args) =>
eventNames
() – Returns an array listing the events for which the emitter has registered
+listeners. The values in the array are strings or Symbol
s.
+ +```js +const EventEmitter = require('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) ] +``` + +
+eventNames() =>
getMaxListeners
() – Returns the current max listener value for the EventEmitter
which is either
+set by emitter.setMaxListeners(n)
or defaults to {@link defaultMaxListeners}.
getMaxListeners() =>
isPaused
() – The readable.isPaused()
method returns the current operating state of theReadable
. This is used primarily by the mechanism that underlies thereadable.pipe()
method. In most
+typical cases, there will be no reason to
+use this method directly.
+ +```js +const readable = new stream.Readable() + +readable.isPaused() // === false +readable.pause() +readable.isPaused() // === true +readable.resume() +readable.isPaused() // === false +``` + +
+isPaused() =>
listenerCount
(eventName) – Returns the number of listeners listening to the event named eventName
. string | symbol#
eventName
– The name of the event being listened for
+
listenerCount(eventName) =>
listeners
(eventName) – Returns a copy of the array of listeners for the event named eventName
.
+ +```js +server.on('connection', stream => { + console.log('someone connected!') +}) +console.log(util.inspect(server.listeners('connection'))) +// Prints: [ [Function] ] +``` + +
+eventName
string | symbol
listeners(eventName) =>
off
(eventName, listener) – Alias for emitter.removeListener()
. string | symbol#
eventName
off(eventName, listener) =>
on
(event, listener) – 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.
+ +```js +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. + +```js +const myEE = new EventEmitter() +myEE.on('foo', () => console.log('a')) +myEE.prependListener('foo', () => console.log('b')) +myEE.emit('foo') +// Prints: +// b +// a +``` + +
+event
"close"
listener
()
listener() =>
on(event, listener) =>
event
"data"
listener
(chunk) any#
chunk
listener(chunk) =>
on(event, listener) =>
event
"end"
listener
()
listener() =>
on(event, listener) =>
event
"error"
listener
(err) Error#
err
listener(err) =>
on(event, listener) =>
event
"pause"
listener
()
listener() =>
on(event, listener) =>
event
"readable"
listener
()
listener() =>
on(event, listener) =>
event
"resume"
listener
()
listener() =>
on(event, listener) =>
event
string | symbol
listener
(args) any []#
args
listener(args) =>
on(event, listener) =>
once
(event, listener) – Adds a one-timelistener
function for the event named eventName
. The
+next time eventName
is triggered, this listener is removed and then invoked.
+ +```js +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. + +```js +const myEE = new EventEmitter() +myEE.once('foo', () => console.log('a')) +myEE.prependOnceListener('foo', () => console.log('b')) +myEE.emit('foo') +// Prints: +// b +// a +``` + +
+event
"close"
listener
()
listener() =>
once(event, listener) =>
event
"data"
listener
(chunk) any#
chunk
listener(chunk) =>
once(event, listener) =>
event
"end"
listener
()
listener() =>
once(event, listener) =>
event
"error"
listener
(err) Error#
err
listener(err) =>
once(event, listener) =>
event
"pause"
listener
()
listener() =>
once(event, listener) =>
event
"readable"
listener
()
listener() =>
once(event, listener) =>
event
"resume"
listener
()
listener() =>
once(event, listener) =>
event
string | symbol
listener
(args) any []#
args
listener(args) =>
once(event, listener) =>
pause
() – The readable.pause()
method will cause a stream in flowing mode to stop
+emitting 'data'
events, switching out of flowing mode. Any data that
+becomes available will remain in the internal buffer.
+ +```js +const readable = getReadableStreamSomehow() +readable.on('data', chunk => { + console.log(`Received ${chunk.length} bytes of data.`) + readable.pause() + console.log('There will be no additional data for 1 second.') + setTimeout(() => { + console.log('Now data will start flowing again.') + readable.resume() + }, 1000) +}) +``` + +The `readable.pause()` method has no effect if there is a `'readable'`event listener. + +
+pause() =>
pipe
(destination, { end }) { #
options
pipe<T extends WritableStream<T>>(destination, { end }) =>
prependListener
(event, listener) – 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.
+ +```js +server.prependListener('connection', stream => { + console.log('someone connected!') +}) +``` + +Returns a reference to the `EventEmitter`, so that calls can be chained. + +
+event
"close"
listener
()
listener() =>
prependListener(event, listener) =>
event
"data"
listener
(chunk) any#
chunk
listener(chunk) =>
prependListener(event, listener) =>
event
"end"
listener
()
listener() =>
prependListener(event, listener) =>
event
"error"
listener
(err) Error#
err
listener(err) =>
prependListener(event, listener) =>
event
"pause"
listener
()
listener() =>
prependListener(event, listener) =>
event
"readable"
listener
()
listener() =>
prependListener(event, listener) =>
event
"resume"
listener
()
listener() =>
prependListener(event, listener) =>
event
string | symbol
listener
(args) any []#
args
listener(args) =>
prependListener(event, listener) =>
prependOnceListener
(event, listener) – Adds a one-timelistener
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.
+ +```js +server.prependOnceListener('connection', stream => { + console.log('Ah, we have our first user!') +}) +``` + +Returns a reference to the `EventEmitter`, so that calls can be chained. + +
+event
"close"
listener
()
listener() =>
prependOnceListener(event, listener) =>
event
"data"
listener
(chunk) any#
chunk
listener(chunk) =>
prependOnceListener(event, listener) =>
event
"end"
listener
()
listener() =>
prependOnceListener(event, listener) =>
event
"error"
listener
(err) Error#
err
listener(err) =>
prependOnceListener(event, listener) =>
event
"pause"
listener
()
listener() =>
prependOnceListener(event, listener) =>
event
"readable"
listener
()
listener() =>
prependOnceListener(event, listener) =>
event
"resume"
listener
()
listener() =>
prependOnceListener(event, listener) =>
event
string | symbol
listener
(args) any []#
args
listener(args) =>
prependOnceListener(event, listener) =>
push
(chunk, encoding) push(chunk, encoding) =>
rawListeners
(eventName) – Returns a copy of the array of listeners for the event named eventName
,
+including any wrappers (such as those created by .once()
).
+ +```js +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') +``` + +
+eventName
string | symbol
rawListeners(eventName) =>
read
(size) – The readable.read()
method pulls some data out of the internal buffer and
+returns it. If no data available to be read, null
is returned. By default,
+the data will be returned as a Buffer
object unless an encoding has been
+specified using the readable.setEncoding()
method or the stream is operating
+in object mode.
+ +The optional `size` argument specifies a specific number of bytes to read. If`size` bytes are not available to be read, `null` will be returned _unless_the stream has ended, in which +case all of the data remaining in the internal +buffer will be returned. + +If the `size` argument is not specified, all of the data contained in the +internal buffer will be returned. + +The `size` argument must be less than or equal to 1 GiB. + +The `readable.read()` method should only be called on `Readable` streams +operating in paused mode. In flowing mode, `readable.read()` is called +automatically until the internal buffer is fully drained. + +```js +const readable = getReadableStreamSomehow() + +// 'readable' may be triggered multiple times as data is buffered in +readable.on('readable', () => { + let chunk + console.log('Stream is readable (new data received in buffer)') + // Use a loop to make sure we read all currently available data + while (null !== (chunk = readable.read())) { + console.log(`Read ${chunk.length} bytes of data...`) + } +}) + +// 'end' will be triggered once when there is no more data available +readable.on('end', () => { + console.log('Reached end of stream.') +}) +``` + +Each call to `readable.read()` returns a chunk of data, or `null`. The chunks +are not concatenated. A `while` loop is necessary to consume all data +currently in the buffer. When reading a large file `.read()` may return `null`, +having consumed all buffered content so far, but there is still more data to +come not yet buffered. In this case a new `'readable'` event will be emitted +when there is more data in the buffer. Finally the `'end'` event will be +emitted when there is no more data to come. + +Therefore to read a file's whole contents from a `readable`, it is necessary +to collect chunks across multiple `'readable'` events: + +```js +const chunks = [] + +readable.on('readable', () => { + let chunk + while (null !== (chunk = readable.read())) { + chunks.push(chunk) + } +}) + +readable.on('end', () => { + const content = chunks.join('') +}) +``` + +A `Readable` stream in object mode will always return a single item from +a call to `readable.read(size)`, regardless of the value of the`size` argument. + +If the `readable.read()` method returns a chunk of data, a `'data'` event will +also be emitted. + +Calling {@link read} after the `'end'` event has +been emitted will return `null`. No runtime error will be raised. + +
+size
– Optional argument to specify how much data to read.
+number
read(size) =>
removeAllListeners
(event) – 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. + +
+event
string | symbol
removeAllListeners(event) =>
removeListener
(event, listener) – Removes the specified listener
from the listener array for the event namedeventName
.
+ +```js +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. + +```js +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 indices 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: + +```js +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. + +
+event
"close"
listener
()
listener() =>
removeListener(event, listener) =>
event
"data"
listener
(chunk) any#
chunk
listener(chunk) =>
removeListener(event, listener) =>
event
"end"
listener
()
listener() =>
removeListener(event, listener) =>
event
"error"
listener
(err) Error#
err
listener(err) =>
removeListener(event, listener) =>
event
"pause"
listener
()
listener() =>
removeListener(event, listener) =>
event
"readable"
listener
()
listener() =>
removeListener(event, listener) =>
event
"resume"
listener
()
listener() =>
removeListener(event, listener) =>
event
string | symbol
listener
(args) any []#
args
listener(args) =>
removeListener(event, listener) =>
resume
() – The readable.resume()
method causes an explicitly paused Readable
stream to
+resume emitting 'data'
events, switching the stream into flowing mode.
+ +The `readable.resume()` method can be used to fully consume the data from a +stream without actually processing any of that data: + +```js +getReadableStreamSomehow() + .resume() + .on('end', () => { + console.log('Reached the end, but did not read anything.') + }) +``` + +The `readable.resume()` method has no effect if there is a `'readable'`event listener. + +
+resume() =>
setEncoding
(encoding) – The readable.setEncoding()
method sets the character encoding for
+data read from the Readable
stream.
+ +By default, no encoding is assigned and stream data will be returned as`Buffer` objects. Setting an encoding causes the stream data +to be returned as strings of the specified encoding rather than as `Buffer`objects. For instance, calling `readable.setEncoding('utf8')` will cause the +output data to be interpreted as UTF-8 data, and passed as strings. Calling`readable.setEncoding('hex')` will cause the data to be encoded in hexadecimal +string format. + +The `Readable` stream will properly handle multi-byte characters delivered +through the stream that would otherwise become improperly decoded if simply +pulled from the stream as `Buffer` objects. + +```js +const readable = getReadableStreamSomehow() +readable.setEncoding('utf8') +readable.on('data', chunk => { + assert.equal(typeof chunk, 'string') + console.log('Got %d characters of string data:', chunk.length) +}) +``` + +
+encoding
– The encoding to use.
+setEncoding(encoding) =>
setMaxListeners
(n) – By default EventEmitter
s 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 toInfinity
(or 0
) to indicate an unlimited number of listeners.
+ +Returns a reference to the `EventEmitter`, so that calls can be chained. + +
+n
number
setMaxListeners(n) =>
unpipe
(destination) – The readable.unpipe()
method detaches a Writable
stream previously attached
+using the {@link pipe} method.
+ +If the `destination` is not specified, then _all_ pipes are detached. + +If the `destination` is specified, but no pipe is set up for it, then +the method does nothing. + +```js +const fs = require('fs') +const readable = getReadableStreamSomehow() +const writable = fs.createWriteStream('file.txt') +// All the data from readable goes into 'file.txt', +// but only for the first second. +readable.pipe(writable) +setTimeout(() => { + console.log('Stop writing to file.txt.') + readable.unpipe(writable) + console.log('Manually close the file stream.') + writable.end() +}, 1000) +``` + +
+destination
– Optional specific stream to unpipe
+unpipe(destination) =>
unshift
(chunk, encoding) – Passing chunk
as null
signals the end of the stream (EOF) and behaves the
+same as readable.push(null)
, after which no more data can be written. The EOF
+signal is put at the end of the buffer and any buffered data will still be
+flushed.
+ +The `readable.unshift()` method pushes a chunk of data back into the internal +buffer. This is useful in certain situations where a stream is being consumed by +code that needs to "un-consume" some amount of data that it has optimistically +pulled out of the source, so that the data can be passed on to some other party. + +The `stream.unshift(chunk)` method cannot be called after the `'end'` event +has been emitted or a runtime error will be thrown. + +Developers using `stream.unshift()` often should consider switching to +use of a `Transform` stream instead. See the `API for stream implementers` section for more information. + +```js +// Pull off a header delimited by \n\n. +// Use unshift() if we get too much. +// Call the callback with (error, header, stream). +const { StringDecoder } = require('string_decoder') +function parseHeader(stream, callback) { + stream.on('error', callback) + stream.on('readable', onReadable) + const decoder = new StringDecoder('utf8') + let header = '' + function onReadable() { + let chunk + while (null !== (chunk = stream.read())) { + const str = decoder.write(chunk) + if (str.match(/\n\n/)) { + // Found the header boundary. + const split = str.split(/\n\n/) + header += split.shift() + const remaining = split.join('\n\n') + const buf = Buffer.from(remaining, 'utf8') + stream.removeListener('error', callback) + // Remove the 'readable' listener before unshifting. + stream.removeListener('readable', onReadable) + if (buf.length) + stream.unshift(buf) + // Now the body of the message can be read from the stream. + callback(null, header, stream) + } else { + // Still reading the header. + header += str + } + } + } +} +``` + +Unlike {@link push}, `stream.unshift(chunk)` will not +end the reading process by resetting the internal reading state of the stream. +This can cause unexpected results if `readable.unshift()` is called during a +read (i.e. from within a {@link _read} implementation on a +custom stream). Following the call to `readable.unshift()` with an immediate {@link push} will reset the reading state appropriately, +however it is best to simply avoid calling `readable.unshift()` while in the +process of performing a read. + +
+chunk
– Chunk of data to unshift onto the read queue. For streams not operating in object mode, chunk
must be a string, Buffer
, Uint8Array
or null
. For object mode
+streams, chunk
may be any JavaScript value.any
encoding
– Encoding of string chunks. Must be a valid Buffer
encoding, such as 'utf8'
or 'ascii'
.
+unshift(chunk, encoding) =>
wrap
(stream) – Prior to Node.js 0.10, streams did not implement the entire stream
module API
+as it is currently defined. (See Compatibility
for more information.)
+ +When using an older Node.js library that emits `'data'` events and has a {@link pause} method that is advisory only, the`readable.wrap()` method can be used to create a `Readable` +stream that uses +the old stream as its data source. + +It will rarely be necessary to use `readable.wrap()` but the method has been +provided as a convenience for interacting with older Node.js applications and +libraries. + +```js +const { OldReader } = require('./old-api-module.js') +const { Readable } = require('stream') +const oreader = new OldReader() +const myReader = new Readable().wrap(oreader) + +myReader.on('readable', () => { + myReader.read() // etc. +}) +``` + +
+stream
– An "old style" readable stream
+wrap(stream) =>
from
(iterable, options) – A utility method for creating Readable Streams out of iterators.getEventListeners
(emitter, name) – Returns a copy of the array of listeners for the event named eventName
.
+ +For `EventEmitter`s this behaves exactly the same as calling `.listeners` on +the emitter. + +For `EventTarget`s this is the only way to get the event listeners for the +event target. This is useful for debugging and diagnostic purposes. + +```js +const { getEventListeners, EventEmitter } = require('events') + +{ + const ee = new EventEmitter() + const listener = () => console.log('Events are fun') + ee.on('foo', listener) + getEventListeners(ee, 'foo') // [listener] +} +{ + const et = new EventTarget() + const listener = () => console.log('Events are fun') + et.addEventListener('foo', listener) + getEventListeners(et, 'foo') // [listener] +} +``` + +
+emitter
name
string | symbol
getEventListeners(emitter, name) =>
isDisturbed
(stream) – Returns whether the stream has been read from or cancelled. #
stream
isDisturbed(stream) =>
listenerCount
(emitter, eventName) – A class method that returns the number of listeners for the given eventName
registered on the given emitter
.
+ +```js +const { EventEmitter, listenerCount } = require('events') +const myEmitter = new EventEmitter() +myEmitter.on('event', () => {}) +myEmitter.on('event', () => {}) +console.log(listenerCount(myEmitter, 'event')) +// Prints: 2 +``` + +
+emitter
– The emitter to queryeventName
– The event name
+string | symbol
listenerCount(emitter, eventName) =>
on
(emitter, eventName, options) – ```js
+const { on, EventEmitter } = require('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: + +```js +const { on, EventEmitter } = require('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()); +```` + +
+emitter
eventName
– The name of the event being listened forstring
options
on(emitter, eventName, options) =>
once
(emitter, eventName, options) – 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](https://dom.spec.whatwg.org/#interface-eventtarget) interface, which has no special`'error'` event +semantics and does not listen to the `'error'` event. + +```js +const { once, EventEmitter } = require('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.log('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: + +```js +const { EventEmitter, once } = require('events') + +const ee = new EventEmitter() + +once(ee, 'error') + .then(([err]) => console.log('ok', err.message)) + .catch(err => console.log('error', err.message)) + +ee.emit('error', new Error('boom')) + +// Prints: ok boom +``` + +An `AbortSignal` can be used to cancel waiting for the event: + +```js +const { EventEmitter, once } = require('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() // Abort waiting for the event +ee.emit('foo') // Prints: Waiting for the event was canceled! +``` + +
+emitter
eventName
string | symbol
options
once(emitter, eventName, options) =>
emitter
eventName
string
options
once(emitter, eventName, options) =>
setMaxListeners
(n, eventTargets) – By default EventEmitter
s 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 EventEmitter.setMaxListeners()
method allows the default limit to be
+modified (if eventTargets is empty) or modify the limit specified in every EventTarget
| EventEmitter
passed as arguments.
+The value can be set toInfinity
(or 0
) to indicate an unlimited number of listeners.
+ +```js +EventEmitter.setMaxListeners(20) +// Equivalent to +EventEmitter.defaultMaxListeners = 20 + +const eventTarget = new EventTarget() +// Only way to increase limit for `EventTarget` instances +// as these doesn't expose its own `setMaxListeners` method +EventEmitter.setMaxListeners(20, eventTarget) +``` + +
+n
number
eventTargets
setMaxListeners(n, eventTargets) =>
Server
number
+
+In case of inactivity, the rules defined in `server.timeout` apply. However,
+that inactivity based timeout would still allow the connection to be kept open
+if the headers are being sent very slowly (by default, up to a byte per 2
+minutes). In order to prevent this, whenever header data arrives an additional
+check is made that more than `server.headersTimeout` milliseconds has not
+passed since the connection was established. If the check fails, a `'timeout'`event is emitted on the server object, and (by default) the socket is destroyed.
+See `server.timeout` for more information on how timeout behavior can be
+customized.
+
+ number
+
+A value of `0` will disable the keep-alive timeout behavior on incoming
+connections.
+A value of `0` makes the http server behave similarly to Node.js versions prior
+to 8.0.0, which did not have a keep-alive timeout.
+
+The socket timeout logic is set up on connection, so changing this value only
+affects new connections to the server, not any existing connections.
+
+ boolean number
+
+It is not recommended to use this option once a socket has been sent to a child
+with `child_process.fork()`.
+
+
+
+A value of `0` will disable the limit.
+
+When the limit is reached it will set the `Connection` header value to `close`,
+but will not actually close the connection, subsequent requests sent
+after the limit is reached will get `503 Service Unavailable` as a response.
+
+ number
+
+If the timeout expires, the server responds with status 408 without
+forwarding the request to the request listener and then closes the connection.
+
+It must be set to a non-zero value (e.g. 120 seconds) to protect against
+potential Denial-of-Service attacks in case the server is deployed without a
+reverse proxy in front.
+
+ number
+
+A value of `0` will disable the timeout behavior on incoming connections.
+
+The socket timeout logic is set up on connection, so changing this
+value only affects new connections to the server, not any existing connections.
+
+ typeof captureRejectionSymbol boolean typeof errorMonitor
+
+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.
+
+ string#
src/.fastpm/-/@types/node@17.0.45/http.d.ts#L164 constructor
(requestListener)
#
new Server
()
#
src/.fastpm/-/@types/node@17.0.45/http.d.ts#L224 headersTimeout
– Limit the amount of time the parser will wait to receive the complete HTTP
+headers.#
src/.fastpm/-/@types/node@17.0.45/http.d.ts#L240 keepAliveTimeout
– The number of milliseconds of inactivity a server needs to wait for additional
+incoming data, after it has finished writing the last response, before a socket
+will be destroyed. If the server receives new data before the keep-alive
+timeout has fired, it will reset the regular inactivity timeout, i.e.,server.timeout
.#
src/.fastpm/-/@types/node@17.0.45/net.d.ts#L527 listening
– Indicates whether or not the server is listening for connections.#
src/.fastpm/-/@types/node@17.0.45/net.d.ts#L521 maxConnections
– Set this property to reject connections when the server's connection count gets
+high.#
src/.fastpm/-/@types/node@17.0.45/http.d.ts#L186 maxHeadersCount
– Limits maximum incoming headers count. If set to 0, no limit will be applied.null
| number#
src/.fastpm/-/@types/node@17.0.45/http.d.ts#L198 maxRequestsPerSocket
– The maximum number of requests socket can handle
+before closing keep alive connection.null
| number#
src/.fastpm/-/@types/node@17.0.45/http.d.ts#L253 requestTimeout
– Sets the timeout value in milliseconds for receiving the entire request from
+the client.#
src/.fastpm/-/@types/node@17.0.45/http.d.ts#L209 timeout
– The number of milliseconds of inactivity before a socket is presumed
+to have timed out.#
src/.fastpm/-/@types/node@17.0.45/events.d.ts#L301 captureRejectionSymbol
#
src/.fastpm/-/@types/node@17.0.45/events.d.ts#L306 captureRejections
– Sets or gets the default captureRejection value for all emitters.#
src/.fastpm/-/@types/node@17.0.45/events.d.ts#L300 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.#
src/.fastpm/-/@types/node@17.0.45/http.d.ts#L254 addListener
(event, listener) – events.EventEmitter
+1. close
+2. connection
+3. error
+4. listening
#
event
addListener(event, listener) =>
event
"close"
listener
()
listener() =>
addListener(event, listener) =>
event
"connection"
addListener(event, listener) =>
event
"error"
listener
(err) Error#
err
listener(err) =>
addListener(event, listener) =>
event
"listening"
listener
()
listener() =>
addListener(event, listener) =>
event
"checkContinue"
listener
addListener(event, listener) =>
event
"checkExpectation"
listener
addListener(event, listener) =>
event
"clientError"
addListener(event, listener) =>
event
"connect"
listener
(req, socket, head) #
req
listener(req, socket, head) =>
addListener(event, listener) =>
event
"request"
listener
addListener(event, listener) =>
event
"upgrade"
listener
(req, socket, head) #
req
listener(req, socket, head) =>
addListener(event, listener) =>
address
() – Returns the bound address
, the address family
name, and port
of the server
+as reported by the operating system if listening on an IP socket
+(useful to find which port was assigned when getting an OS-assigned address):{ port: 12346, family: 'IPv4', address: '127.0.0.1' }
.
+ +For a server listening on a pipe or Unix domain socket, the name is returned +as a string. + +```js +const server = net.createServer(socket => { + socket.end('goodbye\n') +}).on('error', err => { + // Handle errors here. + throw err +}) + +// Grab an arbitrary unused port. +server.listen(() => { + console.log('opened server on', server.address()) +}) +``` + +`server.address()` returns `null` before the `'listening'` event has been +emitted or after calling `server.close()`. + +
+address() =>
null
| string | AddressInfoclose
(callback) – Stops the server from accepting new connections and keeps existing
+connections. This function is asynchronous, the server is finally closed
+when all connections are ended and the server emits a 'close'
event.
+The optional callback
will be called once the 'close'
event occurs. Unlike
+that event, it will be called with an Error
as its only argument if the server
+was not open when it was closed.
close(callback) =>
emit
(event, args) – Synchronously calls each of the listeners registered for the event namedeventName
, in the order they were registered, passing the supplied arguments
+to each.
+ +Returns `true` if the event had listeners, `false` otherwise. + +```js +const EventEmitter = require('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 +``` + +
+event
string
args
any []
emit(event, args) =>
event
"close"
emit(event) =>
event
"connection"
socket
emit(event, socket) =>
event
"error"
err
Error
emit(event, err) =>
event
"listening"
emit(event) =>
event
"checkContinue"
req
res
emit(event, req, res) =>
event
"checkExpectation"
req
res
emit(event, req, res) =>
event
"clientError"
err
Error
socket
emit(event, err, socket) =>
event
"connect"
req
socket
head
emit(event, req, socket, head) =>
event
"request"
req
res
emit(event, req, res) =>
event
"upgrade"
req
socket
head
emit(event, req, socket, head) =>
eventNames
() – Returns an array listing the events for which the emitter has registered
+listeners. The values in the array are strings or Symbol
s.
+ +```js +const EventEmitter = require('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) ] +``` + +
+eventNames() =>
getConnections
(cb) – Asynchronously get the number of concurrent connections on the server. Works
+when sockets were sent to forks.
+ +Callback should take two arguments `err` and `count`. + +
+getConnections(cb) =>
getMaxListeners
() – Returns the current max listener value for the EventEmitter
which is either
+set by emitter.setMaxListeners(n)
or defaults to {@link defaultMaxListeners}.
getMaxListeners() =>
listen
(port, hostname, backlog, listeningListener) – Start a server listening for connections. A net.Server
can be a TCP or
+an IPC
server depending on what it listens to.
+ +Possible signatures: + +- `server.listen(handle[, backlog][, callback])` +- `server.listen(options[, callback])` +- `server.listen(path[, backlog][, callback])` for `IPC` servers +- `server.listen([port[, host[, backlog]]][, callback])` for TCP servers + +This function is asynchronous. When the server starts listening, the `'listening'` event will be emitted. The last parameter `callback`will be added as a listener for the `'listening'` +event. + +All `listen()` methods can take a `backlog` parameter to specify the maximum +length of the queue of pending connections. The actual length will be determined +by the OS through sysctl settings such as `tcp_max_syn_backlog` and `somaxconn`on Linux. The default value of this parameter is 511 (not 512). + +All {@link Socket} are set to `SO_REUSEADDR` (see [`socket(7)`](https://man7.org/linux/man-pages/man7/socket.7.html) for +details). + +The `server.listen()` method can be called again if and only if there was an +error during the first `server.listen()` call or `server.close()` has been +called. Otherwise, an `ERR_SERVER_ALREADY_LISTEN` error will be thrown. + +One of the most common errors raised when listening is `EADDRINUSE`. +This happens when another server is already listening on the requested`port`/`path`/`handle`. One way to handle this would be to retry +after a certain amount of time: + +```js +server.on('error', e => { + if (e.code === 'EADDRINUSE') { + console.log('Address in use, retrying...') + setTimeout(() => { + server.close() + server.listen(PORT, HOST) + }, 1000) + } +}) +``` + +
+port
number
hostname
string
backlog
number
listeningListener
()
listeningListener() =>
listen(port, hostname, backlog, listeningListener) =>
port
number
hostname
string
listeningListener
()
listeningListener() =>
listen(port, hostname, listeningListener) =>
port
number
backlog
number
listeningListener
()
listeningListener() =>
listen(port, backlog, listeningListener) =>
port
number
listeningListener
()
listeningListener() =>
listen(port, listeningListener) =>
path
string
backlog
number
listeningListener
()
listeningListener() =>
listen(path, backlog, listeningListener) =>
path
string
listeningListener
()
listeningListener() =>
listen(path, listeningListener) =>
options
listeningListener
()
listeningListener() =>
listen(options, listeningListener) =>
handle
any
backlog
number
listeningListener
()
listeningListener() =>
listen(handle, backlog, listeningListener) =>
handle
any
listeningListener
()
listeningListener() =>
listen(handle, listeningListener) =>
listenerCount
(eventName) – Returns the number of listeners listening to the event named eventName
. string | symbol#
eventName
– The name of the event being listened for
+
listenerCount(eventName) =>
listeners
(eventName) – Returns a copy of the array of listeners for the event named eventName
.
+ +```js +server.on('connection', stream => { + console.log('someone connected!') +}) +console.log(util.inspect(server.listeners('connection'))) +// Prints: [ [Function] ] +``` + +
+eventName
string | symbol
listeners(eventName) =>
off
(eventName, listener) – Alias for emitter.removeListener()
. string | symbol#
eventName
off(eventName, listener) =>
on
(event, listener) – 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.
+ +```js +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. + +```js +const myEE = new EventEmitter() +myEE.on('foo', () => console.log('a')) +myEE.prependListener('foo', () => console.log('b')) +myEE.emit('foo') +// Prints: +// b +// a +``` + +
+event
string
listener
(args) any []#
args
listener(args) =>
on(event, listener) =>
event
"close"
listener
()
listener() =>
on(event, listener) =>
event
"connection"
on(event, listener) =>
event
"error"
listener
(err) Error#
err
listener(err) =>
on(event, listener) =>
event
"listening"
listener
()
listener() =>
on(event, listener) =>
event
"checkContinue"
listener
on(event, listener) =>
event
"checkExpectation"
listener
on(event, listener) =>
event
"clientError"
on(event, listener) =>
event
"connect"
listener
(req, socket, head) #
req
listener(req, socket, head) =>
on(event, listener) =>
event
"request"
listener
on(event, listener) =>
event
"upgrade"
listener
(req, socket, head) #
req
listener(req, socket, head) =>
on(event, listener) =>
once
(event, listener) – Adds a one-timelistener
function for the event named eventName
. The
+next time eventName
is triggered, this listener is removed and then invoked.
+ +```js +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. + +```js +const myEE = new EventEmitter() +myEE.once('foo', () => console.log('a')) +myEE.prependOnceListener('foo', () => console.log('b')) +myEE.emit('foo') +// Prints: +// b +// a +``` + +
+event
string
listener
(args) any []#
args
listener(args) =>
once(event, listener) =>
event
"close"
listener
()
listener() =>
once(event, listener) =>
event
"connection"
once(event, listener) =>
event
"error"
listener
(err) Error#
err
listener(err) =>
once(event, listener) =>
event
"listening"
listener
()
listener() =>
once(event, listener) =>
event
"checkContinue"
listener
once(event, listener) =>
event
"checkExpectation"
listener
once(event, listener) =>
event
"clientError"
once(event, listener) =>
event
"connect"
listener
(req, socket, head) #
req
listener(req, socket, head) =>
once(event, listener) =>
event
"request"
listener
once(event, listener) =>
event
"upgrade"
listener
(req, socket, head) #
req
listener(req, socket, head) =>
once(event, listener) =>
prependListener
(event, listener) – 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.
+ +```js +server.prependListener('connection', stream => { + console.log('someone connected!') +}) +``` + +Returns a reference to the `EventEmitter`, so that calls can be chained. + +
+event
string
listener
(args) any []#
args
listener(args) =>
prependListener(event, listener) =>
event
"close"
listener
()
listener() =>
prependListener(event, listener) =>
event
"connection"
prependListener(event, listener) =>
event
"error"
listener
(err) Error#
err
listener(err) =>
prependListener(event, listener) =>
event
"listening"
listener
()
listener() =>
prependListener(event, listener) =>
event
"checkContinue"
listener
prependListener(event, listener) =>
event
"checkExpectation"
listener
prependListener(event, listener) =>
event
"clientError"
prependListener(event, listener) =>
event
"connect"
listener
(req, socket, head) #
req
listener(req, socket, head) =>
prependListener(event, listener) =>
event
"request"
listener
prependListener(event, listener) =>
event
"upgrade"
listener
(req, socket, head) #
req
listener(req, socket, head) =>
prependListener(event, listener) =>
prependOnceListener
(event, listener) – Adds a one-timelistener
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.
+ +```js +server.prependOnceListener('connection', stream => { + console.log('Ah, we have our first user!') +}) +``` + +Returns a reference to the `EventEmitter`, so that calls can be chained. + +
+event
string
listener
(args) any []#
args
listener(args) =>
prependOnceListener(event, listener) =>
event
"close"
listener
()
listener() =>
prependOnceListener(event, listener) =>
event
"connection"
prependOnceListener(event, listener) =>
event
"error"
listener
(err) Error#
err
listener(err) =>
prependOnceListener(event, listener) =>
event
"listening"
listener
()
listener() =>
prependOnceListener(event, listener) =>
event
"checkContinue"
listener
prependOnceListener(event, listener) =>
event
"checkExpectation"
listener
prependOnceListener(event, listener) =>
event
"clientError"
prependOnceListener(event, listener) =>
event
"connect"
listener
(req, socket, head) #
req
listener(req, socket, head) =>
prependOnceListener(event, listener) =>
event
"request"
listener
prependOnceListener(event, listener) =>
event
"upgrade"
listener
(req, socket, head) #
req
listener(req, socket, head) =>
prependOnceListener(event, listener) =>
rawListeners
(eventName) – Returns a copy of the array of listeners for the event named eventName
,
+including any wrappers (such as those created by .once()
).
+ +```js +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') +``` + +
+eventName
string | symbol
rawListeners(eventName) =>
ref
() – Opposite of unref()
, calling ref()
on a previously unref
ed server will_not_ let the program exit if it's the only server left (the default behavior).
+If the server is ref
ed calling ref()
again will have no effect.
ref() =>
removeAllListeners
(event) – 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. + +
+event
string | symbol
removeAllListeners(event) =>
removeListener
(eventName, listener) – Removes the specified listener
from the listener array for the event namedeventName
.
+ +```js +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. + +```js +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 indices 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: + +```js +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. + +
+eventName
string | symbol
listener
(args) any []#
args
listener(args) =>
removeListener(eventName, listener) =>
setMaxListeners
(n) – By default EventEmitter
s 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 toInfinity
(or 0
) to indicate an unlimited number of listeners.
+ +Returns a reference to the `EventEmitter`, so that calls can be chained. + +
+n
number
setMaxListeners(n) =>
setTimeout
(msecs, callback) – Sets the timeout value for sockets, and emits a 'timeout'
event on
+the Server object, passing the socket as an argument, if a timeout
+occurs.
+ +If there is a `'timeout'` event listener on the Server object, then it +will be called with the timed-out socket as an argument. + +By default, the Server does not timeout sockets. However, if a callback +is assigned to the Server's `'timeout'` event, timeouts must be handled +explicitly. + +
+msecs
number
callback
()
callback() =>
setTimeout(msecs, callback) =>
callback
()
callback() =>
setTimeout(callback) =>
unref
() – Calling unref()
on a server will allow the program to exit if this is the only
+active server in the event system. If the server is already unref
ed callingunref()
again will have no effect.
unref() =>
getEventListeners
(emitter, name) – Returns a copy of the array of listeners for the event named eventName
.
+ +For `EventEmitter`s this behaves exactly the same as calling `.listeners` on +the emitter. + +For `EventTarget`s this is the only way to get the event listeners for the +event target. This is useful for debugging and diagnostic purposes. + +```js +const { getEventListeners, EventEmitter } = require('events') + +{ + const ee = new EventEmitter() + const listener = () => console.log('Events are fun') + ee.on('foo', listener) + getEventListeners(ee, 'foo') // [listener] +} +{ + const et = new EventTarget() + const listener = () => console.log('Events are fun') + et.addEventListener('foo', listener) + getEventListeners(et, 'foo') // [listener] +} +``` + +
+emitter
name
string | symbol
getEventListeners(emitter, name) =>
listenerCount
(emitter, eventName) – A class method that returns the number of listeners for the given eventName
registered on the given emitter
.
+ +```js +const { EventEmitter, listenerCount } = require('events') +const myEmitter = new EventEmitter() +myEmitter.on('event', () => {}) +myEmitter.on('event', () => {}) +console.log(listenerCount(myEmitter, 'event')) +// Prints: 2 +``` + +
+emitter
– The emitter to queryeventName
– The event name
+string | symbol
listenerCount(emitter, eventName) =>
on
(emitter, eventName, options) – ```js
+const { on, EventEmitter } = require('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: + +```js +const { on, EventEmitter } = require('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()); +```` + +
+emitter
eventName
– The name of the event being listened forstring
options
on(emitter, eventName, options) =>
once
(emitter, eventName, options) – 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](https://dom.spec.whatwg.org/#interface-eventtarget) interface, which has no special`'error'` event +semantics and does not listen to the `'error'` event. + +```js +const { once, EventEmitter } = require('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.log('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: + +```js +const { EventEmitter, once } = require('events') + +const ee = new EventEmitter() + +once(ee, 'error') + .then(([err]) => console.log('ok', err.message)) + .catch(err => console.log('error', err.message)) + +ee.emit('error', new Error('boom')) + +// Prints: ok boom +``` + +An `AbortSignal` can be used to cancel waiting for the event: + +```js +const { EventEmitter, once } = require('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() // Abort waiting for the event +ee.emit('foo') // Prints: Waiting for the event was canceled! +``` + +
+emitter
eventName
string | symbol
options
once(emitter, eventName, options) =>
emitter
eventName
string
options
once(emitter, eventName, options) =>
setMaxListeners
(n, eventTargets) – By default EventEmitter
s 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 EventEmitter.setMaxListeners()
method allows the default limit to be
+modified (if eventTargets is empty) or modify the limit specified in every EventTarget
| EventEmitter
passed as arguments.
+The value can be set toInfinity
(or 0
) to indicate an unlimited number of listeners.
+ +```js +EventEmitter.setMaxListeners(20) +// Equivalent to +EventEmitter.defaultMaxListeners = 20 + +const eventTarget = new EventTarget() +// Only way to increase limit for `EventTarget` instances +// as these doesn't expose its own `setMaxListeners` method +EventEmitter.setMaxListeners(20, eventTarget) +``` + +
+n
number
eventTargets
setMaxListeners(n, eventTargets) =>
Server
– This class is used to create a TCP or IPC
server.
new Server
() #
options
connections
number
listening
– Indicates whether or not the server is listening for connections.boolean
maxConnections
– Set this property to reject connections when the server's connection count gets
+high.number
+ +It is not recommended to use this option once a socket has been sent to a child +with `child_process.fork()`. + +
+captureRejectionSymbol
typeof captureRejectionSymbol
captureRejections
– Sets or gets the default captureRejection value for all emitters.boolean
defaultMaxListeners
number
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.typeof errorMonitor
+ +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. + +
+addListener
(event, listener) – events.EventEmitter
+1. close
+2. connection
+3. error
+4. listening string#
event
addListener(event, listener) =>
event
"close"
listener
()
listener() =>
addListener(event, listener) =>
event
"connection"
addListener(event, listener) =>
event
"error"
listener
(err) Error#
err
listener(err) =>
addListener(event, listener) =>
event
"listening"
listener
()
listener() =>
addListener(event, listener) =>
address
() – Returns the bound address
, the address family
name, and port
of the server
+as reported by the operating system if listening on an IP socket
+(useful to find which port was assigned when getting an OS-assigned address):{ port: 12346, family: 'IPv4', address: '127.0.0.1' }
.
+ +For a server listening on a pipe or Unix domain socket, the name is returned +as a string. + +```js +const server = net.createServer(socket => { + socket.end('goodbye\n') +}).on('error', err => { + // Handle errors here. + throw err +}) + +// Grab an arbitrary unused port. +server.listen(() => { + console.log('opened server on', server.address()) +}) +``` + +`server.address()` returns `null` before the `'listening'` event has been +emitted or after calling `server.close()`. + +
+address() =>
null
| string | AddressInfoclose
(callback) – Stops the server from accepting new connections and keeps existing
+connections. This function is asynchronous, the server is finally closed
+when all connections are ended and the server emits a 'close'
event.
+The optional callback
will be called once the 'close'
event occurs. Unlike
+that event, it will be called with an Error
as its only argument if the server
+was not open when it was closed.
close(callback) =>
emit
(event, args) – Synchronously calls each of the listeners registered for the event namedeventName
, in the order they were registered, passing the supplied arguments
+to each.
+ +Returns `true` if the event had listeners, `false` otherwise. + +```js +const EventEmitter = require('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 +``` + +
+event
string | symbol
args
any []
emit(event, args) =>
event
"close"
emit(event) =>
event
"connection"
socket
emit(event, socket) =>
event
"error"
err
Error
emit(event, err) =>
event
"listening"
emit(event) =>
eventNames
() – Returns an array listing the events for which the emitter has registered
+listeners. The values in the array are strings or Symbol
s.
+ +```js +const EventEmitter = require('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) ] +``` + +
+eventNames() =>
getConnections
(cb) – Asynchronously get the number of concurrent connections on the server. Works
+when sockets were sent to forks.
+ +Callback should take two arguments `err` and `count`. + +
+getConnections(cb) =>
getMaxListeners
() – Returns the current max listener value for the EventEmitter
which is either
+set by emitter.setMaxListeners(n)
or defaults to {@link defaultMaxListeners}.
getMaxListeners() =>
listen
(port, hostname, backlog, listeningListener) – Start a server listening for connections. A net.Server
can be a TCP or
+an IPC
server depending on what it listens to.
+ +Possible signatures: + +- `server.listen(handle[, backlog][, callback])` +- `server.listen(options[, callback])` +- `server.listen(path[, backlog][, callback])` for `IPC` servers +- `server.listen([port[, host[, backlog]]][, callback])` for TCP servers + +This function is asynchronous. When the server starts listening, the `'listening'` event will be emitted. The last parameter `callback`will be added as a listener for the `'listening'` +event. + +All `listen()` methods can take a `backlog` parameter to specify the maximum +length of the queue of pending connections. The actual length will be determined +by the OS through sysctl settings such as `tcp_max_syn_backlog` and `somaxconn`on Linux. The default value of this parameter is 511 (not 512). + +All {@link Socket} are set to `SO_REUSEADDR` (see [`socket(7)`](https://man7.org/linux/man-pages/man7/socket.7.html) for +details). + +The `server.listen()` method can be called again if and only if there was an +error during the first `server.listen()` call or `server.close()` has been +called. Otherwise, an `ERR_SERVER_ALREADY_LISTEN` error will be thrown. + +One of the most common errors raised when listening is `EADDRINUSE`. +This happens when another server is already listening on the requested`port`/`path`/`handle`. One way to handle this would be to retry +after a certain amount of time: + +```js +server.on('error', e => { + if (e.code === 'EADDRINUSE') { + console.log('Address in use, retrying...') + setTimeout(() => { + server.close() + server.listen(PORT, HOST) + }, 1000) + } +}) +``` + +
+port
number
hostname
string
backlog
number
listeningListener
()
listeningListener() =>
listen(port, hostname, backlog, listeningListener) =>
port
number
hostname
string
listeningListener
()
listeningListener() =>
listen(port, hostname, listeningListener) =>
port
number
backlog
number
listeningListener
()
listeningListener() =>
listen(port, backlog, listeningListener) =>
port
number
listeningListener
()
listeningListener() =>
listen(port, listeningListener) =>
path
string
backlog
number
listeningListener
()
listeningListener() =>
listen(path, backlog, listeningListener) =>
path
string
listeningListener
()
listeningListener() =>
listen(path, listeningListener) =>
options
listeningListener
()
listeningListener() =>
listen(options, listeningListener) =>
handle
any
backlog
number
listeningListener
()
listeningListener() =>
listen(handle, backlog, listeningListener) =>
handle
any
listeningListener
()
listeningListener() =>
listen(handle, listeningListener) =>
listenerCount
(eventName) – Returns the number of listeners listening to the event named eventName
. string | symbol#
eventName
– The name of the event being listened for
+
listenerCount(eventName) =>
listeners
(eventName) – Returns a copy of the array of listeners for the event named eventName
.
+ +```js +server.on('connection', stream => { + console.log('someone connected!') +}) +console.log(util.inspect(server.listeners('connection'))) +// Prints: [ [Function] ] +``` + +
+eventName
string | symbol
listeners(eventName) =>
off
(eventName, listener) – Alias for emitter.removeListener()
. string | symbol#
eventName
off(eventName, listener) =>
on
(event, listener) – 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.
+ +```js +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. + +```js +const myEE = new EventEmitter() +myEE.on('foo', () => console.log('a')) +myEE.prependListener('foo', () => console.log('b')) +myEE.emit('foo') +// Prints: +// b +// a +``` + +
+event
string
listener
(args) any []#
args
listener(args) =>
on(event, listener) =>
event
"close"
listener
()
listener() =>
on(event, listener) =>
event
"connection"
on(event, listener) =>
event
"error"
listener
(err) Error#
err
listener(err) =>
on(event, listener) =>
event
"listening"
listener
()
listener() =>
on(event, listener) =>
once
(event, listener) – Adds a one-timelistener
function for the event named eventName
. The
+next time eventName
is triggered, this listener is removed and then invoked.
+ +```js +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. + +```js +const myEE = new EventEmitter() +myEE.once('foo', () => console.log('a')) +myEE.prependOnceListener('foo', () => console.log('b')) +myEE.emit('foo') +// Prints: +// b +// a +``` + +
+event
string
listener
(args) any []#
args
listener(args) =>
once(event, listener) =>
event
"close"
listener
()
listener() =>
once(event, listener) =>
event
"connection"
once(event, listener) =>
event
"error"
listener
(err) Error#
err
listener(err) =>
once(event, listener) =>
event
"listening"
listener
()
listener() =>
once(event, listener) =>
prependListener
(event, listener) – 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.
+ +```js +server.prependListener('connection', stream => { + console.log('someone connected!') +}) +``` + +Returns a reference to the `EventEmitter`, so that calls can be chained. + +
+event
string
listener
(args) any []#
args
listener(args) =>
prependListener(event, listener) =>
event
"close"
listener
()
listener() =>
prependListener(event, listener) =>
event
"connection"
prependListener(event, listener) =>
event
"error"
listener
(err) Error#
err
listener(err) =>
prependListener(event, listener) =>
event
"listening"
listener
()
listener() =>
prependListener(event, listener) =>
prependOnceListener
(event, listener) – Adds a one-timelistener
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.
+ +```js +server.prependOnceListener('connection', stream => { + console.log('Ah, we have our first user!') +}) +``` + +Returns a reference to the `EventEmitter`, so that calls can be chained. + +
+event
string
listener
(args) any []#
args
listener(args) =>
prependOnceListener(event, listener) =>
event
"close"
listener
()
listener() =>
prependOnceListener(event, listener) =>
event
"connection"
prependOnceListener(event, listener) =>
event
"error"
listener
(err) Error#
err
listener(err) =>
prependOnceListener(event, listener) =>
event
"listening"
listener
()
listener() =>
prependOnceListener(event, listener) =>
rawListeners
(eventName) – Returns a copy of the array of listeners for the event named eventName
,
+including any wrappers (such as those created by .once()
).
+ +```js +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') +``` + +
+eventName
string | symbol
rawListeners(eventName) =>
ref
() – Opposite of unref()
, calling ref()
on a previously unref
ed server will_not_ let the program exit if it's the only server left (the default behavior).
+If the server is ref
ed calling ref()
again will have no effect.
ref() =>
removeAllListeners
(event) – 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. + +
+event
string | symbol
removeAllListeners(event) =>
removeListener
(eventName, listener) – Removes the specified listener
from the listener array for the event namedeventName
.
+ +```js +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. + +```js +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 indices 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: + +```js +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. + +
+eventName
string | symbol
listener
(args) any []#
args
listener(args) =>
removeListener(eventName, listener) =>
setMaxListeners
(n) – By default EventEmitter
s 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 toInfinity
(or 0
) to indicate an unlimited number of listeners.
+ +Returns a reference to the `EventEmitter`, so that calls can be chained. + +
+n
number
setMaxListeners(n) =>
unref
() – Calling unref()
on a server will allow the program to exit if this is the only
+active server in the event system. If the server is already unref
ed callingunref()
again will have no effect.
unref() =>
getEventListeners
(emitter, name) – Returns a copy of the array of listeners for the event named eventName
.
+ +For `EventEmitter`s this behaves exactly the same as calling `.listeners` on +the emitter. + +For `EventTarget`s this is the only way to get the event listeners for the +event target. This is useful for debugging and diagnostic purposes. + +```js +const { getEventListeners, EventEmitter } = require('events') + +{ + const ee = new EventEmitter() + const listener = () => console.log('Events are fun') + ee.on('foo', listener) + getEventListeners(ee, 'foo') // [listener] +} +{ + const et = new EventTarget() + const listener = () => console.log('Events are fun') + et.addEventListener('foo', listener) + getEventListeners(et, 'foo') // [listener] +} +``` + +
+emitter
name
string | symbol
getEventListeners(emitter, name) =>
listenerCount
(emitter, eventName) – A class method that returns the number of listeners for the given eventName
registered on the given emitter
.
+ +```js +const { EventEmitter, listenerCount } = require('events') +const myEmitter = new EventEmitter() +myEmitter.on('event', () => {}) +myEmitter.on('event', () => {}) +console.log(listenerCount(myEmitter, 'event')) +// Prints: 2 +``` + +
+emitter
– The emitter to queryeventName
– The event name
+string | symbol
listenerCount(emitter, eventName) =>
on
(emitter, eventName, options) – ```js
+const { on, EventEmitter } = require('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: + +```js +const { on, EventEmitter } = require('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()); +```` + +
+emitter
eventName
– The name of the event being listened forstring
options
on(emitter, eventName, options) =>
once
(emitter, eventName, options) – 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](https://dom.spec.whatwg.org/#interface-eventtarget) interface, which has no special`'error'` event +semantics and does not listen to the `'error'` event. + +```js +const { once, EventEmitter } = require('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.log('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: + +```js +const { EventEmitter, once } = require('events') + +const ee = new EventEmitter() + +once(ee, 'error') + .then(([err]) => console.log('ok', err.message)) + .catch(err => console.log('error', err.message)) + +ee.emit('error', new Error('boom')) + +// Prints: ok boom +``` + +An `AbortSignal` can be used to cancel waiting for the event: + +```js +const { EventEmitter, once } = require('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() // Abort waiting for the event +ee.emit('foo') // Prints: Waiting for the event was canceled! +``` + +
+emitter
eventName
string | symbol
options
once(emitter, eventName, options) =>
emitter
eventName
string
options
once(emitter, eventName, options) =>
setMaxListeners
(n, eventTargets) – By default EventEmitter
s 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 EventEmitter.setMaxListeners()
method allows the default limit to be
+modified (if eventTargets is empty) or modify the limit specified in every EventTarget
| EventEmitter
passed as arguments.
+The value can be set toInfinity
(or 0
) to indicate an unlimited number of listeners.
+ +```js +EventEmitter.setMaxListeners(20) +// Equivalent to +EventEmitter.defaultMaxListeners = 20 + +const eventTarget = new EventTarget() +// Only way to increase limit for `EventTarget` instances +// as these doesn't expose its own `setMaxListeners` method +EventEmitter.setMaxListeners(20, eventTarget) +``` + +
+n
number
eventTargets
setMaxListeners(n, eventTargets) =>
Server
clients
Set<T>
options
path
string
captureRejectionSymbol
typeof captureRejectionSymbol
captureRejections
– Sets or gets the default captureRejection value for all emitters.boolean
defaultMaxListeners
number
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.typeof errorMonitor
+ +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. + +
+addListener
(event, cb) – Alias for emitter.on(eventName, listener)
. #
event
"connection"
addListener(event, cb) =>
event
"error"
cb
(err) Error#
err
cb(err) =>
addListener(event, cb) =>
event
"headers"
cb
(headers, request) cb(headers, request) =>
addListener(event, cb) =>
event
"close"
| "listening"
cb
()
cb() =>
addListener(event, cb) =>
event
string | symbol
listener
(args) any []#
args
listener(args) =>
addListener(event, listener) =>
address
()
address() =>
close
(cb)
close(cb) =>
emit
(eventName, args) – Synchronously calls each of the listeners registered for the event namedeventName
, in the order they were registered, passing the supplied arguments
+to each.
+ +Returns `true` if the event had listeners, `false` otherwise. + +```js +const EventEmitter = require('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 +``` + +
+eventName
string | symbol
args
any []
emit(eventName, args) =>
eventNames
() – Returns an array listing the events for which the emitter has registered
+listeners. The values in the array are strings or Symbol
s.
+ +```js +const EventEmitter = require('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) ] +``` + +
+eventNames() =>
getMaxListeners
() – Returns the current max listener value for the EventEmitter
which is either
+set by emitter.setMaxListeners(n)
or defaults to {@link defaultMaxListeners}.
getMaxListeners() =>
handleUpgrade
(request, socket, upgradeHead, callback) #
request
handleUpgrade(request, socket, upgradeHead, callback) =>
listenerCount
(eventName) – Returns the number of listeners listening to the event named eventName
. string | symbol#
eventName
– The name of the event being listened for
+
listenerCount(eventName) =>
listeners
(eventName) – Returns a copy of the array of listeners for the event named eventName
.
+ +```js +server.on('connection', stream => { + console.log('someone connected!') +}) +console.log(util.inspect(server.listeners('connection'))) +// Prints: [ [Function] ] +``` + +
+eventName
string | symbol
listeners(eventName) =>
off
(event, cb) – Alias for emitter.removeListener()
. #
event
"connection"
off(event, cb) =>
event
"error"
off(event, cb) =>
event
"headers"
cb
(this, headers, request) cb(this, headers, request) =>
off(event, cb) =>
event
"close"
| "listening"
off(event, cb) =>
event
string | symbol
off(event, listener) =>
on
(event, cb) – 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.
+ +```js +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. + +```js +const myEE = new EventEmitter() +myEE.on('foo', () => console.log('a')) +myEE.prependListener('foo', () => console.log('b')) +myEE.emit('foo') +// Prints: +// b +// a +``` + +
+event
"connection"
cb
(this, socket, request) #
request
cb(this, socket, request) =>
on(event, cb) =>
event
"error"
on(event, cb) =>
event
"headers"
cb
(this, headers, request) cb(this, headers, request) =>
on(event, cb) =>
event
"close"
| "listening"
on(event, cb) =>
event
string | symbol
on(event, listener) =>
once
(event, cb) – Adds a one-timelistener
function for the event named eventName
. The
+next time eventName
is triggered, this listener is removed and then invoked.
+ +```js +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. + +```js +const myEE = new EventEmitter() +myEE.once('foo', () => console.log('a')) +myEE.prependOnceListener('foo', () => console.log('b')) +myEE.emit('foo') +// Prints: +// b +// a +``` + +
+event
"connection"
cb
(this, socket, request) #
request
cb(this, socket, request) =>
once(event, cb) =>
event
"error"
once(event, cb) =>
event
"headers"
cb
(this, headers, request) cb(this, headers, request) =>
once(event, cb) =>
event
"close"
| "listening"
once(event, cb) =>
event
string | symbol
once(event, listener) =>
prependListener
(eventName, listener) – 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.
+ +```js +server.prependListener('connection', stream => { + console.log('someone connected!') +}) +``` + +Returns a reference to the `EventEmitter`, so that calls can be chained. + +
+eventName
– The name of the event.string | symbol
listener
(args) any []#
args
listener(args) =>
prependListener(eventName, listener) =>
prependOnceListener
(eventName, listener) – Adds a one-timelistener
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.
+ +```js +server.prependOnceListener('connection', stream => { + console.log('Ah, we have our first user!') +}) +``` + +Returns a reference to the `EventEmitter`, so that calls can be chained. + +
+eventName
– The name of the event.string | symbol
listener
(args) any []#
args
listener(args) =>
prependOnceListener(eventName, listener) =>
rawListeners
(eventName) – Returns a copy of the array of listeners for the event named eventName
,
+including any wrappers (such as those created by .once()
).
+ +```js +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') +``` + +
+eventName
string | symbol
rawListeners(eventName) =>
removeAllListeners
(event) – 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. + +
+event
string | symbol
removeAllListeners(event) =>
removeListener
(event, cb) – Removes the specified listener
from the listener array for the event namedeventName
.
+ +```js +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. + +```js +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 indices 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: + +```js +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. + +
+event
"connection"
removeListener(event, cb) =>
event
"error"
cb
(err) Error#
err
cb(err) =>
removeListener(event, cb) =>
event
"headers"
cb
(headers, request) cb(headers, request) =>
removeListener(event, cb) =>
event
"close"
| "listening"
cb
()
cb() =>
removeListener(event, cb) =>
event
string | symbol
listener
(args) any []#
args
listener(args) =>
removeListener(event, listener) =>
setMaxListeners
(n) – By default EventEmitter
s 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 toInfinity
(or 0
) to indicate an unlimited number of listeners.
+ +Returns a reference to the `EventEmitter`, so that calls can be chained. + +
+n
number
setMaxListeners(n) =>
shouldHandle
(request) #
request
shouldHandle(request) =>
getEventListeners
(emitter, name) – Returns a copy of the array of listeners for the event named eventName
.
+ +For `EventEmitter`s this behaves exactly the same as calling `.listeners` on +the emitter. + +For `EventTarget`s this is the only way to get the event listeners for the +event target. This is useful for debugging and diagnostic purposes. + +```js +const { getEventListeners, EventEmitter } = require('events') + +{ + const ee = new EventEmitter() + const listener = () => console.log('Events are fun') + ee.on('foo', listener) + getEventListeners(ee, 'foo') // [listener] +} +{ + const et = new EventTarget() + const listener = () => console.log('Events are fun') + et.addEventListener('foo', listener) + getEventListeners(et, 'foo') // [listener] +} +``` + +
+emitter
name
string | symbol
getEventListeners(emitter, name) =>
listenerCount
(emitter, eventName) – A class method that returns the number of listeners for the given eventName
registered on the given emitter
.
+ +```js +const { EventEmitter, listenerCount } = require('events') +const myEmitter = new EventEmitter() +myEmitter.on('event', () => {}) +myEmitter.on('event', () => {}) +console.log(listenerCount(myEmitter, 'event')) +// Prints: 2 +``` + +
+emitter
– The emitter to queryeventName
– The event name
+string | symbol
listenerCount(emitter, eventName) =>
on
(emitter, eventName, options) – ```js
+const { on, EventEmitter } = require('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: + +```js +const { on, EventEmitter } = require('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()); +```` + +
+emitter
eventName
– The name of the event being listened forstring
options
on(emitter, eventName, options) =>
once
(emitter, eventName, options) – 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](https://dom.spec.whatwg.org/#interface-eventtarget) interface, which has no special`'error'` event +semantics and does not listen to the `'error'` event. + +```js +const { once, EventEmitter } = require('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.log('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: + +```js +const { EventEmitter, once } = require('events') + +const ee = new EventEmitter() + +once(ee, 'error') + .then(([err]) => console.log('ok', err.message)) + .catch(err => console.log('error', err.message)) + +ee.emit('error', new Error('boom')) + +// Prints: ok boom +``` + +An `AbortSignal` can be used to cancel waiting for the event: + +```js +const { EventEmitter, once } = require('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() // Abort waiting for the event +ee.emit('foo') // Prints: Waiting for the event was canceled! +``` + +
+emitter
eventName
string | symbol
options
once(emitter, eventName, options) =>
emitter
eventName
string
options
once(emitter, eventName, options) =>
setMaxListeners
(n, eventTargets) – By default EventEmitter
s 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 EventEmitter.setMaxListeners()
method allows the default limit to be
+modified (if eventTargets is empty) or modify the limit specified in every EventTarget
| EventEmitter
passed as arguments.
+The value can be set toInfinity
(or 0
) to indicate an unlimited number of listeners.
+ +```js +EventEmitter.setMaxListeners(20) +// Equivalent to +EventEmitter.defaultMaxListeners = 20 + +const eventTarget = new EventTarget() +// Only way to increase limit for `EventTarget` instances +// as these doesn't expose its own `setMaxListeners` method +EventEmitter.setMaxListeners(20, eventTarget) +``` + +
+n
number
eventTargets
setMaxListeners(n, eventTargets) =>
Server
typeof captureRejectionSymbol boolean typeof errorMonitor
+
+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.
+
+#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L891 constructor
(options) – Creates the proxy server with specified options.
#
src/.fastpm/-/@types/node@17.0.45/events.d.ts#L301 captureRejectionSymbol
#
src/.fastpm/-/@types/node@17.0.45/events.d.ts#L306 captureRejections
– Sets or gets the default captureRejection value for all emitters.#
src/.fastpm/-/@types/node@17.0.45/events.d.ts#L300 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.#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L953 addListener
(event, listener) – Alias for emitter.on(eventName, listener)
.
addListener(event, listener) =>
close
(callback) – A function that closes the inner webserver and stops listening on given port callback() => #
callback
()
void
close(callback) =>
emit
(event, args) – Synchronously calls each of the listeners registered for the event namedeventName
, in the order they were registered, passing the supplied arguments
+to each.
+ +Returns `true` if the event had listeners, `false` otherwise. + +```js +const EventEmitter = require('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 +``` + +
+event
string
args
any []
emit(event, args) =>
eventNames
() – Returns an array listing the events for which the emitter has registered
+listeners. The values in the array are strings or Symbol
s.
+ +```js +const EventEmitter = require('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) ] +``` + +
+eventNames() =>
getMaxListeners
() – Returns the current max listener value for the EventEmitter
which is either
+set by emitter.setMaxListeners(n)
or defaults to {@link defaultMaxListeners}.
getMaxListeners() =>
listen
(port) – A function that wraps the object in a webserver, for your convenience number#
port
– Port to listen on
+
listen(port) =>
listenerCount
(type) – Returns the number of listeners listening to the event named eventName
. string#
type
listenerCount(type) =>
listeners
(event) – Returns a copy of the array of listeners for the event named eventName
.
+ +```js +server.on('connection', stream => { + console.log('someone connected!') +}) +console.log(util.inspect(server.listeners('connection'))) +// Prints: [ [Function] ] +``` + +
+event
string
listeners(event) =>
() =>
off
(eventName, listener) – Alias for emitter.removeListener()
. string | symbol#
eventName
off(eventName, listener) =>
on
(event, listener) – 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.
+ +```js +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. + +```js +const myEE = new EventEmitter() +myEE.on('foo', () => console.log('a')) +myEE.prependListener('foo', () => console.log('b')) +myEE.emit('foo') +// Prints: +// b +// a +``` + +
+event
string
listener
()
listener() =>
on(event, listener) =>
event
"error"
listener
on(event, listener) =>
event
"start"
listener
(req, res, target) listener(req, res, target) =>
on(event, listener) =>
event
"proxyReq"
listener
(proxyReq, req, res, options) on(event, listener) =>
event
"proxyRes"
listener
(proxyRes, req, res) listener(proxyRes, req, res) =>
on(event, listener) =>
event
"proxyReqWs"
listener
(proxyReq, req, socket, options, head) on(event, listener) =>
event
"econnreset"
listener
(err, req, res, target) on(event, listener) =>
event
"end"
listener
(req, res, proxyRes) listener(req, res, proxyRes) =>
on(event, listener) =>
event
"close"
listener
(proxyRes, proxySocket, proxyHead) listener(proxyRes, proxySocket, proxyHead) =>
on(event, listener) =>
once
(event, listener) – Adds a one-timelistener
function for the event named eventName
. The
+next time eventName
is triggered, this listener is removed and then invoked.
+ +```js +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. + +```js +const myEE = new EventEmitter() +myEE.once('foo', () => console.log('a')) +myEE.prependOnceListener('foo', () => console.log('b')) +myEE.emit('foo') +// Prints: +// b +// a +``` + +
+event
string
listener
()
listener() =>
once(event, listener) =>
prependListener
(eventName, listener) – 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.
+ +```js +server.prependListener('connection', stream => { + console.log('someone connected!') +}) +``` + +Returns a reference to the `EventEmitter`, so that calls can be chained. + +
+eventName
– The name of the event.string | symbol
listener
(args) any []#
args
listener(args) =>
prependListener(eventName, listener) =>
prependOnceListener
(eventName, listener) – Adds a one-timelistener
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.
+ +```js +server.prependOnceListener('connection', stream => { + console.log('Ah, we have our first user!') +}) +``` + +Returns a reference to the `EventEmitter`, so that calls can be chained. + +
+eventName
– The name of the event.string | symbol
listener
(args) any []#
args
listener(args) =>
prependOnceListener(eventName, listener) =>
rawListeners
(eventName) – Returns a copy of the array of listeners for the event named eventName
,
+including any wrappers (such as those created by .once()
).
+ +```js +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') +``` + +
+eventName
string | symbol
rawListeners(eventName) =>
removeAllListeners
(event) – 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. + +
+event
string
removeAllListeners(event) =>
removeListener
(event, listener) – Removes the specified listener
from the listener array for the event namedeventName
.
+ +```js +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. + +```js +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 indices 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: + +```js +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. + +
+event
string
listener
()
listener() =>
removeListener(event, listener) =>
setMaxListeners
(n) – By default EventEmitter
s 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 toInfinity
(or 0
) to indicate an unlimited number of listeners.
+ +Returns a reference to the `EventEmitter`, so that calls can be chained. + +
+n
number
setMaxListeners(n) =>
web
(req, res, options, callback) – Used for proxying regular HTTP(S) requestsws
(req, socket, head, options, callback) – Used for proxying regular HTTP(S) requestscreateProxy
(options) – Creates the proxy server with specified options. #
options
– Config object passed to the proxy
createProxy(options) =>
createProxyServer
(options) – Creates the proxy server with specified options. #
options
– Config object passed to the proxy
createProxyServer(options) =>
createServer
(options) – Creates the proxy server with specified options. #
options
– Config object passed to the proxy
createServer(options) =>
getEventListeners
(emitter, name) – Returns a copy of the array of listeners for the event named eventName
.
+ +For `EventEmitter`s this behaves exactly the same as calling `.listeners` on +the emitter. + +For `EventTarget`s this is the only way to get the event listeners for the +event target. This is useful for debugging and diagnostic purposes. + +```js +const { getEventListeners, EventEmitter } = require('events') + +{ + const ee = new EventEmitter() + const listener = () => console.log('Events are fun') + ee.on('foo', listener) + getEventListeners(ee, 'foo') // [listener] +} +{ + const et = new EventTarget() + const listener = () => console.log('Events are fun') + et.addEventListener('foo', listener) + getEventListeners(et, 'foo') // [listener] +} +``` + +
+emitter
name
string | symbol
getEventListeners(emitter, name) =>
listenerCount
(emitter, eventName) – A class method that returns the number of listeners for the given eventName
registered on the given emitter
.
+ +```js +const { EventEmitter, listenerCount } = require('events') +const myEmitter = new EventEmitter() +myEmitter.on('event', () => {}) +myEmitter.on('event', () => {}) +console.log(listenerCount(myEmitter, 'event')) +// Prints: 2 +``` + +
+emitter
– The emitter to queryeventName
– The event name
+string | symbol
listenerCount(emitter, eventName) =>
on
(emitter, eventName, options) – ```js
+const { on, EventEmitter } = require('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: + +```js +const { on, EventEmitter } = require('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()); +```` + +
+emitter
eventName
– The name of the event being listened forstring
options
on(emitter, eventName, options) =>
once
(emitter, eventName, options) – 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](https://dom.spec.whatwg.org/#interface-eventtarget) interface, which has no special`'error'` event +semantics and does not listen to the `'error'` event. + +```js +const { once, EventEmitter } = require('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.log('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: + +```js +const { EventEmitter, once } = require('events') + +const ee = new EventEmitter() + +once(ee, 'error') + .then(([err]) => console.log('ok', err.message)) + .catch(err => console.log('error', err.message)) + +ee.emit('error', new Error('boom')) + +// Prints: ok boom +``` + +An `AbortSignal` can be used to cancel waiting for the event: + +```js +const { EventEmitter, once } = require('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() // Abort waiting for the event +ee.emit('foo') // Prints: Waiting for the event was canceled! +``` + +
+emitter
eventName
string | symbol
options
once(emitter, eventName, options) =>
emitter
eventName
string
options
once(emitter, eventName, options) =>
setMaxListeners
(n, eventTargets) – By default EventEmitter
s 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 EventEmitter.setMaxListeners()
method allows the default limit to be
+modified (if eventTargets is empty) or modify the limit specified in every EventTarget
| EventEmitter
passed as arguments.
+The value can be set toInfinity
(or 0
) to indicate an unlimited number of listeners.
+ +```js +EventEmitter.setMaxListeners(20) +// Equivalent to +EventEmitter.defaultMaxListeners = 20 + +const eventTarget = new EventTarget() +// Only way to increase limit for `EventTarget` instances +// as these doesn't expose its own `setMaxListeners` method +EventEmitter.setMaxListeners(20, eventTarget) +``` + +
+n
number
eventTargets
setMaxListeners(n, eventTargets) =>
Server
– See http.Server
for more information. number
+
+In case of inactivity, the rules defined in `server.timeout` apply. However,
+that inactivity based timeout would still allow the connection to be kept open
+if the headers are being sent very slowly (by default, up to a byte per 2
+minutes). In order to prevent this, whenever header data arrives an additional
+check is made that more than `server.headersTimeout` milliseconds has not
+passed since the connection was established. If the check fails, a `'timeout'`event is emitted on the server object, and (by default) the socket is destroyed.
+See `server.timeout` for more information on how timeout behavior can be
+customized.
+
+ number
+
+A value of `0` will disable the keep-alive timeout behavior on incoming
+connections.
+A value of `0` makes the http server behave similarly to Node.js versions prior
+to 8.0.0, which did not have a keep-alive timeout.
+
+The socket timeout logic is set up on connection, so changing this value only
+affects new connections to the server, not any existing connections.
+
+ boolean number
+
+It is not recommended to use this option once a socket has been sent to a child
+with `child_process.fork()`.
+
+
+
+A value of `0` will disable the limit.
+
+When the limit is reached it will set the `Connection` header value to `close`,
+but will not actually close the connection, subsequent requests sent
+after the limit is reached will get `503 Service Unavailable` as a response.
+
+ number
+
+If the timeout expires, the server responds with status 408 without
+forwarding the request to the request listener and then closes the connection.
+
+It must be set to a non-zero value (e.g. 120 seconds) to protect against
+potential Denial-of-Service attacks in case the server is deployed without a
+reverse proxy in front.
+
+ number
+
+A value of `0` will disable the timeout behavior on incoming connections.
+
+The socket timeout logic is set up on connection, so changing this
+value only affects new connections to the server, not any existing connections.
+
+ typeof captureRejectionSymbol boolean typeof errorMonitor
+
+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.
+
+
+
+When there are multiple matching contexts, the most recently added one is
+used.
+
+ string addContext(hostname, context) => #
src/.fastpm/-/@types/node@17.0.45/https.d.ts#L35 constructor
(requestListener)
#
new Server
()
#
src/.fastpm/-/@types/node@17.0.45/http.d.ts#L224 headersTimeout
– Limit the amount of time the parser will wait to receive the complete HTTP
+headers.#
src/.fastpm/-/@types/node@17.0.45/http.d.ts#L240 keepAliveTimeout
– The number of milliseconds of inactivity a server needs to wait for additional
+incoming data, after it has finished writing the last response, before a socket
+will be destroyed. If the server receives new data before the keep-alive
+timeout has fired, it will reset the regular inactivity timeout, i.e.,server.timeout
.#
src/.fastpm/-/@types/node@17.0.45/net.d.ts#L527 listening
– Indicates whether or not the server is listening for connections.#
src/.fastpm/-/@types/node@17.0.45/net.d.ts#L521 maxConnections
– Set this property to reject connections when the server's connection count gets
+high.#
src/.fastpm/-/@types/node@17.0.45/http.d.ts#L186 maxHeadersCount
– Limits maximum incoming headers count. If set to 0, no limit will be applied.null
| number#
src/.fastpm/-/@types/node@17.0.45/http.d.ts#L198 maxRequestsPerSocket
– The maximum number of requests socket can handle
+before closing keep alive connection.null
| number#
src/.fastpm/-/@types/node@17.0.45/http.d.ts#L253 requestTimeout
– Sets the timeout value in milliseconds for receiving the entire request from
+the client.#
src/.fastpm/-/@types/node@17.0.45/http.d.ts#L209 timeout
– The number of milliseconds of inactivity before a socket is presumed
+to have timed out.#
src/.fastpm/-/@types/node@17.0.45/events.d.ts#L301 captureRejectionSymbol
#
src/.fastpm/-/@types/node@17.0.45/events.d.ts#L306 captureRejections
– Sets or gets the default captureRejection value for all emitters.#
src/.fastpm/-/@types/node@17.0.45/events.d.ts#L300 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.#
src/.fastpm/-/@types/node@17.0.45/tls.d.ts#L563 addContext
(hostname, context) – The server.addContext()
method adds a secure context that will be used if
+the client request's SNI name matches the supplied hostname
(or wildcard).
#
hostname
– A SNI host name or wildcard (e.g. '*'
)#
context
– An object containing any of the possible properties from the {@link createSecureContext} options
arguments (e.g. key
, cert
, ca
, etc).
+void
addListener
(event, listener) – events.EventEmitter
+1. close
+2. connection
+3. error
+4. listening string#
event
addListener(event, listener) =>
event
"keylog"
addListener(event, listener) =>
event
"newSession"
listener
(sessionId, sessionData, callback)
listener(sessionId, sessionData, callback) =>
addListener(event, listener) =>
event
"OCSPRequest"
listener
(certificate, issuer, callback)
listener(certificate, issuer, callback) =>
addListener(event, listener) =>
event
"resumeSession"
listener
(sessionId, callback)
listener(sessionId, callback) =>
addListener(event, listener) =>
event
"secureConnection"
addListener(event, listener) =>
event
"tlsClientError"
addListener(event, listener) =>
event
"close"
listener
()
listener() =>
addListener(event, listener) =>
event
"connection"
addListener(event, listener) =>
event
"error"
listener
(err) Error#
err
listener(err) =>
addListener(event, listener) =>
event
"listening"
listener
()
listener() =>
addListener(event, listener) =>
event
"checkContinue"
listener
addListener(event, listener) =>
event
"checkExpectation"
listener
addListener(event, listener) =>
event
"clientError"
addListener(event, listener) =>
event
"connect"
listener
(req, socket, head) #
req
listener(req, socket, head) =>
addListener(event, listener) =>
event
"request"
listener
addListener(event, listener) =>
event
"upgrade"
listener
(req, socket, head) #
req
listener(req, socket, head) =>
addListener(event, listener) =>
address
() – Returns the bound address
, the address family
name, and port
of the server
+as reported by the operating system if listening on an IP socket
+(useful to find which port was assigned when getting an OS-assigned address):{ port: 12346, family: 'IPv4', address: '127.0.0.1' }
.
+ +For a server listening on a pipe or Unix domain socket, the name is returned +as a string. + +```js +const server = net.createServer(socket => { + socket.end('goodbye\n') +}).on('error', err => { + // Handle errors here. + throw err +}) + +// Grab an arbitrary unused port. +server.listen(() => { + console.log('opened server on', server.address()) +}) +``` + +`server.address()` returns `null` before the `'listening'` event has been +emitted or after calling `server.close()`. + +
+address() =>
null
| string | AddressInfoclose
(callback) – Stops the server from accepting new connections and keeps existing
+connections. This function is asynchronous, the server is finally closed
+when all connections are ended and the server emits a 'close'
event.
+The optional callback
will be called once the 'close'
event occurs. Unlike
+that event, it will be called with an Error
as its only argument if the server
+was not open when it was closed.
close(callback) =>
emit
(event, args) – Synchronously calls each of the listeners registered for the event namedeventName
, in the order they were registered, passing the supplied arguments
+to each.
+ +Returns `true` if the event had listeners, `false` otherwise. + +```js +const EventEmitter = require('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 +``` + +
+event
string
args
any []
emit(event, args) =>
event
"keylog"
line
tlsSocket
emit(event, line, tlsSocket) =>
event
"newSession"
sessionId
sessionData
emit(event, sessionId, sessionData, callback) =>
event
"OCSPRequest"
certificate
issuer
emit(event, certificate, issuer, callback) =>
event
"resumeSession"
sessionId
emit(event, sessionId, callback) =>
event
"secureConnection"
tlsSocket
emit(event, tlsSocket) =>
event
"tlsClientError"
err
Error
tlsSocket
emit(event, err, tlsSocket) =>
event
"close"
emit(event) =>
event
"connection"
socket
emit(event, socket) =>
event
"error"
err
Error
emit(event, err) =>
event
"listening"
emit(event) =>
event
"checkContinue"
req
res
emit(event, req, res) =>
event
"checkExpectation"
req
res
emit(event, req, res) =>
event
"clientError"
err
Error
socket
emit(event, err, socket) =>
event
"connect"
req
socket
head
emit(event, req, socket, head) =>
event
"request"
req
res
emit(event, req, res) =>
event
"upgrade"
req
socket
head
emit(event, req, socket, head) =>
eventNames
() – Returns an array listing the events for which the emitter has registered
+listeners. The values in the array are strings or Symbol
s.
+ +```js +const EventEmitter = require('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) ] +``` + +
+eventNames() =>
getConnections
(cb) – Asynchronously get the number of concurrent connections on the server. Works
+when sockets were sent to forks.
+ +Callback should take two arguments `err` and `count`. + +
+getConnections(cb) =>
getMaxListeners
() – Returns the current max listener value for the EventEmitter
which is either
+set by emitter.setMaxListeners(n)
or defaults to {@link defaultMaxListeners}.
getMaxListeners() =>
getTicketKeys
() – Returns the session ticket keys.
+ +See `Session Resumption` for more information. + +
+getTicketKeys() =>
listen
(port, hostname, backlog, listeningListener) – Start a server listening for connections. A net.Server
can be a TCP or
+an IPC
server depending on what it listens to.
+ +Possible signatures: + +- `server.listen(handle[, backlog][, callback])` +- `server.listen(options[, callback])` +- `server.listen(path[, backlog][, callback])` for `IPC` servers +- `server.listen([port[, host[, backlog]]][, callback])` for TCP servers + +This function is asynchronous. When the server starts listening, the `'listening'` event will be emitted. The last parameter `callback`will be added as a listener for the `'listening'` +event. + +All `listen()` methods can take a `backlog` parameter to specify the maximum +length of the queue of pending connections. The actual length will be determined +by the OS through sysctl settings such as `tcp_max_syn_backlog` and `somaxconn`on Linux. The default value of this parameter is 511 (not 512). + +All {@link Socket} are set to `SO_REUSEADDR` (see [`socket(7)`](https://man7.org/linux/man-pages/man7/socket.7.html) for +details). + +The `server.listen()` method can be called again if and only if there was an +error during the first `server.listen()` call or `server.close()` has been +called. Otherwise, an `ERR_SERVER_ALREADY_LISTEN` error will be thrown. + +One of the most common errors raised when listening is `EADDRINUSE`. +This happens when another server is already listening on the requested`port`/`path`/`handle`. One way to handle this would be to retry +after a certain amount of time: + +```js +server.on('error', e => { + if (e.code === 'EADDRINUSE') { + console.log('Address in use, retrying...') + setTimeout(() => { + server.close() + server.listen(PORT, HOST) + }, 1000) + } +}) +``` + +
+port
number
hostname
string
backlog
number
listeningListener
()
listeningListener() =>
listen(port, hostname, backlog, listeningListener) =>
port
number
hostname
string
listeningListener
()
listeningListener() =>
listen(port, hostname, listeningListener) =>
port
number
backlog
number
listeningListener
()
listeningListener() =>
listen(port, backlog, listeningListener) =>
port
number
listeningListener
()
listeningListener() =>
listen(port, listeningListener) =>
path
string
backlog
number
listeningListener
()
listeningListener() =>
listen(path, backlog, listeningListener) =>
path
string
listeningListener
()
listeningListener() =>
listen(path, listeningListener) =>
options
listeningListener
()
listeningListener() =>
listen(options, listeningListener) =>
handle
any
backlog
number
listeningListener
()
listeningListener() =>
listen(handle, backlog, listeningListener) =>
handle
any
listeningListener
()
listeningListener() =>
listen(handle, listeningListener) =>
listenerCount
(eventName) – Returns the number of listeners listening to the event named eventName
. string | symbol#
eventName
– The name of the event being listened for
+
listenerCount(eventName) =>
listeners
(eventName) – Returns a copy of the array of listeners for the event named eventName
.
+ +```js +server.on('connection', stream => { + console.log('someone connected!') +}) +console.log(util.inspect(server.listeners('connection'))) +// Prints: [ [Function] ] +``` + +
+eventName
string | symbol
listeners(eventName) =>
off
(eventName, listener) – Alias for emitter.removeListener()
. string | symbol#
eventName
off(eventName, listener) =>
on
(event, listener) – 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.
+ +```js +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. + +```js +const myEE = new EventEmitter() +myEE.on('foo', () => console.log('a')) +myEE.prependListener('foo', () => console.log('b')) +myEE.emit('foo') +// Prints: +// b +// a +``` + +
+event
string
listener
(args) any []#
args
listener(args) =>
on(event, listener) =>
event
"keylog"
on(event, listener) =>
event
"newSession"
listener
(sessionId, sessionData, callback)
listener(sessionId, sessionData, callback) =>
on(event, listener) =>
event
"OCSPRequest"
listener
(certificate, issuer, callback)
listener(certificate, issuer, callback) =>
on(event, listener) =>
event
"resumeSession"
listener
(sessionId, callback)
listener(sessionId, callback) =>
on(event, listener) =>
event
"secureConnection"
on(event, listener) =>
event
"tlsClientError"
on(event, listener) =>
event
"close"
listener
()
listener() =>
on(event, listener) =>
event
"connection"
on(event, listener) =>
event
"error"
listener
(err) Error#
err
listener(err) =>
on(event, listener) =>
event
"listening"
listener
()
listener() =>
on(event, listener) =>
event
"checkContinue"
listener
on(event, listener) =>
event
"checkExpectation"
listener
on(event, listener) =>
event
"clientError"
on(event, listener) =>
event
"connect"
listener
(req, socket, head) #
req
listener(req, socket, head) =>
on(event, listener) =>
event
"request"
listener
on(event, listener) =>
event
"upgrade"
listener
(req, socket, head) #
req
listener(req, socket, head) =>
on(event, listener) =>
once
(event, listener) – Adds a one-timelistener
function for the event named eventName
. The
+next time eventName
is triggered, this listener is removed and then invoked.
+ +```js +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. + +```js +const myEE = new EventEmitter() +myEE.once('foo', () => console.log('a')) +myEE.prependOnceListener('foo', () => console.log('b')) +myEE.emit('foo') +// Prints: +// b +// a +``` + +
+event
string
listener
(args) any []#
args
listener(args) =>
once(event, listener) =>
event
"keylog"
once(event, listener) =>
event
"newSession"
listener
(sessionId, sessionData, callback)
listener(sessionId, sessionData, callback) =>
once(event, listener) =>
event
"OCSPRequest"
listener
(certificate, issuer, callback)
listener(certificate, issuer, callback) =>
once(event, listener) =>
event
"resumeSession"
listener
(sessionId, callback)
listener(sessionId, callback) =>
once(event, listener) =>
event
"secureConnection"
once(event, listener) =>
event
"tlsClientError"
once(event, listener) =>
event
"close"
listener
()
listener() =>
once(event, listener) =>
event
"connection"
once(event, listener) =>
event
"error"
listener
(err) Error#
err
listener(err) =>
once(event, listener) =>
event
"listening"
listener
()
listener() =>
once(event, listener) =>
event
"checkContinue"
listener
once(event, listener) =>
event
"checkExpectation"
listener
once(event, listener) =>
event
"clientError"
once(event, listener) =>
event
"connect"
listener
(req, socket, head) #
req
listener(req, socket, head) =>
once(event, listener) =>
event
"request"
listener
once(event, listener) =>
event
"upgrade"
listener
(req, socket, head) #
req
listener(req, socket, head) =>
once(event, listener) =>
prependListener
(event, listener) – 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.
+ +```js +server.prependListener('connection', stream => { + console.log('someone connected!') +}) +``` + +Returns a reference to the `EventEmitter`, so that calls can be chained. + +
+event
string
listener
(args) any []#
args
listener(args) =>
prependListener(event, listener) =>
event
"keylog"
prependListener(event, listener) =>
event
"newSession"
listener
(sessionId, sessionData, callback)
listener(sessionId, sessionData, callback) =>
prependListener(event, listener) =>
event
"OCSPRequest"
listener
(certificate, issuer, callback)
listener(certificate, issuer, callback) =>
prependListener(event, listener) =>
event
"resumeSession"
listener
(sessionId, callback)
listener(sessionId, callback) =>
prependListener(event, listener) =>
event
"secureConnection"
prependListener(event, listener) =>
event
"tlsClientError"
prependListener(event, listener) =>
event
"close"
listener
()
listener() =>
prependListener(event, listener) =>
event
"connection"
prependListener(event, listener) =>
event
"error"
listener
(err) Error#
err
listener(err) =>
prependListener(event, listener) =>
event
"listening"
listener
()
listener() =>
prependListener(event, listener) =>
event
"checkContinue"
listener
prependListener(event, listener) =>
event
"checkExpectation"
listener
prependListener(event, listener) =>
event
"clientError"
prependListener(event, listener) =>
event
"connect"
listener
(req, socket, head) #
req
listener(req, socket, head) =>
prependListener(event, listener) =>
event
"request"
listener
prependListener(event, listener) =>
event
"upgrade"
listener
(req, socket, head) #
req
listener(req, socket, head) =>
prependListener(event, listener) =>
prependOnceListener
(event, listener) – Adds a one-timelistener
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.
+ +```js +server.prependOnceListener('connection', stream => { + console.log('Ah, we have our first user!') +}) +``` + +Returns a reference to the `EventEmitter`, so that calls can be chained. + +
+event
string
listener
(args) any []#
args
listener(args) =>
prependOnceListener(event, listener) =>
event
"keylog"
prependOnceListener(event, listener) =>
event
"newSession"
listener
(sessionId, sessionData, callback)
listener(sessionId, sessionData, callback) =>
prependOnceListener(event, listener) =>
event
"OCSPRequest"
listener
(certificate, issuer, callback)
listener(certificate, issuer, callback) =>
prependOnceListener(event, listener) =>
event
"resumeSession"
listener
(sessionId, callback)
listener(sessionId, callback) =>
prependOnceListener(event, listener) =>
event
"secureConnection"
prependOnceListener(event, listener) =>
event
"tlsClientError"
prependOnceListener(event, listener) =>
event
"close"
listener
()
listener() =>
prependOnceListener(event, listener) =>
event
"connection"
prependOnceListener(event, listener) =>
event
"error"
listener
(err) Error#
err
listener(err) =>
prependOnceListener(event, listener) =>
event
"listening"
listener
()
listener() =>
prependOnceListener(event, listener) =>
event
"checkContinue"
listener
prependOnceListener(event, listener) =>
event
"checkExpectation"
listener
prependOnceListener(event, listener) =>
event
"clientError"
prependOnceListener(event, listener) =>
event
"connect"
listener
(req, socket, head) #
req
listener(req, socket, head) =>
prependOnceListener(event, listener) =>
event
"request"
listener
prependOnceListener(event, listener) =>
event
"upgrade"
listener
(req, socket, head) #
req
listener(req, socket, head) =>
prependOnceListener(event, listener) =>
rawListeners
(eventName) – Returns a copy of the array of listeners for the event named eventName
,
+including any wrappers (such as those created by .once()
).
+ +```js +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') +``` + +
+eventName
string | symbol
rawListeners(eventName) =>
ref
() – Opposite of unref()
, calling ref()
on a previously unref
ed server will_not_ let the program exit if it's the only server left (the default behavior).
+If the server is ref
ed calling ref()
again will have no effect.
ref() =>
removeAllListeners
(event) – 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. + +
+event
string | symbol
removeAllListeners(event) =>
removeListener
(eventName, listener) – Removes the specified listener
from the listener array for the event namedeventName
.
+ +```js +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. + +```js +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 indices 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: + +```js +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. + +
+eventName
string | symbol
listener
(args) any []#
args
listener(args) =>
removeListener(eventName, listener) =>
setMaxListeners
(n) – By default EventEmitter
s 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 toInfinity
(or 0
) to indicate an unlimited number of listeners.
+ +Returns a reference to the `EventEmitter`, so that calls can be chained. + +
+n
number
setMaxListeners(n) =>
setSecureContext
(options) – The server.setSecureContext()
method replaces the secure context of an
+existing server. Existing connections to the server are not interrupted. #
options
– An object containing any of the possible properties from the {@link createSecureContext} options
arguments (e.g. key
, cert
, ca
, etc).
+
setSecureContext(options) =>
setTicketKeys
(keys) – Sets the session ticket keys.
+ +Changes to the ticket keys are effective only for future server connections. +Existing or currently pending server connections will use the previous keys. + +See `Session Resumption` for more information. + +
+keys
– A 48-byte buffer containing the session ticket keys.
+setTicketKeys(keys) =>
setTimeout
(msecs, callback) – Sets the timeout value for sockets, and emits a 'timeout'
event on
+the Server object, passing the socket as an argument, if a timeout
+occurs.
+ +If there is a `'timeout'` event listener on the Server object, then it +will be called with the timed-out socket as an argument. + +By default, the Server does not timeout sockets. However, if a callback +is assigned to the Server's `'timeout'` event, timeouts must be handled +explicitly. + +
+msecs
number
callback
()
callback() =>
setTimeout(msecs, callback) =>
callback
()
callback() =>
setTimeout(callback) =>
unref
() – Calling unref()
on a server will allow the program to exit if this is the only
+active server in the event system. If the server is already unref
ed callingunref()
again will have no effect.
unref() =>
getEventListeners
(emitter, name) – Returns a copy of the array of listeners for the event named eventName
.
+ +For `EventEmitter`s this behaves exactly the same as calling `.listeners` on +the emitter. + +For `EventTarget`s this is the only way to get the event listeners for the +event target. This is useful for debugging and diagnostic purposes. + +```js +const { getEventListeners, EventEmitter } = require('events') + +{ + const ee = new EventEmitter() + const listener = () => console.log('Events are fun') + ee.on('foo', listener) + getEventListeners(ee, 'foo') // [listener] +} +{ + const et = new EventTarget() + const listener = () => console.log('Events are fun') + et.addEventListener('foo', listener) + getEventListeners(et, 'foo') // [listener] +} +``` + +
+emitter
name
string | symbol
getEventListeners(emitter, name) =>
listenerCount
(emitter, eventName) – A class method that returns the number of listeners for the given eventName
registered on the given emitter
.
+ +```js +const { EventEmitter, listenerCount } = require('events') +const myEmitter = new EventEmitter() +myEmitter.on('event', () => {}) +myEmitter.on('event', () => {}) +console.log(listenerCount(myEmitter, 'event')) +// Prints: 2 +``` + +
+emitter
– The emitter to queryeventName
– The event name
+string | symbol
listenerCount(emitter, eventName) =>
on
(emitter, eventName, options) – ```js
+const { on, EventEmitter } = require('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: + +```js +const { on, EventEmitter } = require('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()); +```` + +
+emitter
eventName
– The name of the event being listened forstring
options
on(emitter, eventName, options) =>
once
(emitter, eventName, options) – 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](https://dom.spec.whatwg.org/#interface-eventtarget) interface, which has no special`'error'` event +semantics and does not listen to the `'error'` event. + +```js +const { once, EventEmitter } = require('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.log('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: + +```js +const { EventEmitter, once } = require('events') + +const ee = new EventEmitter() + +once(ee, 'error') + .then(([err]) => console.log('ok', err.message)) + .catch(err => console.log('error', err.message)) + +ee.emit('error', new Error('boom')) + +// Prints: ok boom +``` + +An `AbortSignal` can be used to cancel waiting for the event: + +```js +const { EventEmitter, once } = require('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() // Abort waiting for the event +ee.emit('foo') // Prints: Waiting for the event was canceled! +``` + +
+emitter
eventName
string | symbol
options
once(emitter, eventName, options) =>
emitter
eventName
string
options
once(emitter, eventName, options) =>
setMaxListeners
(n, eventTargets) – By default EventEmitter
s 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 EventEmitter.setMaxListeners()
method allows the default limit to be
+modified (if eventTargets is empty) or modify the limit specified in every EventTarget
| EventEmitter
passed as arguments.
+The value can be set toInfinity
(or 0
) to indicate an unlimited number of listeners.
+ +```js +EventEmitter.setMaxListeners(20) +// Equivalent to +EventEmitter.defaultMaxListeners = 20 + +const eventTarget = new EventTarget() +// Only way to increase limit for `EventTarget` instances +// as these doesn't expose its own `setMaxListeners` method +EventEmitter.setMaxListeners(20, eventTarget) +``` + +
+n
number
eventTargets
setMaxListeners(n, eventTargets) =>
Server
– Accepts encrypted connections using TLS or SSL.
new Server
() #
options
connections
number
listening
– Indicates whether or not the server is listening for connections.boolean
maxConnections
– Set this property to reject connections when the server's connection count gets
+high.number
+ +It is not recommended to use this option once a socket has been sent to a child +with `child_process.fork()`. + +
+captureRejectionSymbol
typeof captureRejectionSymbol
captureRejections
– Sets or gets the default captureRejection value for all emitters.boolean
defaultMaxListeners
number
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.typeof errorMonitor
+ +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. + +
+addContext
(hostname, context) – The server.addContext()
method adds a secure context that will be used if
+the client request's SNI name matches the supplied hostname
(or wildcard).
+ +When there are multiple matching contexts, the most recently added one is +used. + +
+hostname
– A SNI host name or wildcard (e.g. '*'
)string
context
– An object containing any of the possible properties from the {@link createSecureContext} options
arguments (e.g. key
, cert
, ca
, etc).
+addContext(hostname, context) =>
addListener
(event, listener) – events.EventEmitter
+1. tlsClientError
+2. newSession
+3. OCSPRequest
+4. resumeSession
+5. secureConnection
+6. keylog string#
event
addListener(event, listener) =>
event
"tlsClientError"
addListener(event, listener) =>
event
"newSession"
listener
(sessionId, sessionData, callback)
listener(sessionId, sessionData, callback) =>
addListener(event, listener) =>
event
"OCSPRequest"
listener
(certificate, issuer, callback)
listener(certificate, issuer, callback) =>
addListener(event, listener) =>
event
"resumeSession"
listener
(sessionId, callback)
listener(sessionId, callback) =>
addListener(event, listener) =>
event
"secureConnection"
addListener(event, listener) =>
event
"keylog"
addListener(event, listener) =>
address
() – Returns the bound address
, the address family
name, and port
of the server
+as reported by the operating system if listening on an IP socket
+(useful to find which port was assigned when getting an OS-assigned address):{ port: 12346, family: 'IPv4', address: '127.0.0.1' }
.
+ +For a server listening on a pipe or Unix domain socket, the name is returned +as a string. + +```js +const server = net.createServer(socket => { + socket.end('goodbye\n') +}).on('error', err => { + // Handle errors here. + throw err +}) + +// Grab an arbitrary unused port. +server.listen(() => { + console.log('opened server on', server.address()) +}) +``` + +`server.address()` returns `null` before the `'listening'` event has been +emitted or after calling `server.close()`. + +
+address() =>
null
| string | AddressInfoclose
(callback) – Stops the server from accepting new connections and keeps existing
+connections. This function is asynchronous, the server is finally closed
+when all connections are ended and the server emits a 'close'
event.
+The optional callback
will be called once the 'close'
event occurs. Unlike
+that event, it will be called with an Error
as its only argument if the server
+was not open when it was closed.
close(callback) =>
emit
(event, args) – Synchronously calls each of the listeners registered for the event namedeventName
, in the order they were registered, passing the supplied arguments
+to each.
+ +Returns `true` if the event had listeners, `false` otherwise. + +```js +const EventEmitter = require('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 +``` + +
+event
string | symbol
args
any []
emit(event, args) =>
event
"tlsClientError"
err
Error
tlsSocket
emit(event, err, tlsSocket) =>
event
"newSession"
sessionId
sessionData
emit(event, sessionId, sessionData, callback) =>
event
"OCSPRequest"
certificate
issuer
emit(event, certificate, issuer, callback) =>
event
"resumeSession"
sessionId
emit(event, sessionId, callback) =>
event
"secureConnection"
tlsSocket
emit(event, tlsSocket) =>
event
"keylog"
line
tlsSocket
emit(event, line, tlsSocket) =>
eventNames
() – Returns an array listing the events for which the emitter has registered
+listeners. The values in the array are strings or Symbol
s.
+ +```js +const EventEmitter = require('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) ] +``` + +
+eventNames() =>
getConnections
(cb) – Asynchronously get the number of concurrent connections on the server. Works
+when sockets were sent to forks.
+ +Callback should take two arguments `err` and `count`. + +
+getConnections(cb) =>
getMaxListeners
() – Returns the current max listener value for the EventEmitter
which is either
+set by emitter.setMaxListeners(n)
or defaults to {@link defaultMaxListeners}.
getMaxListeners() =>
getTicketKeys
() – Returns the session ticket keys.
+ +See `Session Resumption` for more information. + +
+getTicketKeys() =>
listen
(port, hostname, backlog, listeningListener) – Start a server listening for connections. A net.Server
can be a TCP or
+an IPC
server depending on what it listens to.
+ +Possible signatures: + +- `server.listen(handle[, backlog][, callback])` +- `server.listen(options[, callback])` +- `server.listen(path[, backlog][, callback])` for `IPC` servers +- `server.listen([port[, host[, backlog]]][, callback])` for TCP servers + +This function is asynchronous. When the server starts listening, the `'listening'` event will be emitted. The last parameter `callback`will be added as a listener for the `'listening'` +event. + +All `listen()` methods can take a `backlog` parameter to specify the maximum +length of the queue of pending connections. The actual length will be determined +by the OS through sysctl settings such as `tcp_max_syn_backlog` and `somaxconn`on Linux. The default value of this parameter is 511 (not 512). + +All {@link Socket} are set to `SO_REUSEADDR` (see [`socket(7)`](https://man7.org/linux/man-pages/man7/socket.7.html) for +details). + +The `server.listen()` method can be called again if and only if there was an +error during the first `server.listen()` call or `server.close()` has been +called. Otherwise, an `ERR_SERVER_ALREADY_LISTEN` error will be thrown. + +One of the most common errors raised when listening is `EADDRINUSE`. +This happens when another server is already listening on the requested`port`/`path`/`handle`. One way to handle this would be to retry +after a certain amount of time: + +```js +server.on('error', e => { + if (e.code === 'EADDRINUSE') { + console.log('Address in use, retrying...') + setTimeout(() => { + server.close() + server.listen(PORT, HOST) + }, 1000) + } +}) +``` + +
+port
number
hostname
string
backlog
number
listeningListener
()
listeningListener() =>
listen(port, hostname, backlog, listeningListener) =>
port
number
hostname
string
listeningListener
()
listeningListener() =>
listen(port, hostname, listeningListener) =>
port
number
backlog
number
listeningListener
()
listeningListener() =>
listen(port, backlog, listeningListener) =>
port
number
listeningListener
()
listeningListener() =>
listen(port, listeningListener) =>
path
string
backlog
number
listeningListener
()
listeningListener() =>
listen(path, backlog, listeningListener) =>
path
string
listeningListener
()
listeningListener() =>
listen(path, listeningListener) =>
options
listeningListener
()
listeningListener() =>
listen(options, listeningListener) =>
handle
any
backlog
number
listeningListener
()
listeningListener() =>
listen(handle, backlog, listeningListener) =>
handle
any
listeningListener
()
listeningListener() =>
listen(handle, listeningListener) =>
listenerCount
(eventName) – Returns the number of listeners listening to the event named eventName
. string | symbol#
eventName
– The name of the event being listened for
+
listenerCount(eventName) =>
listeners
(eventName) – Returns a copy of the array of listeners for the event named eventName
.
+ +```js +server.on('connection', stream => { + console.log('someone connected!') +}) +console.log(util.inspect(server.listeners('connection'))) +// Prints: [ [Function] ] +``` + +
+eventName
string | symbol
listeners(eventName) =>
off
(eventName, listener) – Alias for emitter.removeListener()
. string | symbol#
eventName
off(eventName, listener) =>
on
(event, listener) – 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.
+ +```js +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. + +```js +const myEE = new EventEmitter() +myEE.on('foo', () => console.log('a')) +myEE.prependListener('foo', () => console.log('b')) +myEE.emit('foo') +// Prints: +// b +// a +``` + +
+event
string
listener
(args) any []#
args
listener(args) =>
on(event, listener) =>
event
"tlsClientError"
on(event, listener) =>
event
"newSession"
listener
(sessionId, sessionData, callback)
listener(sessionId, sessionData, callback) =>
on(event, listener) =>
event
"OCSPRequest"
listener
(certificate, issuer, callback)
listener(certificate, issuer, callback) =>
on(event, listener) =>
event
"resumeSession"
listener
(sessionId, callback)
listener(sessionId, callback) =>
on(event, listener) =>
event
"secureConnection"
on(event, listener) =>
event
"keylog"
on(event, listener) =>
once
(event, listener) – Adds a one-timelistener
function for the event named eventName
. The
+next time eventName
is triggered, this listener is removed and then invoked.
+ +```js +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. + +```js +const myEE = new EventEmitter() +myEE.once('foo', () => console.log('a')) +myEE.prependOnceListener('foo', () => console.log('b')) +myEE.emit('foo') +// Prints: +// b +// a +``` + +
+event
string
listener
(args) any []#
args
listener(args) =>
once(event, listener) =>
event
"tlsClientError"
once(event, listener) =>
event
"newSession"
listener
(sessionId, sessionData, callback)
listener(sessionId, sessionData, callback) =>
once(event, listener) =>
event
"OCSPRequest"
listener
(certificate, issuer, callback)
listener(certificate, issuer, callback) =>
once(event, listener) =>
event
"resumeSession"
listener
(sessionId, callback)
listener(sessionId, callback) =>
once(event, listener) =>
event
"secureConnection"
once(event, listener) =>
event
"keylog"
once(event, listener) =>
prependListener
(event, listener) – 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.
+ +```js +server.prependListener('connection', stream => { + console.log('someone connected!') +}) +``` + +Returns a reference to the `EventEmitter`, so that calls can be chained. + +
+event
string
listener
(args) any []#
args
listener(args) =>
prependListener(event, listener) =>
event
"tlsClientError"
prependListener(event, listener) =>
event
"newSession"
listener
(sessionId, sessionData, callback)
listener(sessionId, sessionData, callback) =>
prependListener(event, listener) =>
event
"OCSPRequest"
listener
(certificate, issuer, callback)
listener(certificate, issuer, callback) =>
prependListener(event, listener) =>
event
"resumeSession"
listener
(sessionId, callback)
listener(sessionId, callback) =>
prependListener(event, listener) =>
event
"secureConnection"
prependListener(event, listener) =>
event
"keylog"
prependListener(event, listener) =>
prependOnceListener
(event, listener) – Adds a one-timelistener
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.
+ +```js +server.prependOnceListener('connection', stream => { + console.log('Ah, we have our first user!') +}) +``` + +Returns a reference to the `EventEmitter`, so that calls can be chained. + +
+event
string
listener
(args) any []#
args
listener(args) =>
prependOnceListener(event, listener) =>
event
"tlsClientError"
prependOnceListener(event, listener) =>
event
"newSession"
listener
(sessionId, sessionData, callback)
listener(sessionId, sessionData, callback) =>
prependOnceListener(event, listener) =>
event
"OCSPRequest"
listener
(certificate, issuer, callback)
listener(certificate, issuer, callback) =>
prependOnceListener(event, listener) =>
event
"resumeSession"
listener
(sessionId, callback)
listener(sessionId, callback) =>
prependOnceListener(event, listener) =>
event
"secureConnection"
prependOnceListener(event, listener) =>
event
"keylog"
prependOnceListener(event, listener) =>
rawListeners
(eventName) – Returns a copy of the array of listeners for the event named eventName
,
+including any wrappers (such as those created by .once()
).
+ +```js +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') +``` + +
+eventName
string | symbol
rawListeners(eventName) =>
ref
() – Opposite of unref()
, calling ref()
on a previously unref
ed server will_not_ let the program exit if it's the only server left (the default behavior).
+If the server is ref
ed calling ref()
again will have no effect.
ref() =>
removeAllListeners
(event) – 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. + +
+event
string | symbol
removeAllListeners(event) =>
removeListener
(eventName, listener) – Removes the specified listener
from the listener array for the event namedeventName
.
+ +```js +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. + +```js +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 indices 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: + +```js +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. + +
+eventName
string | symbol
listener
(args) any []#
args
listener(args) =>
removeListener(eventName, listener) =>
setMaxListeners
(n) – By default EventEmitter
s 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 toInfinity
(or 0
) to indicate an unlimited number of listeners.
+ +Returns a reference to the `EventEmitter`, so that calls can be chained. + +
+n
number
setMaxListeners(n) =>
setSecureContext
(options) – The server.setSecureContext()
method replaces the secure context of an
+existing server. Existing connections to the server are not interrupted. #
options
– An object containing any of the possible properties from the {@link createSecureContext} options
arguments (e.g. key
, cert
, ca
, etc).
+
setSecureContext(options) =>
setTicketKeys
(keys) – Sets the session ticket keys.
+ +Changes to the ticket keys are effective only for future server connections. +Existing or currently pending server connections will use the previous keys. + +See `Session Resumption` for more information. + +
+keys
– A 48-byte buffer containing the session ticket keys.
+setTicketKeys(keys) =>
unref
() – Calling unref()
on a server will allow the program to exit if this is the only
+active server in the event system. If the server is already unref
ed callingunref()
again will have no effect.
unref() =>
getEventListeners
(emitter, name) – Returns a copy of the array of listeners for the event named eventName
.
+ +For `EventEmitter`s this behaves exactly the same as calling `.listeners` on +the emitter. + +For `EventTarget`s this is the only way to get the event listeners for the +event target. This is useful for debugging and diagnostic purposes. + +```js +const { getEventListeners, EventEmitter } = require('events') + +{ + const ee = new EventEmitter() + const listener = () => console.log('Events are fun') + ee.on('foo', listener) + getEventListeners(ee, 'foo') // [listener] +} +{ + const et = new EventTarget() + const listener = () => console.log('Events are fun') + et.addEventListener('foo', listener) + getEventListeners(et, 'foo') // [listener] +} +``` + +
+emitter
name
string | symbol
getEventListeners(emitter, name) =>
listenerCount
(emitter, eventName) – A class method that returns the number of listeners for the given eventName
registered on the given emitter
.
+ +```js +const { EventEmitter, listenerCount } = require('events') +const myEmitter = new EventEmitter() +myEmitter.on('event', () => {}) +myEmitter.on('event', () => {}) +console.log(listenerCount(myEmitter, 'event')) +// Prints: 2 +``` + +
+emitter
– The emitter to queryeventName
– The event name
+string | symbol
listenerCount(emitter, eventName) =>
on
(emitter, eventName, options) – ```js
+const { on, EventEmitter } = require('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: + +```js +const { on, EventEmitter } = require('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()); +```` + +
+emitter
eventName
– The name of the event being listened forstring
options
on(emitter, eventName, options) =>
once
(emitter, eventName, options) – 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](https://dom.spec.whatwg.org/#interface-eventtarget) interface, which has no special`'error'` event +semantics and does not listen to the `'error'` event. + +```js +const { once, EventEmitter } = require('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.log('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: + +```js +const { EventEmitter, once } = require('events') + +const ee = new EventEmitter() + +once(ee, 'error') + .then(([err]) => console.log('ok', err.message)) + .catch(err => console.log('error', err.message)) + +ee.emit('error', new Error('boom')) + +// Prints: ok boom +``` + +An `AbortSignal` can be used to cancel waiting for the event: + +```js +const { EventEmitter, once } = require('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() // Abort waiting for the event +ee.emit('foo') // Prints: Waiting for the event was canceled! +``` + +
+emitter
eventName
string | symbol
options
once(emitter, eventName, options) =>
emitter
eventName
string
options
once(emitter, eventName, options) =>
setMaxListeners
(n, eventTargets) – By default EventEmitter
s 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 EventEmitter.setMaxListeners()
method allows the default limit to be
+modified (if eventTargets is empty) or modify the limit specified in every EventTarget
| EventEmitter
passed as arguments.
+The value can be set toInfinity
(or 0
) to indicate an unlimited number of listeners.
+ +```js +EventEmitter.setMaxListeners(20) +// Equivalent to +EventEmitter.defaultMaxListeners = 20 + +const eventTarget = new EventTarget() +// Only way to increase limit for `EventTarget` instances +// as these doesn't expose its own `setMaxListeners` method +EventEmitter.setMaxListeners(20, eventTarget) +``` + +
+n
number
eventTargets
setMaxListeners(n, eventTargets) =>
ServerResponse
– This object is created internally by an HTTP server, not by the user. It is
+passed as the second parameter to the 'request'
event. boolean boolean
+
+After calling `outgoingMessage.end()`, this property will be nulled.
+
+ number
+
+```js
+response.statusCode = 404
+```
+
+After response header was sent to the client, this property indicates the
+status code which was sent out.
+
+ string
+
+```js
+response.statusMessage = 'Not found'
+```
+
+After response header was sent to the client, this property indicates the
+status message which was sent out.
+
+ boolean number boolean boolean number number boolean typeof captureRejectionSymbol boolean typeof errorMonitor
+
+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.
+
+#
src/.fastpm/-/@types/node@17.0.45/http.d.ts#L346 connection
– Aliases of outgoingMessage.socket
null
| Socket#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L543 destroyed
– Is true
after writable.destroy()
has been called.#
src/.fastpm/-/@types/node@17.0.45/http.d.ts#L340 headersSent
– Read-only. true
if the headers were sent, otherwise false
.#
src/.fastpm/-/@types/node@17.0.45/http.d.ts#L354 socket
– Reference to the underlying socket. Usually, users will not want to access
+this property.null
| Socket#
src/.fastpm/-/@types/node@17.0.45/http.d.ts#L478 statusCode
– When using implicit headers (not calling response.writeHead()
explicitly),
+this property controls the status code that will be sent to the client when
+the headers get flushed.#
src/.fastpm/-/@types/node@17.0.45/http.d.ts#L493 statusMessage
– When using implicit headers (not calling response.writeHead()
explicitly),
+this property controls the status message that will be sent to the client when
+the headers get flushed. If this is left as undefined
then the standard
+message for the status code will be used.#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L504 writable
– Is true
if it is safe to call writable.write()
, which means
+the stream has not been destroyed, errored or ended.#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L538 writableCorked
– Number of times writable.uncork()
needs to be
+called in order to fully uncork the stream.#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L510 writableEnded
– Is true
after writable.end()
has been called. This property
+does not indicate whether the data has been flushed, for this use writable.writableFinished
instead.#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L515 writableFinished
– Is set to true
immediately before the 'finish'
event is emitted.#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L520 writableHighWaterMark
– Return the value of highWaterMark
passed when creating this Writable
.#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L527 writableLength
– This property contains the number of bytes (or objects) in the queue
+ready to be written. The value provides introspection data regarding
+the status of the highWaterMark
.#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L532 writableObjectMode
– Getter for the property objectMode
of a given Writable
stream.#
src/.fastpm/-/@types/node@17.0.45/events.d.ts#L301 captureRejectionSymbol
#
src/.fastpm/-/@types/node@17.0.45/events.d.ts#L306 captureRejections
– Sets or gets the default captureRejection value for all emitters.#
src/.fastpm/-/@types/node@17.0.45/events.d.ts#L300 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.
_construct(callback) =>
_destroy
(error, callback) #
error
null
| Error
_destroy(error, callback) =>
_final
(callback)
_final(callback) =>
_write
(chunk, encoding, callback) _write(chunk, encoding, callback) =>
_writev
(chunks, callback) { #
chunks
callback
(error) #
error
null
| Error
callback(error) =>
_writev(chunks, callback) =>
addListener
(event, listener) – Event emitter
+The defined events on documents including:
+1. close
+2. drain
+3. error
+4. finish
+5. pipe
+6. unpipeaddListener(event, listener) =>
event
"drain"
listener
()
listener() =>
addListener(event, listener) =>
event
"error"
listener
(err) Error#
err
listener(err) =>
addListener(event, listener) =>
event
"finish"
listener
()
listener() =>
addListener(event, listener) =>
event
"pipe"
addListener(event, listener) =>
event
"unpipe"
addListener(event, listener) =>
event
string | symbol
listener
(args) any []#
args
listener(args) =>
addListener(event, listener) =>
addTrailers
(headers) – Adds HTTP trailers (headers but at the end of the message) to the message.
+ +Trailers are **only** be emitted if the message is chunked encoded. If not, +the trailer will be silently discarded. + +HTTP requires the `Trailer` header to be sent to emit trailers, +with a list of header fields in its value, e.g. + +```js +message.writeHead(200, { 'Content-Type': 'text/plain', Trailer: 'Content-MD5' }) +message.write(fileData) +message.addTrailers({ 'Content-MD5': '7895bf4b8828b55ceaf47747b4bca667' }) +message.end() +``` + +Attempting to set a header field name or value that contains invalid characters +will result in a `TypeError` being thrown. + +
+headers
OutgoingHttpHeaders | readonly [ string, string ] []
addTrailers(headers) =>
assignSocket
(socket)
assignSocket(socket) =>
cork
() – The writable.cork()
method forces all written data to be buffered in memory.
+The buffered data will be flushed when either the {@link uncork} or {@link end} methods are called.
+ +The primary intent of `writable.cork()` is to accommodate a situation in which +several small chunks are written to the stream in rapid succession. Instead of +immediately forwarding them to the underlying destination, `writable.cork()`buffers all the chunks until `writable.uncork()` is called, which will pass them +all to `writable._writev()`, if present. This prevents a head-of-line blocking +situation where data is being buffered while waiting for the first small chunk +to be processed. However, use of `writable.cork()` without implementing`writable._writev()` may have an adverse effect on throughput. + +See also: `writable.uncork()`, `writable._writev()`. + +
+cork() =>
destroy
(error) – Destroy the stream. Optionally emit an 'error'
event, and emit a 'close'
event (unless emitClose
is set to false
). After this call, the writable
+stream has ended and subsequent calls to write()
or end()
will result in
+an ERR_STREAM_DESTROYED
error.
+This is a destructive and immediate way to destroy a stream. Previous calls towrite()
may not have drained, and may trigger an ERR_STREAM_DESTROYED
error.
+Use end()
instead of destroy if data should flush before close, or wait for
+the 'drain'
event before destroying the stream.
+ +Once `destroy()` has been called any further calls will be a no-op and no +further errors except from `_destroy()` may be emitted as `'error'`. + +Implementors should not override this method, +but instead implement `writable._destroy()`. + +
+error
– Optional, an error to emit with 'error'
event.
+Error
destroy(error) =>
detachSocket
(socket)
detachSocket(socket) =>
emit
(event) – Synchronously calls each of the listeners registered for the event namedeventName
, in the order they were registered, passing the supplied arguments
+to each.
+ +Returns `true` if the event had listeners, `false` otherwise. + +```js +const EventEmitter = require('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 +``` + +
+event
"close"
emit(event) =>
event
"drain"
emit(event) =>
event
"error"
err
Error
emit(event, err) =>
event
"finish"
emit(event) =>
event
"pipe"
src
emit(event, src) =>
event
"unpipe"
src
emit(event, src) =>
event
string | symbol
args
any []
emit(event, args) =>
end
(cb) – Calling the writable.end()
method signals that no more data will be written
+to the Writable
. The optional chunk
and encoding
arguments allow one
+final additional chunk of data to be written immediately before closing the
+stream.
+ +Calling the {@link write} method after calling {@link end} will raise an error. + +```js +// Write 'hello, ' and then end with 'world!'. +const fs = require('fs') +const file = fs.createWriteStream('example.txt') +file.write('hello, ') +file.end('world!') +// Writing more now is not allowed! +``` + +
+cb
()
cb() =>
end(cb) =>
chunk
any
cb
()
cb() =>
end(chunk, cb) =>
chunk
any
encoding
cb
()
cb() =>
end(chunk, encoding, cb) =>
eventNames
() – Returns an array listing the events for which the emitter has registered
+listeners. The values in the array are strings or Symbol
s.
+ +```js +const EventEmitter = require('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) ] +``` + +
+eventNames() =>
flushHeaders
() – Compulsorily flushes the message headers
+ +For efficiency reason, Node.js normally buffers the message headers +until `outgoingMessage.end()` is called or the first chunk of message data +is written. It then tries to pack the headers and data into a single TCP +packet. + +It is usually desired (it saves a TCP round-trip), but not when the first +data is not sent until possibly much later. `outgoingMessage.flushHeaders()`bypasses the optimization and kickstarts the request. + +
+flushHeaders() =>
getHeader
(name) – Gets the value of HTTP header with the given name. If such a name doesn't
+exist in message, it will be undefined
. string#
name
– Name of header
+
getHeader(name) =>
getHeaderNames
() – Returns an array of names of headers of the outgoing outgoingMessage. All
+names are lowercase.
getHeaderNames() =>
getHeaders
() – Returns a shallow copy of the current outgoing headers. Since a shallow
+copy is used, array values may be mutated without additional calls to
+various header-related HTTP module methods. The keys of the returned
+object are the header names and the values are the respective header
+values. All header names are lowercase.
+ +The object returned by the `outgoingMessage.getHeaders()` method does +not prototypically inherit from the JavaScript Object. This means that +typical Object methods such as `obj.toString()`, `obj.hasOwnProperty()`, +and others are not defined and will not work. + +```js +outgoingMessage.setHeader('Foo', 'bar') +outgoingMessage.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']) + +const headers = outgoingMessage.getHeaders() +// headers === { foo: 'bar', 'set-cookie': ['foo=bar', 'bar=baz'] } +``` + +
+getHeaders() =>
getMaxListeners
() – Returns the current max listener value for the EventEmitter
which is either
+set by emitter.setMaxListeners(n)
or defaults to {@link defaultMaxListeners}.
getMaxListeners() =>
hasHeader
(name) – Returns true
if the header identified by name
is currently set in the
+outgoing headers. The header name is case-insensitive.
+ +```js +const hasContentType = outgoingMessage.hasHeader('content-type') +``` + +
+name
string
hasHeader(name) =>
listenerCount
(eventName) – Returns the number of listeners listening to the event named eventName
. string | symbol#
eventName
– The name of the event being listened for
+
listenerCount(eventName) =>
listeners
(eventName) – Returns a copy of the array of listeners for the event named eventName
.
+ +```js +server.on('connection', stream => { + console.log('someone connected!') +}) +console.log(util.inspect(server.listeners('connection'))) +// Prints: [ [Function] ] +``` + +
+eventName
string | symbol
listeners(eventName) =>
off
(eventName, listener) – Alias for emitter.removeListener()
. string | symbol#
eventName
off(eventName, listener) =>
on
(event, listener) – 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.
+ +```js +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. + +```js +const myEE = new EventEmitter() +myEE.on('foo', () => console.log('a')) +myEE.prependListener('foo', () => console.log('b')) +myEE.emit('foo') +// Prints: +// b +// a +``` + +
+event
"close"
listener
()
listener() =>
on(event, listener) =>
event
"drain"
listener
()
listener() =>
on(event, listener) =>
event
"error"
listener
(err) Error#
err
listener(err) =>
on(event, listener) =>
event
"finish"
listener
()
listener() =>
on(event, listener) =>
event
"pipe"
on(event, listener) =>
event
"unpipe"
on(event, listener) =>
event
string | symbol
listener
(args) any []#
args
listener(args) =>
on(event, listener) =>
once
(event, listener) – Adds a one-timelistener
function for the event named eventName
. The
+next time eventName
is triggered, this listener is removed and then invoked.
+ +```js +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. + +```js +const myEE = new EventEmitter() +myEE.once('foo', () => console.log('a')) +myEE.prependOnceListener('foo', () => console.log('b')) +myEE.emit('foo') +// Prints: +// b +// a +``` + +
+event
"close"
listener
()
listener() =>
once(event, listener) =>
event
"drain"
listener
()
listener() =>
once(event, listener) =>
event
"error"
listener
(err) Error#
err
listener(err) =>
once(event, listener) =>
event
"finish"
listener
()
listener() =>
once(event, listener) =>
event
"pipe"
once(event, listener) =>
event
"unpipe"
once(event, listener) =>
event
string | symbol
listener
(args) any []#
args
listener(args) =>
once(event, listener) =>
pipe
(destination, { end }) { #
options
pipe<T extends WritableStream<T>>(destination, { end }) =>
prependListener
(event, listener) – 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.
+ +```js +server.prependListener('connection', stream => { + console.log('someone connected!') +}) +``` + +Returns a reference to the `EventEmitter`, so that calls can be chained. + +
+event
"close"
listener
()
listener() =>
prependListener(event, listener) =>
event
"drain"
listener
()
listener() =>
prependListener(event, listener) =>
event
"error"
listener
(err) Error#
err
listener(err) =>
prependListener(event, listener) =>
event
"finish"
listener
()
listener() =>
prependListener(event, listener) =>
event
"pipe"
prependListener(event, listener) =>
event
"unpipe"
prependListener(event, listener) =>
event
string | symbol
listener
(args) any []#
args
listener(args) =>
prependListener(event, listener) =>
prependOnceListener
(event, listener) – Adds a one-timelistener
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.
+ +```js +server.prependOnceListener('connection', stream => { + console.log('Ah, we have our first user!') +}) +``` + +Returns a reference to the `EventEmitter`, so that calls can be chained. + +
+event
"close"
listener
()
listener() =>
prependOnceListener(event, listener) =>
event
"drain"
listener
()
listener() =>
prependOnceListener(event, listener) =>
event
"error"
listener
(err) Error#
err
listener(err) =>
prependOnceListener(event, listener) =>
event
"finish"
listener
()
listener() =>
prependOnceListener(event, listener) =>
event
"pipe"
prependOnceListener(event, listener) =>
event
"unpipe"
prependOnceListener(event, listener) =>
event
string | symbol
listener
(args) any []#
args
listener(args) =>
prependOnceListener(event, listener) =>
rawListeners
(eventName) – Returns a copy of the array of listeners for the event named eventName
,
+including any wrappers (such as those created by .once()
).
+ +```js +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') +``` + +
+eventName
string | symbol
rawListeners(eventName) =>
removeAllListeners
(event) – 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. + +
+event
string | symbol
removeAllListeners(event) =>
removeHeader
(name) – Removes a header that is queued for implicit sending.
+ +```js +outgoingMessage.removeHeader('Content-Encoding') +``` + +
+name
string
removeHeader(name) =>
removeListener
(event, listener) – Removes the specified listener
from the listener array for the event namedeventName
.
+ +```js +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. + +```js +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 indices 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: + +```js +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. + +
+event
"close"
listener
()
listener() =>
removeListener(event, listener) =>
event
"drain"
listener
()
listener() =>
removeListener(event, listener) =>
event
"error"
listener
(err) Error#
err
listener(err) =>
removeListener(event, listener) =>
event
"finish"
listener
()
listener() =>
removeListener(event, listener) =>
event
"pipe"
removeListener(event, listener) =>
event
"unpipe"
removeListener(event, listener) =>
event
string | symbol
listener
(args) any []#
args
listener(args) =>
removeListener(event, listener) =>
setDefaultEncoding
(encoding) – The writable.setDefaultEncoding()
method sets the default encoding
for a Writable
stream. #
encoding
– The new default encoding
+
setDefaultEncoding(encoding) =>
setHeader
(name, value) – Sets a single header value for the header object.setMaxListeners
(n) – By default EventEmitter
s 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 toInfinity
(or 0
) to indicate an unlimited number of listeners.
+ +Returns a reference to the `EventEmitter`, so that calls can be chained. + +
+n
number
setMaxListeners(n) =>
setTimeout
(msecs, callback) – Once a socket is associated with the message and is connected,socket.setTimeout()
will be called with msecs
as the first parameter.setTimeout(msecs, callback) =>
uncork
() – The writable.uncork()
method flushes all data buffered since {@link cork} was called.
+ +When using `writable.cork()` and `writable.uncork()` to manage the buffering +of writes to a stream, it is recommended that calls to `writable.uncork()` be +deferred using `process.nextTick()`. Doing so allows batching of all`writable.write()` calls that occur within a given Node.js event loop phase. + +```js +stream.cork() +stream.write('some ') +stream.write('data ') +process.nextTick(() => stream.uncork()) +``` + +If the `writable.cork()` method is called multiple times on a stream, the +same number of calls to `writable.uncork()` must be called to flush the buffered +data. + +```js +stream.cork() +stream.write('some ') +stream.cork() +stream.write('data ') +process.nextTick(() => { + stream.uncork() + // The data will not be flushed until uncork() is called a second time. + stream.uncork() +}) +``` + +See also: `writable.cork()`. + +
+uncork() =>
write
(chunk, callback) – The writable.write()
method writes some data to the stream, and calls the
+supplied callback
once the data has been fully handled. If an error
+occurs, the callback
will be called with the error as its
+first argument. The callback
is called asynchronously and before 'error'
is
+emitted.
+ +The return value is `true` if the internal buffer is less than the`highWaterMark` configured when the stream was created after admitting `chunk`. +If `false` is returned, further attempts to write data to the stream should +stop until the `'drain'` event is emitted. + +While a stream is not draining, calls to `write()` will buffer `chunk`, and +return false. Once all currently buffered chunks are drained (accepted for +delivery by the operating system), the `'drain'` event will be emitted. +It is recommended that once `write()` returns false, no more chunks be written +until the `'drain'` event is emitted. While calling `write()` on a stream that +is not draining is allowed, Node.js will buffer all written chunks until +maximum memory usage occurs, at which point it will abort unconditionally. +Even before it aborts, high memory usage will cause poor garbage collector +performance and high RSS (which is not typically released back to the system, +even after the memory is no longer required). Since TCP sockets may never +drain if the remote peer does not read the data, writing a socket that is +not draining may lead to a remotely exploitable vulnerability. + +Writing data while the stream is not draining is particularly +problematic for a `Transform`, because the `Transform` streams are paused +by default until they are piped or a `'data'` or `'readable'` event handler +is added. + +If the data to be written can be generated or fetched on demand, it is +recommended to encapsulate the logic into a `Readable` and use {@link pipe}. However, if calling `write()` is preferred, it is +possible to respect backpressure and avoid memory issues using the `'drain'` event: + +```js +function write(data, cb) { + if (!stream.write(data)) { + stream.once('drain', cb) + } else { + process.nextTick(cb) + } +} + +// Wait for cb to be called before doing any other write. +write('hello', () => { + console.log('Write completed, do more writes now.') +}) +``` + +A `Writable` stream in object mode will always ignore the `encoding` argument. + +
+chunk
– Optional data to write. For streams not operating in object mode, chunk
must be a string, Buffer
or Uint8Array
. For object mode streams, chunk
may be any
+JavaScript value other than null
.any
callback
(error) undefined | #
error
null
| Error
callback(error) =>
write(chunk, callback) =>
chunk
any
encoding
callback
(error) undefined | #
error
null
| Error
callback(error) =>
write(chunk, encoding, callback) =>
writeContinue
(callback) – Sends a HTTP/1.1 100 Continue message to the client, indicating that
+the request body should be sent. See the 'checkContinue'
event onServer
. callback() => #
callback
()
void
writeContinue(callback) =>
writeHead
(statusCode, statusMessage, headers) – Sends a response header to the request. The status code is a 3-digit HTTP
+status code, like 404
. The last argument, headers
, are the response headers.
+Optionally one can give a human-readable statusMessage
as the second
+argument.
+ +`headers` may be an `Array` where the keys and values are in the same list. +It is _not_ a list of tuples. So, the even-numbered offsets are key values, +and the odd-numbered offsets are the associated values. The array is in the same +format as `request.rawHeaders`. + +Returns a reference to the `ServerResponse`, so that calls can be chained. + +```js +const body = 'hello world' +response + .writeHead(200, { + 'Content-Length': Buffer.byteLength(body), + 'Content-Type': 'text/plain', + }) + .end(body) +``` + +This method must only be called once on a message and it must +be called before `response.end()` is called. + +If `response.write()` or `response.end()` are called before calling +this, the implicit/mutable headers will be calculated and call this function. + +When headers have been set with `response.setHeader()`, they will be merged +with any headers passed to `response.writeHead()`, with the headers passed +to `response.writeHead()` given precedence. + +If this method is called and `response.setHeader()` has not been called, +it will directly write the supplied header values onto the network channel +without caching internally, and the `response.getHeader()` on the header +will not yield the expected result. If progressive population of headers is +desired with potential future retrieval and modification, use `response.setHeader()` instead. + +```js +// Returns content-type = text/plain +const server = http.createServer((req, res) => { + res.setHeader('Content-Type', 'text/html') + res.setHeader('X-Foo', 'bar') + res.writeHead(200, { 'Content-Type': 'text/plain' }) + res.end('ok') +}) +``` + +`Content-Length` is given in bytes, not characters. Use `Buffer.byteLength()` to determine the length of the body in bytes. Node.js +does not check whether `Content-Length` and the length of the body which has +been transmitted are equal or not. + +Attempting to set a header field name or value that contains invalid characters +will result in a `TypeError` being thrown. + +
+statusCode
number
statusMessage
string
headers
writeHead(statusCode, statusMessage, headers) =>
statusCode
number
headers
writeHead(statusCode, headers) =>
writeProcessing
() – Sends a HTTP/1.1 102 Processing message to the client, indicating that
+the request body should be sent.
writeProcessing() =>
getEventListeners
(emitter, name) – Returns a copy of the array of listeners for the event named eventName
.
+ +For `EventEmitter`s this behaves exactly the same as calling `.listeners` on +the emitter. + +For `EventTarget`s this is the only way to get the event listeners for the +event target. This is useful for debugging and diagnostic purposes. + +```js +const { getEventListeners, EventEmitter } = require('events') + +{ + const ee = new EventEmitter() + const listener = () => console.log('Events are fun') + ee.on('foo', listener) + getEventListeners(ee, 'foo') // [listener] +} +{ + const et = new EventTarget() + const listener = () => console.log('Events are fun') + et.addEventListener('foo', listener) + getEventListeners(et, 'foo') // [listener] +} +``` + +
+emitter
name
string | symbol
getEventListeners(emitter, name) =>
listenerCount
(emitter, eventName) – A class method that returns the number of listeners for the given eventName
registered on the given emitter
.
+ +```js +const { EventEmitter, listenerCount } = require('events') +const myEmitter = new EventEmitter() +myEmitter.on('event', () => {}) +myEmitter.on('event', () => {}) +console.log(listenerCount(myEmitter, 'event')) +// Prints: 2 +``` + +
+emitter
– The emitter to queryeventName
– The event name
+string | symbol
listenerCount(emitter, eventName) =>
on
(emitter, eventName, options) – ```js
+const { on, EventEmitter } = require('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: + +```js +const { on, EventEmitter } = require('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()); +```` + +
+emitter
eventName
– The name of the event being listened forstring
options
on(emitter, eventName, options) =>
once
(emitter, eventName, options) – 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](https://dom.spec.whatwg.org/#interface-eventtarget) interface, which has no special`'error'` event +semantics and does not listen to the `'error'` event. + +```js +const { once, EventEmitter } = require('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.log('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: + +```js +const { EventEmitter, once } = require('events') + +const ee = new EventEmitter() + +once(ee, 'error') + .then(([err]) => console.log('ok', err.message)) + .catch(err => console.log('error', err.message)) + +ee.emit('error', new Error('boom')) + +// Prints: ok boom +``` + +An `AbortSignal` can be used to cancel waiting for the event: + +```js +const { EventEmitter, once } = require('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() // Abort waiting for the event +ee.emit('foo') // Prints: Waiting for the event was canceled! +``` + +
+emitter
eventName
string | symbol
options
once(emitter, eventName, options) =>
emitter
eventName
string
options
once(emitter, eventName, options) =>
setMaxListeners
(n, eventTargets) – By default EventEmitter
s 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 EventEmitter.setMaxListeners()
method allows the default limit to be
+modified (if eventTargets is empty) or modify the limit specified in every EventTarget
| EventEmitter
passed as arguments.
+The value can be set toInfinity
(or 0
) to indicate an unlimited number of listeners.
+ +```js +EventEmitter.setMaxListeners(20) +// Equivalent to +EventEmitter.defaultMaxListeners = 20 + +const eventTarget = new EventTarget() +// Only way to increase limit for `EventTarget` instances +// as these doesn't expose its own `setMaxListeners` method +EventEmitter.setMaxListeners(20, eventTarget) +``` + +
+n
number
eventTargets
setMaxListeners(n, eventTargets) =>
Socket
– This class is an abstraction of a TCP socket or a streaming IPC
endpoint
+(uses named pipes on Windows, and Unix domain sockets otherwise). It is also
+an EventEmitter
.+ +A `net.Socket` can be created by the user and used directly to interact with +a server. For example, it is returned by {@link createConnection}, +so the user can use it to talk to the server. + +It can also be created by Node.js and passed to the user when a connection +is received. For example, it is passed to the listeners of a `'connection'` event emitted on a {@link Server}, so the user can use +it to interact with the client. + +
+ boolean
+
+This can be changed manually to change the half-open behavior of an existing`Duplex` stream instance, but must be changed before the `'end'` event is
+emitted.
+
+ number
+
+`net.Socket` has the property that `socket.write()` always works. This is to
+help users get up and running quickly. The computer cannot always keep up
+with the amount of data that is written to a socket. The network connection
+simply might be too slow. Node.js will internally queue up the data written to a
+socket and send it out over the wire when it is possible.
+
+The consequence of this internal buffering is that memory may grow.
+Users who experience large or growing `bufferSize` should attempt to
+"throttle" the data flows in their program with `socket.pause()` and `socket.resume()`.
+
+ boolean boolean string number boolean boolean boolean boolean number number boolean string string number typeof captureRejectionSymbol boolean typeof errorMonitor
+
+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.
+
+ [asyncIterator]() => #
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L819 allowHalfOpen
– If false
then the stream will automatically end the writable side when the
+readable side ends. Set initially by the allowHalfOpen
constructor option,
+which defaults to false
.#
src/.fastpm/-/@types/node@17.0.45/net.d.ts#L231 bufferSize
– This property shows the number of characters buffered for writing. The buffer
+may contain strings whose length after encoding is not yet known. So this number
+is only an approximation of the number of bytes in the buffer.#
src/.fastpm/-/@types/node@17.0.45/net.d.ts#L249 connecting
– If true
,socket.connect(options[, connectListener])
was
+called and has not yet finished. It will stay true
until the socket becomes
+connected, then it is set to false
and the 'connect'
event is emitted. Note
+that the socket.connect(options[, connectListener])
callback is a listener for the 'connect'
event.#
src/.fastpm/-/@types/node@17.0.45/net.d.ts#L253 destroyed
– See writable.destroyed
for further details.#
src/.fastpm/-/@types/node@17.0.45/net.d.ts#L260 localAddress
– The string representation of the local IP address the remote client is
+connecting on. For example, in a server listening on '0.0.0.0'
, if a client
+connects on '192.168.1.1'
, the value of socket.localAddress
would be'192.168.1.1'
.#
src/.fastpm/-/@types/node@17.0.45/net.d.ts#L265 localPort
– The numeric representation of the local port. For example, 80
or 21
.#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L71 readable
– Is true
if it is safe to call readable.read()
, which means
+the stream has not been destroyed or emitted 'error'
or 'end'
.#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L65 readableAborted
– Returns whether the stream was destroyed or errored before emitting 'end'
.#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L77 readableDidRead
– Returns whether 'data'
has been emitted.#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L82 readableEncoding
– Getter for the property encoding
of a given Readable
stream. The encoding
property can be set using the readable.setEncoding()
method.null
| BufferEncoding#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L87 readableEnded
– Becomes true
when 'end'
event is emitted.#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L93 readableFlowing
– This property reflects the current state of a Readable
stream as described
+in the Three states
section.null
| boolean#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L98 readableHighWaterMark
– Returns the value of highWaterMark
passed when creating this Readable
.#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L105 readableLength
– This property contains the number of bytes (or objects) in the queue
+ready to be read. The value provides introspection data regarding
+the status of the highWaterMark
.#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L110 readableObjectMode
– Getter for the property objectMode
of a given Readable
stream.#
src/.fastpm/-/@types/node@17.0.45/net.d.ts#L271 readyState
– This property represents the state of the connection as a string.#
src/.fastpm/-/@types/node@17.0.45/net.d.ts#L277 remoteAddress
– The string representation of the remote IP address. For example,'74.125.127.100'
or '2001:4860:a005::68'
. Value may be undefined
if
+the socket is destroyed (for example, if the client disconnected).#
src/.fastpm/-/@types/node@17.0.45/net.d.ts#L282 remoteFamily
– The string representation of the remote IP family. 'IPv4'
or 'IPv6'
.#
src/.fastpm/-/@types/node@17.0.45/net.d.ts#L287 remotePort
– The numeric representation of the remote port. For example, 80
or 21
.#
src/.fastpm/-/@types/node@17.0.45/events.d.ts#L301 captureRejectionSymbol
#
src/.fastpm/-/@types/node@17.0.45/events.d.ts#L306 captureRejections
– Sets or gets the default captureRejection value for all emitters.#
src/.fastpm/-/@types/node@17.0.45/events.d.ts#L300 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.#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L479 [asyncIterator]
()
AsyncIterableIterator<any>
_construct
(callback)
_construct(callback) =>
_destroy
(error, callback) #
error
null
| Error
_destroy(error, callback) =>
_final
(callback)
_final(callback) =>
_read
(size) number#
size
_read(size) =>
_write
(chunk, encoding, callback) _write(chunk, encoding, callback) =>
_writev
(chunks, callback) { #
chunks
callback
(error) #
error
null
| Error
callback(error) =>
_writev(chunks, callback) =>
addListener
(event, listener) – events.EventEmitter
+1. close
+2. connect
+3. data
+4. drain
+5. end
+6. error
+7. lookup
+8. timeout string#
event
addListener(event, listener) =>
event
"close"
listener
(hadError) boolean#
hadError
listener(hadError) =>
addListener(event, listener) =>
event
"connect"
listener
()
listener() =>
addListener(event, listener) =>
event
"data"
addListener(event, listener) =>
event
"drain"
listener
()
listener() =>
addListener(event, listener) =>
event
"end"
listener
()
listener() =>
addListener(event, listener) =>
event
"error"
listener
(err) Error#
err
listener(err) =>
addListener(event, listener) =>
event
"lookup"
listener
(err, address, family, host) addListener(event, listener) =>
event
"ready"
listener
()
listener() =>
addListener(event, listener) =>
event
"timeout"
listener
()
listener() =>
addListener(event, listener) =>
address
() – Returns the bound address
, the address family
name and port
of the
+socket as reported by the operating system:{ port: 12346, family: 'IPv4', address: '127.0.0.1' }
address() =>
connect
(options, connectionListener) – Initiate a connection on a given socket.
+ +Possible signatures: + +- `socket.connect(options[, connectListener])` +- `socket.connect(path[, connectListener])` for `IPC` connections. +- `socket.connect(port[, host][, connectListener])` for TCP connections. +- Returns: `net.Socket` The socket itself. + +This function is asynchronous. When the connection is established, the `'connect'` event will be emitted. If there is a problem connecting, +instead of a `'connect'` event, an `'error'` event will be emitted with +the error passed to the `'error'` listener. +The last parameter `connectListener`, if supplied, will be added as a listener +for the `'connect'` event **once**. + +This function should only be used for reconnecting a socket after`'close'` has been emitted or otherwise it may lead to undefined +behavior. + +
+options
connectionListener
()
connectionListener() =>
connect(options, connectionListener) =>
port
number
host
string
connectionListener
()
connectionListener() =>
connect(port, host, connectionListener) =>
port
number
connectionListener
()
connectionListener() =>
connect(port, connectionListener) =>
path
string
connectionListener
()
connectionListener() =>
connect(path, connectionListener) =>
cork
()
cork() =>
destroy
(error) – Destroy the stream. Optionally emit an 'error'
event, and emit a 'close'
event (unless emitClose
is set to false
). After this call, the readable
+stream will release any internal resources and subsequent calls to push()
will be ignored.
+ +Once `destroy()` has been called any further calls will be a no-op and no +further errors except from `_destroy()` may be emitted as `'error'`. + +Implementors should not override this method, but instead implement `readable._destroy()`. + +
+error
– Error which will be passed as payload in 'error'
event
+Error
destroy(error) =>
emit
(event, args) – Synchronously calls each of the listeners registered for the event namedeventName
, in the order they were registered, passing the supplied arguments
+to each.
+ +Returns `true` if the event had listeners, `false` otherwise. + +```js +const EventEmitter = require('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 +``` + +
+event
string | symbol
args
any []
emit(event, args) =>
event
"close"
hadError
boolean
emit(event, hadError) =>
event
"connect"
emit(event) =>
event
"data"
data
emit(event, data) =>
event
"drain"
emit(event) =>
event
"end"
emit(event) =>
event
"error"
err
Error
emit(event, err) =>
event
"lookup"
err
Error
address
string
family
string | number
host
string
emit(event, err, address, family, host) =>
event
"ready"
emit(event) =>
event
"timeout"
emit(event) =>
end
(callback) – Half-closes the socket. i.e., it sends a FIN packet. It is possible the
+server will still send some data.
+ +See `writable.end()` for further details. + +
+callback
()
callback() =>
end(callback) =>
buffer
string | Uint8Array
callback
()
callback() =>
end(buffer, callback) =>
str
string | Uint8Array
encoding
callback
()
callback() =>
end(str, encoding, callback) =>
eventNames
() – Returns an array listing the events for which the emitter has registered
+listeners. The values in the array are strings or Symbol
s.
+ +```js +const EventEmitter = require('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) ] +``` + +
+eventNames() =>
getMaxListeners
() – Returns the current max listener value for the EventEmitter
which is either
+set by emitter.setMaxListeners(n)
or defaults to {@link defaultMaxListeners}.
getMaxListeners() =>
isPaused
() – The readable.isPaused()
method returns the current operating state of theReadable
. This is used primarily by the mechanism that underlies thereadable.pipe()
method. In most
+typical cases, there will be no reason to
+use this method directly.
+ +```js +const readable = new stream.Readable() + +readable.isPaused() // === false +readable.pause() +readable.isPaused() // === true +readable.resume() +readable.isPaused() // === false +``` + +
+isPaused() =>
listenerCount
(eventName) – Returns the number of listeners listening to the event named eventName
. string | symbol#
eventName
– The name of the event being listened for
+
listenerCount(eventName) =>
listeners
(eventName) – Returns a copy of the array of listeners for the event named eventName
.
+ +```js +server.on('connection', stream => { + console.log('someone connected!') +}) +console.log(util.inspect(server.listeners('connection'))) +// Prints: [ [Function] ] +``` + +
+eventName
string | symbol
listeners(eventName) =>
off
(eventName, listener) – Alias for emitter.removeListener()
. string | symbol#
eventName
off(eventName, listener) =>
on
(event, listener) – 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.
+ +```js +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. + +```js +const myEE = new EventEmitter() +myEE.on('foo', () => console.log('a')) +myEE.prependListener('foo', () => console.log('b')) +myEE.emit('foo') +// Prints: +// b +// a +``` + +
+event
string
listener
(args) any []#
args
listener(args) =>
on(event, listener) =>
event
"close"
listener
(hadError) boolean#
hadError
listener(hadError) =>
on(event, listener) =>
event
"connect"
listener
()
listener() =>
on(event, listener) =>
event
"data"
on(event, listener) =>
event
"drain"
listener
()
listener() =>
on(event, listener) =>
event
"end"
listener
()
listener() =>
on(event, listener) =>
event
"error"
listener
(err) Error#
err
listener(err) =>
on(event, listener) =>
event
"lookup"
listener
(err, address, family, host) on(event, listener) =>
event
"ready"
listener
()
listener() =>
on(event, listener) =>
event
"timeout"
listener
()
listener() =>
on(event, listener) =>
once
(event, listener) – Adds a one-timelistener
function for the event named eventName
. The
+next time eventName
is triggered, this listener is removed and then invoked.
+ +```js +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. + +```js +const myEE = new EventEmitter() +myEE.once('foo', () => console.log('a')) +myEE.prependOnceListener('foo', () => console.log('b')) +myEE.emit('foo') +// Prints: +// b +// a +``` + +
+event
string
listener
(args) any []#
args
listener(args) =>
once(event, listener) =>
event
"close"
listener
(hadError) boolean#
hadError
listener(hadError) =>
once(event, listener) =>
event
"connect"
listener
()
listener() =>
once(event, listener) =>
event
"data"
once(event, listener) =>
event
"drain"
listener
()
listener() =>
once(event, listener) =>
event
"end"
listener
()
listener() =>
once(event, listener) =>
event
"error"
listener
(err) Error#
err
listener(err) =>
once(event, listener) =>
event
"lookup"
listener
(err, address, family, host) once(event, listener) =>
event
"ready"
listener
()
listener() =>
once(event, listener) =>
event
"timeout"
listener
()
listener() =>
once(event, listener) =>
pause
() – Pauses the reading of data. That is, 'data'
events will not be emitted.
+Useful to throttle back an upload.
pause() =>
pipe
(destination, { end }) { #
options
pipe<T extends WritableStream<T>>(destination, { end }) =>
prependListener
(event, listener) – 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.
+ +```js +server.prependListener('connection', stream => { + console.log('someone connected!') +}) +``` + +Returns a reference to the `EventEmitter`, so that calls can be chained. + +
+event
string
listener
(args) any []#
args
listener(args) =>
prependListener(event, listener) =>
event
"close"
listener
(hadError) boolean#
hadError
listener(hadError) =>
prependListener(event, listener) =>
event
"connect"
listener
()
listener() =>
prependListener(event, listener) =>
event
"data"
prependListener(event, listener) =>
event
"drain"
listener
()
listener() =>
prependListener(event, listener) =>
event
"end"
listener
()
listener() =>
prependListener(event, listener) =>
event
"error"
listener
(err) Error#
err
listener(err) =>
prependListener(event, listener) =>
event
"lookup"
listener
(err, address, family, host) prependListener(event, listener) =>
event
"ready"
listener
()
listener() =>
prependListener(event, listener) =>
event
"timeout"
listener
()
listener() =>
prependListener(event, listener) =>
prependOnceListener
(event, listener) – Adds a one-timelistener
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.
+ +```js +server.prependOnceListener('connection', stream => { + console.log('Ah, we have our first user!') +}) +``` + +Returns a reference to the `EventEmitter`, so that calls can be chained. + +
+event
string
listener
(args) any []#
args
listener(args) =>
prependOnceListener(event, listener) =>
event
"close"
listener
(hadError) boolean#
hadError
listener(hadError) =>
prependOnceListener(event, listener) =>
event
"connect"
listener
()
listener() =>
prependOnceListener(event, listener) =>
event
"data"
prependOnceListener(event, listener) =>
event
"drain"
listener
()
listener() =>
prependOnceListener(event, listener) =>
event
"end"
listener
()
listener() =>
prependOnceListener(event, listener) =>
event
"error"
listener
(err) Error#
err
listener(err) =>
prependOnceListener(event, listener) =>
event
"lookup"
listener
(err, address, family, host) prependOnceListener(event, listener) =>
event
"ready"
listener
()
listener() =>
prependOnceListener(event, listener) =>
event
"timeout"
listener
()
listener() =>
prependOnceListener(event, listener) =>
push
(chunk, encoding) push(chunk, encoding) =>
rawListeners
(eventName) – Returns a copy of the array of listeners for the event named eventName
,
+including any wrappers (such as those created by .once()
).
+ +```js +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') +``` + +
+eventName
string | symbol
rawListeners(eventName) =>
read
(size) – The readable.read()
method pulls some data out of the internal buffer and
+returns it. If no data available to be read, null
is returned. By default,
+the data will be returned as a Buffer
object unless an encoding has been
+specified using the readable.setEncoding()
method or the stream is operating
+in object mode.
+ +The optional `size` argument specifies a specific number of bytes to read. If`size` bytes are not available to be read, `null` will be returned _unless_the stream has ended, in which +case all of the data remaining in the internal +buffer will be returned. + +If the `size` argument is not specified, all of the data contained in the +internal buffer will be returned. + +The `size` argument must be less than or equal to 1 GiB. + +The `readable.read()` method should only be called on `Readable` streams +operating in paused mode. In flowing mode, `readable.read()` is called +automatically until the internal buffer is fully drained. + +```js +const readable = getReadableStreamSomehow() + +// 'readable' may be triggered multiple times as data is buffered in +readable.on('readable', () => { + let chunk + console.log('Stream is readable (new data received in buffer)') + // Use a loop to make sure we read all currently available data + while (null !== (chunk = readable.read())) { + console.log(`Read ${chunk.length} bytes of data...`) + } +}) + +// 'end' will be triggered once when there is no more data available +readable.on('end', () => { + console.log('Reached end of stream.') +}) +``` + +Each call to `readable.read()` returns a chunk of data, or `null`. The chunks +are not concatenated. A `while` loop is necessary to consume all data +currently in the buffer. When reading a large file `.read()` may return `null`, +having consumed all buffered content so far, but there is still more data to +come not yet buffered. In this case a new `'readable'` event will be emitted +when there is more data in the buffer. Finally the `'end'` event will be +emitted when there is no more data to come. + +Therefore to read a file's whole contents from a `readable`, it is necessary +to collect chunks across multiple `'readable'` events: + +```js +const chunks = [] + +readable.on('readable', () => { + let chunk + while (null !== (chunk = readable.read())) { + chunks.push(chunk) + } +}) + +readable.on('end', () => { + const content = chunks.join('') +}) +``` + +A `Readable` stream in object mode will always return a single item from +a call to `readable.read(size)`, regardless of the value of the`size` argument. + +If the `readable.read()` method returns a chunk of data, a `'data'` event will +also be emitted. + +Calling {@link read} after the `'end'` event has +been emitted will return `null`. No runtime error will be raised. + +
+size
– Optional argument to specify how much data to read.
+number
read(size) =>
ref
() – Opposite of unref()
, calling ref()
on a previously unref
ed socket will_not_ let the program exit if it's the only socket left (the default behavior).
+If the socket is ref
ed calling ref
again will have no effect.
ref() =>
removeAllListeners
(event) – 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. + +
+event
string | symbol
removeAllListeners(event) =>
removeListener
(event, listener) – Removes the specified listener
from the listener array for the event namedeventName
.
+ +```js +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. + +```js +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 indices 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: + +```js +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. + +
+event
"close"
listener
()
listener() =>
removeListener(event, listener) =>
event
"data"
listener
(chunk) any#
chunk
listener(chunk) =>
removeListener(event, listener) =>
event
"end"
listener
()
listener() =>
removeListener(event, listener) =>
event
"error"
listener
(err) Error#
err
listener(err) =>
removeListener(event, listener) =>
event
"pause"
listener
()
listener() =>
removeListener(event, listener) =>
event
"readable"
listener
()
listener() =>
removeListener(event, listener) =>
event
"resume"
listener
()
listener() =>
removeListener(event, listener) =>
event
string | symbol
listener
(args) any []#
args
listener(args) =>
removeListener(event, listener) =>
resume
() – Resumes reading after a call to socket.pause()
.
resume() =>
setDefaultEncoding
(encoding) #
encoding
setDefaultEncoding(encoding) =>
setEncoding
(encoding) – Set the encoding for the socket as a Readable Stream
. See readable.setEncoding()
for more information. #
encoding
setEncoding(encoding) =>
setKeepAlive
(enable, initialDelay) – Enable/disable keep-alive functionality, and optionally set the initial
+delay before the first keepalive probe is sent on an idle socket.
+ +Set `initialDelay` (in milliseconds) to set the delay between the last +data packet received and the first keepalive probe. Setting `0` for`initialDelay` will leave the value unchanged from the default +(or previous) setting. + +Enabling the keep-alive functionality will set the following socket options: + +- `SO_KEEPALIVE=1` +- `TCP_KEEPIDLE=initialDelay` +- `TCP_KEEPCNT=10` +- `TCP_KEEPINTVL=1` + +
+enable
boolean
initialDelay
number
setKeepAlive(enable, initialDelay) =>
setMaxListeners
(n) – By default EventEmitter
s 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 toInfinity
(or 0
) to indicate an unlimited number of listeners.
+ +Returns a reference to the `EventEmitter`, so that calls can be chained. + +
+n
number
setMaxListeners(n) =>
setNoDelay
(noDelay) – Enable/disable the use of Nagle's algorithm.
+ +When a TCP connection is created, it will have Nagle's algorithm enabled. + +Nagle's algorithm delays data before it is sent via the network. It attempts +to optimize throughput at the expense of latency. + +Passing `true` for `noDelay` or not passing an argument will disable Nagle's +algorithm for the socket. Passing `false` for `noDelay` will enable Nagle's +algorithm. + +
+noDelay
boolean
setNoDelay(noDelay) =>
setTimeout
(timeout, callback) – Sets the socket to timeout after timeout
milliseconds of inactivity on
+the socket. By default net.Socket
do not have a timeout.
+ +When an idle timeout is triggered the socket will receive a `'timeout'` event but the connection will not be severed. The user must manually call `socket.end()` or `socket.destroy()` to +end the connection. + +```js +socket.setTimeout(3000) +socket.on('timeout', () => { + console.log('socket timeout') + socket.end() +}) +``` + +If `timeout` is 0, then the existing idle timeout is disabled. + +The optional `callback` parameter will be added as a one-time listener for the `'timeout'` event. + +
+timeout
number
callback
()
callback() =>
setTimeout(timeout, callback) =>
uncork
()
uncork() =>
unpipe
(destination) – The readable.unpipe()
method detaches a Writable
stream previously attached
+using the {@link pipe} method.
+ +If the `destination` is not specified, then _all_ pipes are detached. + +If the `destination` is specified, but no pipe is set up for it, then +the method does nothing. + +```js +const fs = require('fs') +const readable = getReadableStreamSomehow() +const writable = fs.createWriteStream('file.txt') +// All the data from readable goes into 'file.txt', +// but only for the first second. +readable.pipe(writable) +setTimeout(() => { + console.log('Stop writing to file.txt.') + readable.unpipe(writable) + console.log('Manually close the file stream.') + writable.end() +}, 1000) +``` + +
+destination
– Optional specific stream to unpipe
+unpipe(destination) =>
unref
() – Calling unref()
on a socket will allow the program to exit if this is the only
+active socket in the event system. If the socket is already unref
ed callingunref()
again will have no effect.
unref() =>
unshift
(chunk, encoding) – Passing chunk
as null
signals the end of the stream (EOF) and behaves the
+same as readable.push(null)
, after which no more data can be written. The EOF
+signal is put at the end of the buffer and any buffered data will still be
+flushed.
+ +The `readable.unshift()` method pushes a chunk of data back into the internal +buffer. This is useful in certain situations where a stream is being consumed by +code that needs to "un-consume" some amount of data that it has optimistically +pulled out of the source, so that the data can be passed on to some other party. + +The `stream.unshift(chunk)` method cannot be called after the `'end'` event +has been emitted or a runtime error will be thrown. + +Developers using `stream.unshift()` often should consider switching to +use of a `Transform` stream instead. See the `API for stream implementers` section for more information. + +```js +// Pull off a header delimited by \n\n. +// Use unshift() if we get too much. +// Call the callback with (error, header, stream). +const { StringDecoder } = require('string_decoder') +function parseHeader(stream, callback) { + stream.on('error', callback) + stream.on('readable', onReadable) + const decoder = new StringDecoder('utf8') + let header = '' + function onReadable() { + let chunk + while (null !== (chunk = stream.read())) { + const str = decoder.write(chunk) + if (str.match(/\n\n/)) { + // Found the header boundary. + const split = str.split(/\n\n/) + header += split.shift() + const remaining = split.join('\n\n') + const buf = Buffer.from(remaining, 'utf8') + stream.removeListener('error', callback) + // Remove the 'readable' listener before unshifting. + stream.removeListener('readable', onReadable) + if (buf.length) + stream.unshift(buf) + // Now the body of the message can be read from the stream. + callback(null, header, stream) + } else { + // Still reading the header. + header += str + } + } + } +} +``` + +Unlike {@link push}, `stream.unshift(chunk)` will not +end the reading process by resetting the internal reading state of the stream. +This can cause unexpected results if `readable.unshift()` is called during a +read (i.e. from within a {@link _read} implementation on a +custom stream). Following the call to `readable.unshift()` with an immediate {@link push} will reset the reading state appropriately, +however it is best to simply avoid calling `readable.unshift()` while in the +process of performing a read. + +
+chunk
– Chunk of data to unshift onto the read queue. For streams not operating in object mode, chunk
must be a string, Buffer
, Uint8Array
or null
. For object mode
+streams, chunk
may be any JavaScript value.any
encoding
– Encoding of string chunks. Must be a valid Buffer
encoding, such as 'utf8'
or 'ascii'
.
+unshift(chunk, encoding) =>
wrap
(stream) – Prior to Node.js 0.10, streams did not implement the entire stream
module API
+as it is currently defined. (See Compatibility
for more information.)
+ +When using an older Node.js library that emits `'data'` events and has a {@link pause} method that is advisory only, the`readable.wrap()` method can be used to create a `Readable` +stream that uses +the old stream as its data source. + +It will rarely be necessary to use `readable.wrap()` but the method has been +provided as a convenience for interacting with older Node.js applications and +libraries. + +```js +const { OldReader } = require('./old-api-module.js') +const { Readable } = require('stream') +const oreader = new OldReader() +const myReader = new Readable().wrap(oreader) + +myReader.on('readable', () => { + myReader.read() // etc. +}) +``` + +
+stream
– An "old style" readable stream
+wrap(stream) =>
write
(buffer, cb) – Sends data on the socket. The second parameter specifies the encoding in the
+case of a string. It defaults to UTF8 encoding.
+ +Returns `true` if the entire data was flushed successfully to the kernel +buffer. Returns `false` if all or part of the data was queued in user memory.`'drain'` will be emitted when the buffer is again free. + +The optional `callback` parameter will be executed when the data is finally +written out, which may not be immediately. + +See `Writable` stream `write()` method for more +information. + +
+buffer
string | Uint8Array
cb
(err) Error#
err
cb(err) =>
write(buffer, cb) =>
str
string | Uint8Array
encoding
cb
(err) Error#
err
cb(err) =>
write(str, encoding, cb) =>
from
(src) – A utility method for creating duplex streams.
+ +- `Stream` converts writable stream into writable `Duplex` and readable stream + to `Duplex`. +- `Blob` converts into readable `Duplex`. +- `string` converts into readable `Duplex`. +- `ArrayBuffer` converts into readable `Duplex`. +- `AsyncIterable` converts into a readable `Duplex`. Cannot yield `null`. +- `AsyncGeneratorFunction` converts into a readable/writable transform + `Duplex`. Must take a source `AsyncIterable` as first parameter. Cannot yield + `null`. +- `AsyncFunction` converts into a writable `Duplex`. Must return + either `null` or `undefined` +- `Object ({ writable, readable })` converts `readable` and + `writable` into `Stream` and then combines them into `Duplex` where the + `Duplex` will write to the `writable` and read from the `readable`. +- `Promise` converts into readable `Duplex`. Value `null` is ignored. + +
+src
string | Object | Stream | Iterable<any> | AsyncIterable<any> | Blob | ArrayBuffer | AsyncGeneratorFunction | Promise<any>
from(src) =>
getEventListeners
(emitter, name) – Returns a copy of the array of listeners for the event named eventName
.
+ +For `EventEmitter`s this behaves exactly the same as calling `.listeners` on +the emitter. + +For `EventTarget`s this is the only way to get the event listeners for the +event target. This is useful for debugging and diagnostic purposes. + +```js +const { getEventListeners, EventEmitter } = require('events') + +{ + const ee = new EventEmitter() + const listener = () => console.log('Events are fun') + ee.on('foo', listener) + getEventListeners(ee, 'foo') // [listener] +} +{ + const et = new EventTarget() + const listener = () => console.log('Events are fun') + et.addEventListener('foo', listener) + getEventListeners(et, 'foo') // [listener] +} +``` + +
+emitter
name
string | symbol
getEventListeners(emitter, name) =>
isDisturbed
(stream) – Returns whether the stream has been read from or cancelled. #
stream
isDisturbed(stream) =>
listenerCount
(emitter, eventName) – A class method that returns the number of listeners for the given eventName
registered on the given emitter
.
+ +```js +const { EventEmitter, listenerCount } = require('events') +const myEmitter = new EventEmitter() +myEmitter.on('event', () => {}) +myEmitter.on('event', () => {}) +console.log(listenerCount(myEmitter, 'event')) +// Prints: 2 +``` + +
+emitter
– The emitter to queryeventName
– The event name
+string | symbol
listenerCount(emitter, eventName) =>
on
(emitter, eventName, options) – ```js
+const { on, EventEmitter } = require('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: + +```js +const { on, EventEmitter } = require('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()); +```` + +
+emitter
eventName
– The name of the event being listened forstring
options
on(emitter, eventName, options) =>
once
(emitter, eventName, options) – 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](https://dom.spec.whatwg.org/#interface-eventtarget) interface, which has no special`'error'` event +semantics and does not listen to the `'error'` event. + +```js +const { once, EventEmitter } = require('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.log('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: + +```js +const { EventEmitter, once } = require('events') + +const ee = new EventEmitter() + +once(ee, 'error') + .then(([err]) => console.log('ok', err.message)) + .catch(err => console.log('error', err.message)) + +ee.emit('error', new Error('boom')) + +// Prints: ok boom +``` + +An `AbortSignal` can be used to cancel waiting for the event: + +```js +const { EventEmitter, once } = require('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() // Abort waiting for the event +ee.emit('foo') // Prints: Waiting for the event was canceled! +``` + +
+emitter
eventName
string | symbol
options
once(emitter, eventName, options) =>
emitter
eventName
string
options
once(emitter, eventName, options) =>
setMaxListeners
(n, eventTargets) – By default EventEmitter
s 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 EventEmitter.setMaxListeners()
method allows the default limit to be
+modified (if eventTargets is empty) or modify the limit specified in every EventTarget
| EventEmitter
passed as arguments.
+The value can be set toInfinity
(or 0
) to indicate an unlimited number of listeners.
+ +```js +EventEmitter.setMaxListeners(20) +// Equivalent to +EventEmitter.defaultMaxListeners = 20 + +const eventTarget = new EventTarget() +// Only way to increase limit for `EventTarget` instances +// as these doesn't expose its own `setMaxListeners` method +EventEmitter.setMaxListeners(20, eventTarget) +``` + +
+n
number
eventTargets
setMaxListeners(n, eventTargets) =>
SourceMapConsumer
#
src/.fastpm/-/source-map-js@1.0.2/source-map.d.ts#L54 constructor
(rawSourceMap)
#
src/.fastpm/-/source-map-js@1.0.2/source-map.d.ts#L58 allGeneratedPositionsFor
(originalPosition)
computeColumnSpans
()
computeColumnSpans() =>
eachMapping
(callback, context, order) context
any
order
number
eachMapping(callback, context, order) =>
generatedPositionFor
(originalPosition) #
originalPosition
generatedPositionFor(originalPosition) =>
hasContentsOfAllSources
()
hasContentsOfAllSources() =>
originalPositionFor
(generatedPosition) #
generatedPosition
originalPositionFor(generatedPosition) =>
sourceContentFor
(source, returnNullOnMissing) SourceMapGenerator
addMapping(mapping) => #
src/.fastpm/-/source-map-js@1.0.2/source-map.d.ts#L72 constructor
(startOfSourceMap)
#
src/.fastpm/-/source-map-js@1.0.2/source-map.d.ts#L74 addMapping
(mapping)
void
applySourceMap
(sourceMapConsumer, sourceFile, sourceMapPath) setSourceContent
(sourceFile, sourceContent) toString
()
toString() =>
fromSourceMap
(sourceMapConsumer) #
sourceMapConsumer
fromSourceMap(sourceMapConsumer) =>
Stats
– A fs.Stats
object provides information about a file.+ +Objects returned from {@link stat}, {@link lstat} and {@link fstat} and +their synchronous counterparts are of this type. +If `bigint` in the `options` passed to those methods is true, the numeric values +will be `bigint` instead of `number`, and the object will contain additional +nanosecond-precision properties suffixed with `Ns`. + +```console +Stats { + dev: 2114, + ino: 48064969, + mode: 33188, + nlink: 1, + uid: 85, + gid: 100, + rdev: 0, + size: 527, + blksize: 4096, + blocks: 8, + atimeMs: 1318289051000.1, + mtimeMs: 1318289051000.1, + ctimeMs: 1318289051000.1, + birthtimeMs: 1318289051000.1, + atime: Mon, 10 Oct 2011 23:24:11 GMT, + mtime: Mon, 10 Oct 2011 23:24:11 GMT, + ctime: Mon, 10 Oct 2011 23:24:11 GMT, + birthtime: Mon, 10 Oct 2011 23:24:11 GMT } +``` + +`bigint` version: + +```console +BigIntStats { + dev: 2114n, + ino: 48064969n, + mode: 33188n, + nlink: 1n, + uid: 85n, + gid: 100n, + rdev: 0n, + size: 527n, + blksize: 4096n, + blocks: 8n, + atimeMs: 1318289051000n, + mtimeMs: 1318289051000n, + ctimeMs: 1318289051000n, + birthtimeMs: 1318289051000n, + atimeNs: 1318289051000000000n, + mtimeNs: 1318289051000000000n, + ctimeNs: 1318289051000000000n, + birthtimeNs: 1318289051000000000n, + atime: Mon, 10 Oct 2011 23:24:11 GMT, + mtime: Mon, 10 Oct 2011 23:24:11 GMT, + ctime: Mon, 10 Oct 2011 23:24:11 GMT, + birthtime: Mon, 10 Oct 2011 23:24:11 GMT } +``` + +
+ isBlockDevice() => #
isBlockDevice
()
boolean
isCharacterDevice
()
isCharacterDevice() =>
isDirectory
()
isDirectory() =>
isFIFO
()
isFIFO() =>
isFile
()
isFile() =>
isSocket
()
isSocket() =>
isSymbolicLink
()
isSymbolicLink() =>
Stream
typeof captureRejectionSymbol boolean typeof errorMonitor
+
+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.
+
+#
src/.fastpm/-/@types/node@17.0.45/events.d.ts#L301 captureRejectionSymbol
#
src/.fastpm/-/@types/node@17.0.45/events.d.ts#L306 captureRejections
– Sets or gets the default captureRejection value for all emitters.#
src/.fastpm/-/@types/node@17.0.45/events.d.ts#L300 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.
addListener(eventName, listener) =>
emit
(eventName, args) – Synchronously calls each of the listeners registered for the event namedeventName
, in the order they were registered, passing the supplied arguments
+to each.
+ +Returns `true` if the event had listeners, `false` otherwise. + +```js +const EventEmitter = require('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 +``` + +
+eventName
string | symbol
args
any []
emit(eventName, args) =>
eventNames
() – Returns an array listing the events for which the emitter has registered
+listeners. The values in the array are strings or Symbol
s.
+ +```js +const EventEmitter = require('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) ] +``` + +
+eventNames() =>
getMaxListeners
() – Returns the current max listener value for the EventEmitter
which is either
+set by emitter.setMaxListeners(n)
or defaults to {@link defaultMaxListeners}.
getMaxListeners() =>
listenerCount
(eventName) – Returns the number of listeners listening to the event named eventName
. string | symbol#
eventName
– The name of the event being listened for
+
listenerCount(eventName) =>
listeners
(eventName) – Returns a copy of the array of listeners for the event named eventName
.
+ +```js +server.on('connection', stream => { + console.log('someone connected!') +}) +console.log(util.inspect(server.listeners('connection'))) +// Prints: [ [Function] ] +``` + +
+eventName
string | symbol
listeners(eventName) =>
off
(eventName, listener) – Alias for emitter.removeListener()
. string | symbol#
eventName
off(eventName, listener) =>
on
(eventName, listener) – 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.
+ +```js +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. + +```js +const myEE = new EventEmitter() +myEE.on('foo', () => console.log('a')) +myEE.prependListener('foo', () => console.log('b')) +myEE.emit('foo') +// Prints: +// b +// a +``` + +
+eventName
– The name of the event.string | symbol
listener
(args) any []#
args
listener(args) =>
on(eventName, listener) =>
once
(eventName, listener) – Adds a one-timelistener
function for the event named eventName
. The
+next time eventName
is triggered, this listener is removed and then invoked.
+ +```js +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. + +```js +const myEE = new EventEmitter() +myEE.once('foo', () => console.log('a')) +myEE.prependOnceListener('foo', () => console.log('b')) +myEE.emit('foo') +// Prints: +// b +// a +``` + +
+eventName
– The name of the event.string | symbol
listener
(args) any []#
args
listener(args) =>
once(eventName, listener) =>
pipe
(destination, { end }) { #
options
pipe<T extends WritableStream<T>>(destination, { end }) =>
prependListener
(eventName, listener) – 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.
+ +```js +server.prependListener('connection', stream => { + console.log('someone connected!') +}) +``` + +Returns a reference to the `EventEmitter`, so that calls can be chained. + +
+eventName
– The name of the event.string | symbol
listener
(args) any []#
args
listener(args) =>
prependListener(eventName, listener) =>
prependOnceListener
(eventName, listener) – Adds a one-timelistener
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.
+ +```js +server.prependOnceListener('connection', stream => { + console.log('Ah, we have our first user!') +}) +``` + +Returns a reference to the `EventEmitter`, so that calls can be chained. + +
+eventName
– The name of the event.string | symbol
listener
(args) any []#
args
listener(args) =>
prependOnceListener(eventName, listener) =>
rawListeners
(eventName) – Returns a copy of the array of listeners for the event named eventName
,
+including any wrappers (such as those created by .once()
).
+ +```js +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') +``` + +
+eventName
string | symbol
rawListeners(eventName) =>
removeAllListeners
(event) – 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. + +
+event
string | symbol
removeAllListeners(event) =>
removeListener
(eventName, listener) – Removes the specified listener
from the listener array for the event namedeventName
.
+ +```js +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. + +```js +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 indices 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: + +```js +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. + +
+eventName
string | symbol
listener
(args) any []#
args
listener(args) =>
removeListener(eventName, listener) =>
setMaxListeners
(n) – By default EventEmitter
s 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 toInfinity
(or 0
) to indicate an unlimited number of listeners.
+ +Returns a reference to the `EventEmitter`, so that calls can be chained. + +
+n
number
setMaxListeners(n) =>
getEventListeners
(emitter, name) – Returns a copy of the array of listeners for the event named eventName
.
+ +For `EventEmitter`s this behaves exactly the same as calling `.listeners` on +the emitter. + +For `EventTarget`s this is the only way to get the event listeners for the +event target. This is useful for debugging and diagnostic purposes. + +```js +const { getEventListeners, EventEmitter } = require('events') + +{ + const ee = new EventEmitter() + const listener = () => console.log('Events are fun') + ee.on('foo', listener) + getEventListeners(ee, 'foo') // [listener] +} +{ + const et = new EventTarget() + const listener = () => console.log('Events are fun') + et.addEventListener('foo', listener) + getEventListeners(et, 'foo') // [listener] +} +``` + +
+emitter
name
string | symbol
getEventListeners(emitter, name) =>
listenerCount
(emitter, eventName) – A class method that returns the number of listeners for the given eventName
registered on the given emitter
.
+ +```js +const { EventEmitter, listenerCount } = require('events') +const myEmitter = new EventEmitter() +myEmitter.on('event', () => {}) +myEmitter.on('event', () => {}) +console.log(listenerCount(myEmitter, 'event')) +// Prints: 2 +``` + +
+emitter
– The emitter to queryeventName
– The event name
+string | symbol
listenerCount(emitter, eventName) =>
on
(emitter, eventName, options) – ```js
+const { on, EventEmitter } = require('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: + +```js +const { on, EventEmitter } = require('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()); +```` + +
+emitter
eventName
– The name of the event being listened forstring
options
on(emitter, eventName, options) =>
once
(emitter, eventName, options) – 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](https://dom.spec.whatwg.org/#interface-eventtarget) interface, which has no special`'error'` event +semantics and does not listen to the `'error'` event. + +```js +const { once, EventEmitter } = require('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.log('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: + +```js +const { EventEmitter, once } = require('events') + +const ee = new EventEmitter() + +once(ee, 'error') + .then(([err]) => console.log('ok', err.message)) + .catch(err => console.log('error', err.message)) + +ee.emit('error', new Error('boom')) + +// Prints: ok boom +``` + +An `AbortSignal` can be used to cancel waiting for the event: + +```js +const { EventEmitter, once } = require('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() // Abort waiting for the event +ee.emit('foo') // Prints: Waiting for the event was canceled! +``` + +
+emitter
eventName
string | symbol
options
once(emitter, eventName, options) =>
emitter
eventName
string
options
once(emitter, eventName, options) =>
setMaxListeners
(n, eventTargets) – By default EventEmitter
s 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 EventEmitter.setMaxListeners()
method allows the default limit to be
+modified (if eventTargets is empty) or modify the limit specified in every EventTarget
| EventEmitter
passed as arguments.
+The value can be set toInfinity
(or 0
) to indicate an unlimited number of listeners.
+ +```js +EventEmitter.setMaxListeners(20) +// Equivalent to +EventEmitter.defaultMaxListeners = 20 + +const eventTarget = new EventTarget() +// Only way to increase limit for `EventTarget` instances +// as these doesn't expose its own `setMaxListeners` method +EventEmitter.setMaxListeners(20, eventTarget) +``` + +
+n
number
eventTargets
setMaxListeners(n, eventTargets) =>
TLSSocket
– Performs transparent encryption of written data and all required TLS
+negotiation.+ +Instances of `tls.TLSSocket` implement the duplex `Stream` interface. + +Methods that return TLS connection metadata (e.g.{@link TLSSocket.getPeerCertificate} will only return data while the +connection is open. + +
+ boolean
+
+This can be changed manually to change the half-open behavior of an existing`Duplex` stream instance, but must be changed before the `'end'` event is
+emitted.
+
+ number
+
+`net.Socket` has the property that `socket.write()` always works. This is to
+help users get up and running quickly. The computer cannot always keep up
+with the amount of data that is written to a socket. The network connection
+simply might be too slow. Node.js will internally queue up the data written to a
+socket and send it out over the wire when it is possible.
+
+The consequence of this internal buffering is that memory may grow.
+Users who experience large or growing `bufferSize` should attempt to
+"throttle" the data flows in their program with `socket.pause()` and `socket.resume()`.
+
+ boolean boolean boolean string number boolean boolean boolean boolean number number boolean string string number typeof captureRejectionSymbol boolean typeof errorMonitor
+
+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.
+
+ [asyncIterator]() => #
src/.fastpm/-/@types/node@17.0.45/tls.d.ts#L144 constructor
(socket, options) – Construct a new tls.TLSSocket object from an existing TCP socket.
#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L819 allowHalfOpen
– If false
then the stream will automatically end the writable side when the
+readable side ends. Set initially by the allowHalfOpen
constructor option,
+which defaults to false
.#
src/.fastpm/-/@types/node@17.0.45/tls.d.ts#L167 alpnProtocol
– String containing the selected ALPN protocol.
+Before a handshake has completed, this value is always null.
+When a handshake is completed but not ALPN protocol was selected, tlsSocket.alpnProtocol equals false.null
| string | false
#
src/.fastpm/-/@types/node@17.0.45/net.d.ts#L231 bufferSize
– This property shows the number of characters buffered for writing. The buffer
+may contain strings whose length after encoding is not yet known. So this number
+is only an approximation of the number of bytes in the buffer.#
src/.fastpm/-/@types/node@17.0.45/net.d.ts#L249 connecting
– If true
,socket.connect(options[, connectListener])
was
+called and has not yet finished. It will stay true
until the socket becomes
+connected, then it is set to false
and the 'connect'
event is emitted. Note
+that the socket.connect(options[, connectListener])
callback is a listener for the 'connect'
event.#
src/.fastpm/-/@types/node@17.0.45/net.d.ts#L253 destroyed
– See writable.destroyed
for further details.#
src/.fastpm/-/@types/node@17.0.45/tls.d.ts#L161 encrypted
– Always returns true
. This may be used to distinguish TLS sockets from regularnet.Socket
instances.#
src/.fastpm/-/@types/node@17.0.45/net.d.ts#L260 localAddress
– The string representation of the local IP address the remote client is
+connecting on. For example, in a server listening on '0.0.0.0'
, if a client
+connects on '192.168.1.1'
, the value of socket.localAddress
would be'192.168.1.1'
.#
src/.fastpm/-/@types/node@17.0.45/net.d.ts#L265 localPort
– The numeric representation of the local port. For example, 80
or 21
.#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L71 readable
– Is true
if it is safe to call readable.read()
, which means
+the stream has not been destroyed or emitted 'error'
or 'end'
.#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L65 readableAborted
– Returns whether the stream was destroyed or errored before emitting 'end'
.#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L77 readableDidRead
– Returns whether 'data'
has been emitted.#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L82 readableEncoding
– Getter for the property encoding
of a given Readable
stream. The encoding
property can be set using the readable.setEncoding()
method.null
| BufferEncoding#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L87 readableEnded
– Becomes true
when 'end'
event is emitted.#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L93 readableFlowing
– This property reflects the current state of a Readable
stream as described
+in the Three states
section.null
| boolean#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L98 readableHighWaterMark
– Returns the value of highWaterMark
passed when creating this Readable
.#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L105 readableLength
– This property contains the number of bytes (or objects) in the queue
+ready to be read. The value provides introspection data regarding
+the status of the highWaterMark
.#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L110 readableObjectMode
– Getter for the property objectMode
of a given Readable
stream.#
src/.fastpm/-/@types/node@17.0.45/net.d.ts#L271 readyState
– This property represents the state of the connection as a string.#
src/.fastpm/-/@types/node@17.0.45/net.d.ts#L277 remoteAddress
– The string representation of the remote IP address. For example,'74.125.127.100'
or '2001:4860:a005::68'
. Value may be undefined
if
+the socket is destroyed (for example, if the client disconnected).#
src/.fastpm/-/@types/node@17.0.45/net.d.ts#L282 remoteFamily
– The string representation of the remote IP family. 'IPv4'
or 'IPv6'
.#
src/.fastpm/-/@types/node@17.0.45/net.d.ts#L287 remotePort
– The numeric representation of the remote port. For example, 80
or 21
.#
src/.fastpm/-/@types/node@17.0.45/events.d.ts#L301 captureRejectionSymbol
#
src/.fastpm/-/@types/node@17.0.45/events.d.ts#L306 captureRejections
– Sets or gets the default captureRejection value for all emitters.#
src/.fastpm/-/@types/node@17.0.45/events.d.ts#L300 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.#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L479 [asyncIterator]
()
AsyncIterableIterator<any>
_construct
(callback)
_construct(callback) =>
_destroy
(error, callback) #
error
null
| Error
_destroy(error, callback) =>
_final
(callback)
_final(callback) =>
_read
(size) number#
size
_read(size) =>
_write
(chunk, encoding, callback) _write(chunk, encoding, callback) =>
_writev
(chunks, callback) { #
chunks
callback
(error) #
error
null
| Error
callback(error) =>
_writev(chunks, callback) =>
addListener
(event, listener) – events.EventEmitter
+1. close
+2. connect
+3. data
+4. drain
+5. end
+6. error
+7. lookup
+8. timeout string#
event
addListener(event, listener) =>
event
"OCSPResponse"
addListener(event, listener) =>
event
"secureConnect"
listener
()
listener() =>
addListener(event, listener) =>
event
"session"
addListener(event, listener) =>
event
"keylog"
addListener(event, listener) =>
address
() – Returns the bound address
, the address family
name and port
of the
+socket as reported by the operating system:{ port: 12346, family: 'IPv4', address: '127.0.0.1' }
address() =>
connect
(options, connectionListener) – Initiate a connection on a given socket.
+ +Possible signatures: + +- `socket.connect(options[, connectListener])` +- `socket.connect(path[, connectListener])` for `IPC` connections. +- `socket.connect(port[, host][, connectListener])` for TCP connections. +- Returns: `net.Socket` The socket itself. + +This function is asynchronous. When the connection is established, the `'connect'` event will be emitted. If there is a problem connecting, +instead of a `'connect'` event, an `'error'` event will be emitted with +the error passed to the `'error'` listener. +The last parameter `connectListener`, if supplied, will be added as a listener +for the `'connect'` event **once**. + +This function should only be used for reconnecting a socket after`'close'` has been emitted or otherwise it may lead to undefined +behavior. + +
+options
connectionListener
()
connectionListener() =>
connect(options, connectionListener) =>
port
number
host
string
connectionListener
()
connectionListener() =>
connect(port, host, connectionListener) =>
port
number
connectionListener
()
connectionListener() =>
connect(port, connectionListener) =>
path
string
connectionListener
()
connectionListener() =>
connect(path, connectionListener) =>
cork
()
cork() =>
destroy
(error) – Destroy the stream. Optionally emit an 'error'
event, and emit a 'close'
event (unless emitClose
is set to false
). After this call, the readable
+stream will release any internal resources and subsequent calls to push()
will be ignored.
+ +Once `destroy()` has been called any further calls will be a no-op and no +further errors except from `_destroy()` may be emitted as `'error'`. + +Implementors should not override this method, but instead implement `readable._destroy()`. + +
+error
– Error which will be passed as payload in 'error'
event
+Error
destroy(error) =>
disableRenegotiation
() – Disables TLS renegotiation for this TLSSocket
instance. Once called, attempts
+to renegotiate will trigger an 'error'
event on the TLSSocket
.
disableRenegotiation() =>
emit
(event, args) – Synchronously calls each of the listeners registered for the event namedeventName
, in the order they were registered, passing the supplied arguments
+to each.
+ +Returns `true` if the event had listeners, `false` otherwise. + +```js +const EventEmitter = require('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 +``` + +
+event
string | symbol
args
any []
emit(event, args) =>
event
"OCSPResponse"
response
emit(event, response) =>
event
"secureConnect"
emit(event) =>
event
"session"
session
emit(event, session) =>
event
"keylog"
line
emit(event, line) =>
enableTrace
() – When enabled, TLS packet trace information is written to stderr
. This can be
+used to debug TLS connection problems.
+ +Note: The format of the output is identical to the output of `openssl s_client -trace` or `openssl s_server -trace`. While it is produced by OpenSSL's`SSL_trace()` function, the format is +undocumented, can change without notice, +and should not be relied on. + +
+enableTrace() =>
end
(callback) – Half-closes the socket. i.e., it sends a FIN packet. It is possible the
+server will still send some data.
+ +See `writable.end()` for further details. + +
+callback
()
callback() =>
end(callback) =>
buffer
string | Uint8Array
callback
()
callback() =>
end(buffer, callback) =>
str
string | Uint8Array
encoding
callback
()
callback() =>
end(str, encoding, callback) =>
eventNames
() – Returns an array listing the events for which the emitter has registered
+listeners. The values in the array are strings or Symbol
s.
+ +```js +const EventEmitter = require('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) ] +``` + +
+eventNames() =>
exportKeyingMaterial
(length, label, context) – Keying material is used for validations to prevent different kind of attacks in
+network protocols, for example in the specifications of IEEE 802.1X.
+
+Example
+
+```js
+const keyingMaterial = tlsSocket.exportKeyingMaterial(
+ 128,
+ 'client finished');
+
+
+ Example return value of keyingMaterial:
+
length
– number of bytes to retrieve from keying materialnumber
label
– an application specific label, typically this will be a value from the IANA Exporter Label
+Registry.string
context
– Optionally provide a context.exportKeyingMaterial(length, label, context) =>
getCertificate
() – Returns an object representing the local certificate. The returned object has
+some properties corresponding to the fields of the certificate.
+ +See {@link TLSSocket.getPeerCertificate} for an example of the certificate +structure. + +If there is no local certificate, an empty object will be returned. If the +socket has been destroyed, `null` will be returned. + +
+getCertificate() =>
null
| object | PeerCertificategetCipher
() – Returns an object containing information on the negotiated cipher suite.
+ +For example: + +```json +{ + "name": "AES128-SHA256", + "standardName": "TLS_RSA_WITH_AES_128_CBC_SHA256", + "version": "TLSv1.2" +} +``` + +See [SSL\_CIPHER\_get\_name](https://www.openssl.org/docs/man1.1.1/man3/SSL_CIPHER_get_name.html) for more information. + +
+getCipher() =>
getEphemeralKeyInfo
() – Returns an object representing the type, name, and size of parameter of
+an ephemeral key exchange in perfect forward secrecy
on a client
+connection. It returns an empty object when the key exchange is not
+ephemeral. As this is only supported on a client socket; null
is returned
+if called on a server socket. The supported types are 'DH'
and 'ECDH'
. Thename
property is available only when type is 'ECDH'
.
+ +For example: `{ type: 'ECDH', name: 'prime256v1', size: 256 }`. + +
+getEphemeralKeyInfo() =>
null
| object | EphemeralKeyInfogetFinished
() – As the Finished
messages are message digests of the complete handshake
+(with a total of 192 bits for TLS 1.0 and more for SSL 3.0), they can
+be used for external authentication procedures when the authentication
+provided by SSL/TLS is not desired or is not enough.
+ +Corresponds to the `SSL_get_finished` routine in OpenSSL and may be used +to implement the `tls-unique` channel binding from [RFC 5929](https://tools.ietf.org/html/rfc5929). + +
+getFinished() =>
getMaxListeners
() – Returns the current max listener value for the EventEmitter
which is either
+set by emitter.setMaxListeners(n)
or defaults to {@link defaultMaxListeners}.
getMaxListeners() =>
getPeerCertificate
(detailed) – Returns an object representing the peer's certificate. If the peer does not
+provide a certificate, an empty object will be returned. If the socket has been
+destroyed, null
will be returned.
+ +If the full certificate chain was requested, each certificate will include an`issuerCertificate` property containing an object representing its issuer's +certificate. + +
+detailed
– Include the full certificate chain if true
, otherwise include just the peer's certificate.true
getPeerCertificate(detailed) =>
detailed
false
getPeerCertificate(detailed) =>
detailed
boolean
getPeerCertificate(detailed) =>
getPeerFinished
() – As the Finished
messages are message digests of the complete handshake
+(with a total of 192 bits for TLS 1.0 and more for SSL 3.0), they can
+be used for external authentication procedures when the authentication
+provided by SSL/TLS is not desired or is not enough.
+ +Corresponds to the `SSL_get_peer_finished` routine in OpenSSL and may be used +to implement the `tls-unique` channel binding from [RFC 5929](https://tools.ietf.org/html/rfc5929). + +
+getPeerFinished() =>
getPeerX509Certificate
() – Returns the peer certificate as an X509Certificate
object.
+ +If there is no peer certificate, or the socket has been destroyed,`undefined` will be returned. + +
+getPeerX509Certificate() =>
getProtocol
() – Returns a string containing the negotiated SSL/TLS protocol version of the
+current connection. The value 'unknown'
will be returned for connected
+sockets that have not completed the handshaking process. The value null
will
+be returned for server sockets or disconnected client sockets.
+ +Protocol versions are: + +- `'SSLv3'` +- `'TLSv1'` +- `'TLSv1.1'` +- `'TLSv1.2'` +- `'TLSv1.3'` + +See the OpenSSL [`SSL_get_version`](https://www.openssl.org/docs/man1.1.1/man3/SSL_get_version.html) documentation for more information. + +
+getProtocol() =>
null
| stringgetSession
() – Returns the TLS session data or undefined
if no session was
+negotiated. On the client, the data can be provided to the session
option of {@link connect} to resume the connection. On the server, it may be useful
+for debugging.
+ +See `Session Resumption` for more information. + +Note: `getSession()` works only for TLSv1.2 and below. For TLSv1.3, applications +must use the `'session'` event (it also works for TLSv1.2 and below). + +
+getSession() =>
getTLSTicket
() – For a client, returns the TLS session ticket if one is available, orundefined
. For a server, always returns undefined
.
+ +It may be useful for debugging. + +See `Session Resumption` for more information. + +
+getTLSTicket() =>
getX509Certificate
() – Returns the local certificate as an X509Certificate
object.
+ +If there is no local certificate, or the socket has been destroyed,`undefined` will be returned. + +
+getX509Certificate() =>
isPaused
() – The readable.isPaused()
method returns the current operating state of theReadable
. This is used primarily by the mechanism that underlies thereadable.pipe()
method. In most
+typical cases, there will be no reason to
+use this method directly.
+ +```js +const readable = new stream.Readable() + +readable.isPaused() // === false +readable.pause() +readable.isPaused() // === true +readable.resume() +readable.isPaused() // === false +``` + +
+isPaused() =>
isSessionReused
() – See Session Resumption
for more information.
isSessionReused() =>
listenerCount
(eventName) – Returns the number of listeners listening to the event named eventName
. string | symbol#
eventName
– The name of the event being listened for
+
listenerCount(eventName) =>
listeners
(eventName) – Returns a copy of the array of listeners for the event named eventName
.
+ +```js +server.on('connection', stream => { + console.log('someone connected!') +}) +console.log(util.inspect(server.listeners('connection'))) +// Prints: [ [Function] ] +``` + +
+eventName
string | symbol
listeners(eventName) =>
off
(eventName, listener) – Alias for emitter.removeListener()
. string | symbol#
eventName
off(eventName, listener) =>
on
(event, listener) – 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.
+ +```js +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. + +```js +const myEE = new EventEmitter() +myEE.on('foo', () => console.log('a')) +myEE.prependListener('foo', () => console.log('b')) +myEE.emit('foo') +// Prints: +// b +// a +``` + +
+event
string
listener
(args) any []#
args
listener(args) =>
on(event, listener) =>
event
"OCSPResponse"
on(event, listener) =>
event
"secureConnect"
listener
()
listener() =>
on(event, listener) =>
event
"session"
on(event, listener) =>
event
"keylog"
on(event, listener) =>
once
(event, listener) – Adds a one-timelistener
function for the event named eventName
. The
+next time eventName
is triggered, this listener is removed and then invoked.
+ +```js +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. + +```js +const myEE = new EventEmitter() +myEE.once('foo', () => console.log('a')) +myEE.prependOnceListener('foo', () => console.log('b')) +myEE.emit('foo') +// Prints: +// b +// a +``` + +
+event
string
listener
(args) any []#
args
listener(args) =>
once(event, listener) =>
event
"OCSPResponse"
once(event, listener) =>
event
"secureConnect"
listener
()
listener() =>
once(event, listener) =>
event
"session"
once(event, listener) =>
event
"keylog"
once(event, listener) =>
pause
() – Pauses the reading of data. That is, 'data'
events will not be emitted.
+Useful to throttle back an upload.
pause() =>
pipe
(destination, { end }) { #
options
pipe<T extends WritableStream<T>>(destination, { end }) =>
prependListener
(event, listener) – 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.
+ +```js +server.prependListener('connection', stream => { + console.log('someone connected!') +}) +``` + +Returns a reference to the `EventEmitter`, so that calls can be chained. + +
+event
string
listener
(args) any []#
args
listener(args) =>
prependListener(event, listener) =>
event
"OCSPResponse"
prependListener(event, listener) =>
event
"secureConnect"
listener
()
listener() =>
prependListener(event, listener) =>
event
"session"
prependListener(event, listener) =>
event
"keylog"
prependListener(event, listener) =>
prependOnceListener
(event, listener) – Adds a one-timelistener
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.
+ +```js +server.prependOnceListener('connection', stream => { + console.log('Ah, we have our first user!') +}) +``` + +Returns a reference to the `EventEmitter`, so that calls can be chained. + +
+event
string
listener
(args) any []#
args
listener(args) =>
prependOnceListener(event, listener) =>
event
"OCSPResponse"
prependOnceListener(event, listener) =>
event
"secureConnect"
listener
()
listener() =>
prependOnceListener(event, listener) =>
event
"session"
prependOnceListener(event, listener) =>
event
"keylog"
prependOnceListener(event, listener) =>
push
(chunk, encoding) push(chunk, encoding) =>
rawListeners
(eventName) – Returns a copy of the array of listeners for the event named eventName
,
+including any wrappers (such as those created by .once()
).
+ +```js +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') +``` + +
+eventName
string | symbol
rawListeners(eventName) =>
read
(size) – The readable.read()
method pulls some data out of the internal buffer and
+returns it. If no data available to be read, null
is returned. By default,
+the data will be returned as a Buffer
object unless an encoding has been
+specified using the readable.setEncoding()
method or the stream is operating
+in object mode.
+ +The optional `size` argument specifies a specific number of bytes to read. If`size` bytes are not available to be read, `null` will be returned _unless_the stream has ended, in which +case all of the data remaining in the internal +buffer will be returned. + +If the `size` argument is not specified, all of the data contained in the +internal buffer will be returned. + +The `size` argument must be less than or equal to 1 GiB. + +The `readable.read()` method should only be called on `Readable` streams +operating in paused mode. In flowing mode, `readable.read()` is called +automatically until the internal buffer is fully drained. + +```js +const readable = getReadableStreamSomehow() + +// 'readable' may be triggered multiple times as data is buffered in +readable.on('readable', () => { + let chunk + console.log('Stream is readable (new data received in buffer)') + // Use a loop to make sure we read all currently available data + while (null !== (chunk = readable.read())) { + console.log(`Read ${chunk.length} bytes of data...`) + } +}) + +// 'end' will be triggered once when there is no more data available +readable.on('end', () => { + console.log('Reached end of stream.') +}) +``` + +Each call to `readable.read()` returns a chunk of data, or `null`. The chunks +are not concatenated. A `while` loop is necessary to consume all data +currently in the buffer. When reading a large file `.read()` may return `null`, +having consumed all buffered content so far, but there is still more data to +come not yet buffered. In this case a new `'readable'` event will be emitted +when there is more data in the buffer. Finally the `'end'` event will be +emitted when there is no more data to come. + +Therefore to read a file's whole contents from a `readable`, it is necessary +to collect chunks across multiple `'readable'` events: + +```js +const chunks = [] + +readable.on('readable', () => { + let chunk + while (null !== (chunk = readable.read())) { + chunks.push(chunk) + } +}) + +readable.on('end', () => { + const content = chunks.join('') +}) +``` + +A `Readable` stream in object mode will always return a single item from +a call to `readable.read(size)`, regardless of the value of the`size` argument. + +If the `readable.read()` method returns a chunk of data, a `'data'` event will +also be emitted. + +Calling {@link read} after the `'end'` event has +been emitted will return `null`. No runtime error will be raised. + +
+size
– Optional argument to specify how much data to read.
+number
read(size) =>
ref
() – Opposite of unref()
, calling ref()
on a previously unref
ed socket will_not_ let the program exit if it's the only socket left (the default behavior).
+If the socket is ref
ed calling ref
again will have no effect.
ref() =>
removeAllListeners
(event) – 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. + +
+event
string | symbol
removeAllListeners(event) =>
removeListener
(event, listener) – Removes the specified listener
from the listener array for the event namedeventName
.
+ +```js +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. + +```js +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 indices 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: + +```js +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. + +
+event
"close"
listener
()
listener() =>
removeListener(event, listener) =>
event
"data"
listener
(chunk) any#
chunk
listener(chunk) =>
removeListener(event, listener) =>
event
"end"
listener
()
listener() =>
removeListener(event, listener) =>
event
"error"
listener
(err) Error#
err
listener(err) =>
removeListener(event, listener) =>
event
"pause"
listener
()
listener() =>
removeListener(event, listener) =>
event
"readable"
listener
()
listener() =>
removeListener(event, listener) =>
event
"resume"
listener
()
listener() =>
removeListener(event, listener) =>
event
string | symbol
listener
(args) any []#
args
listener(args) =>
removeListener(event, listener) =>
renegotiate
({ rejectUnauthorized, requestCert }, callback) – The tlsSocket.renegotiate()
method initiates a TLS renegotiation process.
+Upon completion, the callback
function will be passed a single argument
+that is either an Error
(if the request failed) or null
.
+ +This method can be used to request a peer's certificate after the secure +connection has been established. + +When running as the server, the socket will be destroyed with an error after`handshakeTimeout` timeout. + +For TLSv1.3, renegotiation cannot be initiated, it is not supported by the +protocol. + +
+options
{
}
callback
(err) #
err
null
| Error
callback(err) =>
renegotiate({ rejectUnauthorized, requestCert }, callback) =>
resume
() – Resumes reading after a call to socket.pause()
.
resume() =>
setDefaultEncoding
(encoding) #
encoding
setDefaultEncoding(encoding) =>
setEncoding
(encoding) – Set the encoding for the socket as a Readable Stream
. See readable.setEncoding()
for more information. #
encoding
setEncoding(encoding) =>
setKeepAlive
(enable, initialDelay) – Enable/disable keep-alive functionality, and optionally set the initial
+delay before the first keepalive probe is sent on an idle socket.
+ +Set `initialDelay` (in milliseconds) to set the delay between the last +data packet received and the first keepalive probe. Setting `0` for`initialDelay` will leave the value unchanged from the default +(or previous) setting. + +Enabling the keep-alive functionality will set the following socket options: + +- `SO_KEEPALIVE=1` +- `TCP_KEEPIDLE=initialDelay` +- `TCP_KEEPCNT=10` +- `TCP_KEEPINTVL=1` + +
+enable
boolean
initialDelay
number
setKeepAlive(enable, initialDelay) =>
setMaxListeners
(n) – By default EventEmitter
s 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 toInfinity
(or 0
) to indicate an unlimited number of listeners.
+ +Returns a reference to the `EventEmitter`, so that calls can be chained. + +
+n
number
setMaxListeners(n) =>
setMaxSendFragment
(size) – The tlsSocket.setMaxSendFragment()
method sets the maximum TLS fragment size.
+Returns true
if setting the limit succeeded; false
otherwise.
+ +Smaller fragment sizes decrease the buffering latency on the client: larger +fragments are buffered by the TLS layer until the entire fragment is received +and its integrity is verified; large fragments can span multiple roundtrips +and their processing can be delayed due to packet loss or reordering. However, +smaller fragments add extra TLS framing bytes and CPU overhead, which may +decrease overall server throughput. + +
+size
number
setMaxSendFragment(size) =>
setNoDelay
(noDelay) – Enable/disable the use of Nagle's algorithm.
+ +When a TCP connection is created, it will have Nagle's algorithm enabled. + +Nagle's algorithm delays data before it is sent via the network. It attempts +to optimize throughput at the expense of latency. + +Passing `true` for `noDelay` or not passing an argument will disable Nagle's +algorithm for the socket. Passing `false` for `noDelay` will enable Nagle's +algorithm. + +
+noDelay
boolean
setNoDelay(noDelay) =>
setTimeout
(timeout, callback) – Sets the socket to timeout after timeout
milliseconds of inactivity on
+the socket. By default net.Socket
do not have a timeout.
+ +When an idle timeout is triggered the socket will receive a `'timeout'` event but the connection will not be severed. The user must manually call `socket.end()` or `socket.destroy()` to +end the connection. + +```js +socket.setTimeout(3000) +socket.on('timeout', () => { + console.log('socket timeout') + socket.end() +}) +``` + +If `timeout` is 0, then the existing idle timeout is disabled. + +The optional `callback` parameter will be added as a one-time listener for the `'timeout'` event. + +
+timeout
number
callback
()
callback() =>
setTimeout(timeout, callback) =>
uncork
()
uncork() =>
unpipe
(destination) – The readable.unpipe()
method detaches a Writable
stream previously attached
+using the {@link pipe} method.
+ +If the `destination` is not specified, then _all_ pipes are detached. + +If the `destination` is specified, but no pipe is set up for it, then +the method does nothing. + +```js +const fs = require('fs') +const readable = getReadableStreamSomehow() +const writable = fs.createWriteStream('file.txt') +// All the data from readable goes into 'file.txt', +// but only for the first second. +readable.pipe(writable) +setTimeout(() => { + console.log('Stop writing to file.txt.') + readable.unpipe(writable) + console.log('Manually close the file stream.') + writable.end() +}, 1000) +``` + +
+destination
– Optional specific stream to unpipe
+unpipe(destination) =>
unref
() – Calling unref()
on a socket will allow the program to exit if this is the only
+active socket in the event system. If the socket is already unref
ed callingunref()
again will have no effect.
unref() =>
unshift
(chunk, encoding) – Passing chunk
as null
signals the end of the stream (EOF) and behaves the
+same as readable.push(null)
, after which no more data can be written. The EOF
+signal is put at the end of the buffer and any buffered data will still be
+flushed.
+ +The `readable.unshift()` method pushes a chunk of data back into the internal +buffer. This is useful in certain situations where a stream is being consumed by +code that needs to "un-consume" some amount of data that it has optimistically +pulled out of the source, so that the data can be passed on to some other party. + +The `stream.unshift(chunk)` method cannot be called after the `'end'` event +has been emitted or a runtime error will be thrown. + +Developers using `stream.unshift()` often should consider switching to +use of a `Transform` stream instead. See the `API for stream implementers` section for more information. + +```js +// Pull off a header delimited by \n\n. +// Use unshift() if we get too much. +// Call the callback with (error, header, stream). +const { StringDecoder } = require('string_decoder') +function parseHeader(stream, callback) { + stream.on('error', callback) + stream.on('readable', onReadable) + const decoder = new StringDecoder('utf8') + let header = '' + function onReadable() { + let chunk + while (null !== (chunk = stream.read())) { + const str = decoder.write(chunk) + if (str.match(/\n\n/)) { + // Found the header boundary. + const split = str.split(/\n\n/) + header += split.shift() + const remaining = split.join('\n\n') + const buf = Buffer.from(remaining, 'utf8') + stream.removeListener('error', callback) + // Remove the 'readable' listener before unshifting. + stream.removeListener('readable', onReadable) + if (buf.length) + stream.unshift(buf) + // Now the body of the message can be read from the stream. + callback(null, header, stream) + } else { + // Still reading the header. + header += str + } + } + } +} +``` + +Unlike {@link push}, `stream.unshift(chunk)` will not +end the reading process by resetting the internal reading state of the stream. +This can cause unexpected results if `readable.unshift()` is called during a +read (i.e. from within a {@link _read} implementation on a +custom stream). Following the call to `readable.unshift()` with an immediate {@link push} will reset the reading state appropriately, +however it is best to simply avoid calling `readable.unshift()` while in the +process of performing a read. + +
+chunk
– Chunk of data to unshift onto the read queue. For streams not operating in object mode, chunk
must be a string, Buffer
, Uint8Array
or null
. For object mode
+streams, chunk
may be any JavaScript value.any
encoding
– Encoding of string chunks. Must be a valid Buffer
encoding, such as 'utf8'
or 'ascii'
.
+unshift(chunk, encoding) =>
wrap
(stream) – Prior to Node.js 0.10, streams did not implement the entire stream
module API
+as it is currently defined. (See Compatibility
for more information.)
+ +When using an older Node.js library that emits `'data'` events and has a {@link pause} method that is advisory only, the`readable.wrap()` method can be used to create a `Readable` +stream that uses +the old stream as its data source. + +It will rarely be necessary to use `readable.wrap()` but the method has been +provided as a convenience for interacting with older Node.js applications and +libraries. + +```js +const { OldReader } = require('./old-api-module.js') +const { Readable } = require('stream') +const oreader = new OldReader() +const myReader = new Readable().wrap(oreader) + +myReader.on('readable', () => { + myReader.read() // etc. +}) +``` + +
+stream
– An "old style" readable stream
+wrap(stream) =>
write
(buffer, cb) – Sends data on the socket. The second parameter specifies the encoding in the
+case of a string. It defaults to UTF8 encoding.
+ +Returns `true` if the entire data was flushed successfully to the kernel +buffer. Returns `false` if all or part of the data was queued in user memory.`'drain'` will be emitted when the buffer is again free. + +The optional `callback` parameter will be executed when the data is finally +written out, which may not be immediately. + +See `Writable` stream `write()` method for more +information. + +
+buffer
string | Uint8Array
cb
(err) Error#
err
cb(err) =>
write(buffer, cb) =>
str
string | Uint8Array
encoding
cb
(err) Error#
err
cb(err) =>
write(str, encoding, cb) =>
from
(src) – A utility method for creating duplex streams.
+ +- `Stream` converts writable stream into writable `Duplex` and readable stream + to `Duplex`. +- `Blob` converts into readable `Duplex`. +- `string` converts into readable `Duplex`. +- `ArrayBuffer` converts into readable `Duplex`. +- `AsyncIterable` converts into a readable `Duplex`. Cannot yield `null`. +- `AsyncGeneratorFunction` converts into a readable/writable transform + `Duplex`. Must take a source `AsyncIterable` as first parameter. Cannot yield + `null`. +- `AsyncFunction` converts into a writable `Duplex`. Must return + either `null` or `undefined` +- `Object ({ writable, readable })` converts `readable` and + `writable` into `Stream` and then combines them into `Duplex` where the + `Duplex` will write to the `writable` and read from the `readable`. +- `Promise` converts into readable `Duplex`. Value `null` is ignored. + +
+src
string | Object | Stream | Iterable<any> | AsyncIterable<any> | Blob | ArrayBuffer | AsyncGeneratorFunction | Promise<any>
from(src) =>
getEventListeners
(emitter, name) – Returns a copy of the array of listeners for the event named eventName
.
+ +For `EventEmitter`s this behaves exactly the same as calling `.listeners` on +the emitter. + +For `EventTarget`s this is the only way to get the event listeners for the +event target. This is useful for debugging and diagnostic purposes. + +```js +const { getEventListeners, EventEmitter } = require('events') + +{ + const ee = new EventEmitter() + const listener = () => console.log('Events are fun') + ee.on('foo', listener) + getEventListeners(ee, 'foo') // [listener] +} +{ + const et = new EventTarget() + const listener = () => console.log('Events are fun') + et.addEventListener('foo', listener) + getEventListeners(et, 'foo') // [listener] +} +``` + +
+emitter
name
string | symbol
getEventListeners(emitter, name) =>
isDisturbed
(stream) – Returns whether the stream has been read from or cancelled. #
stream
isDisturbed(stream) =>
listenerCount
(emitter, eventName) – A class method that returns the number of listeners for the given eventName
registered on the given emitter
.
+ +```js +const { EventEmitter, listenerCount } = require('events') +const myEmitter = new EventEmitter() +myEmitter.on('event', () => {}) +myEmitter.on('event', () => {}) +console.log(listenerCount(myEmitter, 'event')) +// Prints: 2 +``` + +
+emitter
– The emitter to queryeventName
– The event name
+string | symbol
listenerCount(emitter, eventName) =>
on
(emitter, eventName, options) – ```js
+const { on, EventEmitter } = require('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: + +```js +const { on, EventEmitter } = require('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()); +```` + +
+emitter
eventName
– The name of the event being listened forstring
options
on(emitter, eventName, options) =>
once
(emitter, eventName, options) – 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](https://dom.spec.whatwg.org/#interface-eventtarget) interface, which has no special`'error'` event +semantics and does not listen to the `'error'` event. + +```js +const { once, EventEmitter } = require('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.log('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: + +```js +const { EventEmitter, once } = require('events') + +const ee = new EventEmitter() + +once(ee, 'error') + .then(([err]) => console.log('ok', err.message)) + .catch(err => console.log('error', err.message)) + +ee.emit('error', new Error('boom')) + +// Prints: ok boom +``` + +An `AbortSignal` can be used to cancel waiting for the event: + +```js +const { EventEmitter, once } = require('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() // Abort waiting for the event +ee.emit('foo') // Prints: Waiting for the event was canceled! +``` + +
+emitter
eventName
string | symbol
options
once(emitter, eventName, options) =>
emitter
eventName
string
options
once(emitter, eventName, options) =>
setMaxListeners
(n, eventTargets) – By default EventEmitter
s 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 EventEmitter.setMaxListeners()
method allows the default limit to be
+modified (if eventTargets is empty) or modify the limit specified in every EventTarget
| EventEmitter
passed as arguments.
+The value can be set toInfinity
(or 0
) to indicate an unlimited number of listeners.
+ +```js +EventEmitter.setMaxListeners(20) +// Equivalent to +EventEmitter.defaultMaxListeners = 20 + +const eventTarget = new EventTarget() +// Only way to increase limit for `EventTarget` instances +// as these doesn't expose its own `setMaxListeners` method +EventEmitter.setMaxListeners(20, eventTarget) +``` + +
+n
number
eventTargets
setMaxListeners(n, eventTargets) =>
URL
– Browser-compatible URL
class, implemented by following the WHATWG URL
+Standard. Examples of parsed URLs may be found in the Standard itself.
+The URL
class is also available on the global object.+ +In accordance with browser conventions, all properties of `URL` objects +are implemented as getters and setters on the class prototype, rather than as +data properties on the object itself. Thus, unlike `legacy urlObject` s, +using the `delete` keyword on any properties of `URL` objects (e.g. `delete myURL.protocol`, `delete myURL.pathname`, etc) has no effect but will still +return `true`. + +
+ string
+
+```js
+const myURL = new URL('https://example.org/foo#bar')
+console.log(myURL.hash)
+// Prints #bar
+
+myURL.hash = 'baz'
+console.log(myURL.href)
+// Prints https://example.org/foo#baz
+```
+
+Invalid URL characters included in the value assigned to the `hash` property
+are `percent-encoded`. The selection of which characters to
+percent-encode may vary somewhat from what the {@link parse} and {@link format} methods would produce.
+
+ string
+
+```js
+const myURL = new URL('https://example.org:81/foo')
+console.log(myURL.host)
+// Prints example.org:81
+
+myURL.host = 'example.com:82'
+console.log(myURL.href)
+// Prints https://example.com:82/foo
+```
+
+Invalid host values assigned to the `host` property are ignored.
+
+ string
+
+```js
+const myURL = new URL('https://example.org:81/foo')
+console.log(myURL.hostname)
+// Prints example.org
+
+// Setting the hostname does not change the port
+myURL.hostname = 'example.com:82'
+console.log(myURL.href)
+// Prints https://example.com:81/foo
+
+// Use myURL.host to change the hostname and port
+myURL.host = 'example.org:82'
+console.log(myURL.href)
+// Prints https://example.org:82/foo
+```
+
+Invalid host name values assigned to the `hostname` property are ignored.
+
+ string
+
+```js
+const myURL = new URL('https://example.org/foo')
+console.log(myURL.href)
+// Prints https://example.org/foo
+
+myURL.href = 'https://example.com/bar'
+console.log(myURL.href)
+// Prints https://example.com/bar
+```
+
+Getting the value of the `href` property is equivalent to calling {@link toString}.
+
+Setting the value of this property to a new value is equivalent to creating a
+new `URL` object using `new URL(value)`. Each of the `URL`object's properties will be modified.
+
+If the value assigned to the `href` property is not a valid URL, a `TypeError`will be thrown.
+
+ string
+
+```js
+const myURL = new URL('https://example.org/foo/bar?baz')
+console.log(myURL.origin)
+// Prints https://example.org
+```
+
+```js
+const idnURL = new URL('https://測試')
+console.log(idnURL.origin)
+// Prints https://xn--g6w251d
+
+console.log(idnURL.hostname)
+// Prints xn--g6w251d
+```
+
+ string
+
+```js
+const myURL = new URL('https://abc:xyz@example.com')
+console.log(myURL.password)
+// Prints xyz
+
+myURL.password = '123'
+console.log(myURL.href)
+// Prints https://abc:123@example.com
+```
+
+Invalid URL characters included in the value assigned to the `password` property
+are `percent-encoded`. The selection of which characters to
+percent-encode may vary somewhat from what the {@link parse} and {@link format} methods would produce.
+
+ string
+
+```js
+const myURL = new URL('https://example.org/abc/xyz?123')
+console.log(myURL.pathname)
+// Prints /abc/xyz
+
+myURL.pathname = '/abcdef'
+console.log(myURL.href)
+// Prints https://example.org/abcdef?123
+```
+
+Invalid URL characters included in the value assigned to the `pathname`property are `percent-encoded`. The selection of which characters
+to percent-encode may vary somewhat from what the {@link parse} and {@link format} methods would produce.
+
+ string
+
+The port value may be a number or a string containing a number in the range`0` to `65535` (inclusive). Setting the value to the default port of the`URL` objects given `protocol` will
+result in the `port` value becoming
+the empty string (`''`).
+
+The port value can be an empty string in which case the port depends on
+the protocol/scheme:
+
+ string
+
+```js
+const myURL = new URL('https://example.org')
+console.log(myURL.protocol)
+// Prints https:
+
+myURL.protocol = 'ftp'
+console.log(myURL.href)
+// Prints ftp://example.org/
+```
+
+Invalid URL protocol values assigned to the `protocol` property are ignored.
+
+ string
+
+```js
+const myURL = new URL('https://example.org/abc?123')
+console.log(myURL.search)
+// Prints ?123
+
+myURL.search = 'abc=xyz'
+console.log(myURL.href)
+// Prints https://example.org/abc?abc=xyz
+```
+
+Any invalid URL characters appearing in the value assigned the `search`property will be `percent-encoded`. The selection of which
+characters to percent-encode may vary somewhat from what the {@link parse} and {@link format} methods would produce.
+
+
+
+Use care when using `.searchParams` to modify the `URL` because,
+per the WHATWG specification, the `URLSearchParams` object uses
+different rules to determine which characters to percent-encode. For
+instance, the `URL` object will not percent encode the ASCII tilde (`~`)
+character, while `URLSearchParams` will always encode it:
+
+```js
+const myUrl = new URL('https://example.org/abc?foo=~bar')
+
+console.log(myUrl.search) // prints ?foo=~bar
+
+// Modify the URL via searchParams...
+myUrl.searchParams.sort()
+
+console.log(myUrl.search) // prints ?foo=%7Ebar
+```
+
+ string
+
+```js
+const myURL = new URL('https://abc:xyz@example.com')
+console.log(myURL.username)
+// Prints abc
+
+myURL.username = '123'
+console.log(myURL.href)
+// Prints https://123:xyz@example.com/
+```
+
+Any invalid URL characters appearing in the value assigned the `username`property will be `percent-encoded`. The selection of which
+characters to percent-encode may vary somewhat from what the {@link parse} and {@link format} methods would produce.
+
+
+
+This method is automatically called when an `URL` object is serialized
+with [`JSON.stringify()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify).
+
+```js
+const myURLs = [
+ new URL('https://www.example.com'),
+ new URL('https://test.example.org'),
+]
+console.log(JSON.stringify(myURLs))
+// Prints ["https://www.example.com/","https://test.example.org/"]
+```
+
+ toJSON() => #
src/.fastpm/-/@types/node@17.0.45/url.d.ts#L420 hash
– Gets and sets the fragment portion of the URL.#
src/.fastpm/-/@types/node@17.0.45/url.d.ts#L436 host
– Gets and sets the host portion of the URL.#
src/.fastpm/-/@types/node@17.0.45/url.d.ts#L459 hostname
– Gets and sets the host name portion of the URL. The key difference betweenurl.host
and url.hostname
is that url.hostname
does not include the
+port.#
src/.fastpm/-/@types/node@17.0.45/url.d.ts#L480 href
– Gets and sets the serialized URL.#
src/.fastpm/-/@types/node@17.0.45/url.d.ts#L499 origin
– Gets the read-only serialization of the URL's origin.#
src/.fastpm/-/@types/node@17.0.45/url.d.ts#L517 password
– Gets and sets the password portion of the URL.#
src/.fastpm/-/@types/node@17.0.45/url.d.ts#L534 pathname
– Gets and sets the path portion of the URL.#
src/.fastpm/-/@types/node@17.0.45/url.d.ts#L607 port
– Gets and sets the port portion of the URL.#
src/.fastpm/-/@types/node@17.0.45/url.d.ts#L623 protocol
– Gets and sets the protocol portion of the URL.#
src/.fastpm/-/@types/node@17.0.45/url.d.ts#L640 search
– Gets and sets the serialized query portion of the URL.#
src/.fastpm/-/@types/node@17.0.45/url.d.ts#L664 searchParams
– Gets the URLSearchParams
object representing the query parameters of the
+URL. This property is read-only but the URLSearchParams
object it provides
+can be used to mutate the URL instance; to replace the entirety of query
+parameters of the URL, use the {@link search} setter. See URLSearchParams
documentation for details.
#
src/.fastpm/-/@types/node@17.0.45/url.d.ts#L681 username
– Gets and sets the username portion of the URL.#
src/.fastpm/-/@types/node@17.0.45/url.d.ts#L703 toJSON
() – The toJSON()
method on the URL
object returns the serialized URL. The
+value returned is equivalent to that of {@link href} and {@link toString}.
string
toString
() – The toString()
method on the URL
object returns the serialized URL. The
+value returned is equivalent to that of {@link href} and {@link toJSON}.
toString() =>
createObjectURL
(blob) – Creates a 'blob:nodedata:...'
URL string that represents the given Blob
object and can be used to retrieve the Blob
later.
+ +```js +const { + Blob, + resolveObjectURL, +} = require('buffer') + +const blob = new Blob(['hello']) +const id = URL.createObjectURL(blob) + +// later... + +const otherBlob = resolveObjectURL(id) +console.log(otherBlob.size) +``` + +The data stored by the registered `Blob` will be retained in memory until`URL.revokeObjectURL()` is called to remove it. + +`Blob` objects are registered within the current thread. If using Worker +Threads, `Blob` objects registered within one Worker will not be available +to other workers or the main thread. + +
+blob
createObjectURL(blob) =>
revokeObjectURL
(objectUrl) – Removes the stored Blob
identified by the given ID. string#
objectUrl
revokeObjectURL(objectUrl) =>
URLSearchParams
– The URLSearchParams
API provides read and write access to the query of aURL
. The URLSearchParams
class can also be used standalone with one of the
+four following constructors.
+The URLSearchParams
class is also available on the global object.+ +The WHATWG `URLSearchParams` interface and the `querystring` module have +similar purpose, but the purpose of the `querystring` module is more +general, as it allows the customization of delimiter characters (`&` and `=`). +On the other hand, this API is designed purely for URL query strings. + +```js +const myURL = new URL('https://example.org/?abc=123') +console.log(myURL.searchParams.get('abc')) +// Prints 123 + +myURL.searchParams.append('abc', 'xyz') +console.log(myURL.href) +// Prints https://example.org/?abc=123&abc=xyz + +myURL.searchParams.delete('abc') +myURL.searchParams.set('a', 'b') +console.log(myURL.href) +// Prints https://example.org/?a=b + +const newSearchParams = new URLSearchParams(myURL.searchParams) +// The above is equivalent to +// const newSearchParams = new URLSearchParams(myURL.search); + +newSearchParams.append('a', 'c') +console.log(myURL.href) +// Prints https://example.org/?a=b +console.log(newSearchParams.toString()) +// Prints a=b&a=c + +// newSearchParams.toString() is implicitly called +myURL.search = newSearchParams +console.log(myURL.href) +// Prints https://example.org/?a=b&a=c +newSearchParams.delete('a') +console.log(myURL.href) +// Prints https://example.org/?a=b&a=c +``` + +
+ string | readonly [ string, string ] [] | URLSearchParams | Record<string, string | readonly string []> | Iterable<[ string, string ]> [iterator]() => #
src/.fastpm/-/@types/node@17.0.45/url.d.ts#L750 constructor
(init)
#
new URLSearchParams
()
#
init
#
src/.fastpm/-/@types/node@17.0.45/url.d.ts#L856 [iterator]
()
IterableIterator<[ string, string ]>
append
(name, value) – Append a new name-value pair to the query string.delete
(name) – Remove all name-value pairs whose name is name
. string#
name
delete(name) =>
entries
() – Returns an ES6 Iterator
over each of the name-value pairs in the query.
+Each item of the iterator is a JavaScript Array
. The first item of the Array
is the name
, the second item of the Array
is the value
.
+ +Alias for `urlSearchParams[@@iterator]()`. + +
+entries() =>
forEach
(callback, thisArg) – Iterates over each name-value pair in the query and invokes the given function.
+ +```js +const myURL = new URL('https://example.org/?a=b&c=d') +myURL.searchParams.forEach((value, name, searchParams) => { + console.log(name, value, myURL.searchParams === searchParams) +}) +// Prints: +// a b true +// c d true +``` + +
+callback
(this, value, name, searchParams) thisArg
– To be used as this
value for when fn
is called
+forEach<TThis>(callback, thisArg) =>
get
(name) – Returns the value of the first name-value pair whose name is name
. If there
+are no such pairs, null
is returned. string#
name
get(name) =>
null
| stringgetAll
(name) – Returns the values of all name-value pairs whose name is name
. If there are
+no such pairs, an empty array is returned. string#
name
getAll(name) =>
has
(name) – Returns true
if there is at least one name-value pair whose name is name
. string#
name
has(name) =>
keys
() – Returns an ES6 Iterator
over the names of each name-value pair.
+ +```js +const params = new URLSearchParams('foo=bar&foo=baz') +for (const name of params.keys()) { + console.log(name) +} +// Prints: +// foo +// foo +``` + +
+keys() =>
set
(name, value) – Sets the value in the URLSearchParams
object associated with name
tovalue
. If there are any pre-existing name-value pairs whose names are name
,
+set the first such pair's value to value
and remove all others. If not,
+append the name-value pair to the query string.
+ +```js +const params = new URLSearchParams() +params.append('foo', 'bar') +params.append('foo', 'baz') +params.append('abc', 'def') +console.log(params.toString()) +// Prints foo=bar&foo=baz&abc=def + +params.set('foo', 'def') +params.set('xyz', 'opq') +console.log(params.toString()) +// Prints foo=def&abc=def&xyz=opq +``` + +
+name
string
value
string
set(name, value) =>
sort
() – Sort all existing name-value pairs in-place by their names. Sorting is done
+with a stable sorting algorithm, so relative order between name-value pairs
+with the same name is preserved.
+ +This method can be used, in particular, to increase cache hits. + +```js +const params = new URLSearchParams( + 'query[]=abc&type=search&query[]=123' +) +params.sort() +console.log(params.toString()) +// Prints query%5B%5D=abc&query%5B%5D=123&type=search +``` + +
+sort() =>
toString
() – Returns the search parameters serialized as a string, with characters
+percent-encoded where necessary.
toString() =>
values
() – Returns an ES6 Iterator
over the values of each name-value pair.
values() =>
WebSocket_2
boolean#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L2652 constructor
(address)
#
new WebSocket_2
()
#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L2643 CLOSING
– The connection is in the process of closing.2
#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L2639 CONNECTING
– The connection is not yet open.0
#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L2641 OPEN
– The connection is open and ready to communicate.1
#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L2624 binaryType
"nodebuffer"
| "arraybuffer"
| "fragments"
#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L2628 isPaused
– Indicates whether the websocket is paused
onerror
onmessage
onopen
null
|
protocol
string
readyState
– The current state of the connection0
| 1
| 2
| 3
url
string
CLOSED
– The connection is closed.3
CLOSING
– The connection is in the process of closing.2
CONNECTING
– The connection is not yet open.0
OPEN
– The connection is open and ready to communicate.1
captureRejectionSymbol
typeof captureRejectionSymbol
captureRejections
– Sets or gets the default captureRejection value for all emitters.boolean
defaultMaxListeners
number
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.typeof errorMonitor
+ +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. + +
+addEventListener
(method, cb, options) options
addEventListener(method, cb, options) =>
method
"close"
cb
(event) #
event
cb(event) =>
options
addEventListener(method, cb, options) =>
method
"error"
cb
(event) #
event
cb(event) =>
options
addEventListener(method, cb, options) =>
method
"open"
options
addEventListener(method, cb, options) =>
addListener
(event, listener) – Alias for emitter.on(eventName, listener)
. #
event
"close"
addListener(event, listener) =>
event
"error"
listener
(err) Error#
err
listener(err) =>
addListener(event, listener) =>
event
"upgrade"
listener
(request) #
request
listener(request) =>
addListener(event, listener) =>
event
"message"
addListener(event, listener) =>
event
"open"
listener
()
listener() =>
addListener(event, listener) =>
event
"ping"
| "pong"
addListener(event, listener) =>
event
"unexpected-response"
listener
(request, response) listener(request, response) =>
addListener(event, listener) =>
event
string | symbol
listener
(args) any []#
args
listener(args) =>
addListener(event, listener) =>
close
(code, data) number#
code
close(code, data) =>
emit
(eventName, args) – Synchronously calls each of the listeners registered for the event namedeventName
, in the order they were registered, passing the supplied arguments
+to each.
+ +Returns `true` if the event had listeners, `false` otherwise. + +```js +const EventEmitter = require('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 +``` + +
+eventName
string | symbol
args
any []
emit(eventName, args) =>
eventNames
() – Returns an array listing the events for which the emitter has registered
+listeners. The values in the array are strings or Symbol
s.
+ +```js +const EventEmitter = require('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) ] +``` + +
+eventNames() =>
getMaxListeners
() – Returns the current max listener value for the EventEmitter
which is either
+set by emitter.setMaxListeners(n)
or defaults to {@link defaultMaxListeners}.
getMaxListeners() =>
listenerCount
(eventName) – Returns the number of listeners listening to the event named eventName
. string | symbol#
eventName
– The name of the event being listened for
+
listenerCount(eventName) =>
listeners
(eventName) – Returns a copy of the array of listeners for the event named eventName
.
+ +```js +server.on('connection', stream => { + console.log('someone connected!') +}) +console.log(util.inspect(server.listeners('connection'))) +// Prints: [ [Function] ] +``` + +
+eventName
string | symbol
listeners(eventName) =>
off
(event, listener) – Alias for emitter.removeListener()
. #
event
"close"
off(event, listener) =>
event
"error"
listener
(this, err) listener(this, err) =>
off(event, listener) =>
event
"upgrade"
listener
(this, request) listener(this, request) =>
off(event, listener) =>
event
"message"
listener
(this, data, isBinary) listener(this, data, isBinary) =>
off(event, listener) =>
event
"open"
listener
(this) #
this
listener(this) =>
off(event, listener) =>
event
"ping"
| "pong"
listener
(this, data) #
this
listener(this, data) =>
off(event, listener) =>
event
"unexpected-response"
listener
(this, request, response) listener(this, request, response) =>
off(event, listener) =>
event
string | symbol
listener
(this, args) listener(this, args) =>
off(event, listener) =>
on
(event, listener) – 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.
+ +```js +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. + +```js +const myEE = new EventEmitter() +myEE.on('foo', () => console.log('a')) +myEE.prependListener('foo', () => console.log('b')) +myEE.emit('foo') +// Prints: +// b +// a +``` + +
+event
"close"
listener
(this, code, reason) listener(this, code, reason) =>
on(event, listener) =>
event
"error"
listener
(this, err) listener(this, err) =>
on(event, listener) =>
event
"upgrade"
listener
(this, request) listener(this, request) =>
on(event, listener) =>
event
"message"
listener
(this, data, isBinary) listener(this, data, isBinary) =>
on(event, listener) =>
event
"open"
listener
(this) #
this
listener(this) =>
on(event, listener) =>
event
"ping"
| "pong"
listener
(this, data) #
this
listener(this, data) =>
on(event, listener) =>
event
"unexpected-response"
listener
(this, request, response) listener(this, request, response) =>
on(event, listener) =>
event
string | symbol
listener
(this, args) listener(this, args) =>
on(event, listener) =>
once
(event, listener) – Adds a one-timelistener
function for the event named eventName
. The
+next time eventName
is triggered, this listener is removed and then invoked.
+ +```js +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. + +```js +const myEE = new EventEmitter() +myEE.once('foo', () => console.log('a')) +myEE.prependOnceListener('foo', () => console.log('b')) +myEE.emit('foo') +// Prints: +// b +// a +``` + +
+event
"close"
listener
(this, code, reason) listener(this, code, reason) =>
once(event, listener) =>
event
"error"
listener
(this, err) listener(this, err) =>
once(event, listener) =>
event
"upgrade"
listener
(this, request) listener(this, request) =>
once(event, listener) =>
event
"message"
listener
(this, data, isBinary) listener(this, data, isBinary) =>
once(event, listener) =>
event
"open"
listener
(this) #
this
listener(this) =>
once(event, listener) =>
event
"ping"
| "pong"
listener
(this, data) #
this
listener(this, data) =>
once(event, listener) =>
event
"unexpected-response"
listener
(this, request, response) listener(this, request, response) =>
once(event, listener) =>
event
string | symbol
listener
(this, args) listener(this, args) =>
once(event, listener) =>
pause
() – Pause the websocket causing it to stop emitting events. Some events can still be
+emitted after this is called, until all buffered data is consumed. This method
+is a noop if the ready state is CONNECTING
or CLOSED
.
pause() =>
ping
(data, mask, cb) ping(data, mask, cb) =>
pong
(data, mask, cb) pong(data, mask, cb) =>
prependListener
(eventName, listener) – 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.
+ +```js +server.prependListener('connection', stream => { + console.log('someone connected!') +}) +``` + +Returns a reference to the `EventEmitter`, so that calls can be chained. + +
+eventName
– The name of the event.string | symbol
listener
(args) any []#
args
listener(args) =>
prependListener(eventName, listener) =>
prependOnceListener
(eventName, listener) – Adds a one-timelistener
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.
+ +```js +server.prependOnceListener('connection', stream => { + console.log('Ah, we have our first user!') +}) +``` + +Returns a reference to the `EventEmitter`, so that calls can be chained. + +
+eventName
– The name of the event.string | symbol
listener
(args) any []#
args
listener(args) =>
prependOnceListener(eventName, listener) =>
rawListeners
(eventName) – Returns a copy of the array of listeners for the event named eventName
,
+including any wrappers (such as those created by .once()
).
+ +```js +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') +``` + +
+eventName
string | symbol
rawListeners(eventName) =>
removeAllListeners
(event) – 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. + +
+event
string | symbol
removeAllListeners(event) =>
removeEventListener
(method, cb) removeEventListener(method, cb) =>
method
"close"
cb
(event) #
event
cb(event) =>
removeEventListener(method, cb) =>
method
"error"
cb
(event) #
event
cb(event) =>
removeEventListener(method, cb) =>
method
"open"
removeEventListener(method, cb) =>
removeListener
(event, listener) – Removes the specified listener
from the listener array for the event namedeventName
.
+ +```js +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. + +```js +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 indices 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: + +```js +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. + +
+event
"close"
removeListener(event, listener) =>
event
"error"
listener
(err) Error#
err
listener(err) =>
removeListener(event, listener) =>
event
"upgrade"
listener
(request) #
request
listener(request) =>
removeListener(event, listener) =>
event
"message"
removeListener(event, listener) =>
event
"open"
listener
()
listener() =>
removeListener(event, listener) =>
event
"ping"
| "pong"
removeListener(event, listener) =>
event
"unexpected-response"
listener
(request, response) listener(request, response) =>
removeListener(event, listener) =>
event
string | symbol
listener
(args) any []#
args
listener(args) =>
removeListener(event, listener) =>
resume
() – Make a paused socket resume emitting events. This method is a noop if the ready
+state is CONNECTING
or CLOSED
.
resume() =>
send
(data, cb) any#
data
send(data, cb) =>
data
any
options
{
}
cb
(err) Error#
err
cb(err) =>
send(data, { binary, compress, fin, mask }, cb) =>
setMaxListeners
(n) – By default EventEmitter
s 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 toInfinity
(or 0
) to indicate an unlimited number of listeners.
+ +Returns a reference to the `EventEmitter`, so that calls can be chained. + +
+n
number
setMaxListeners(n) =>
terminate
()
terminate() =>
getEventListeners
(emitter, name) – Returns a copy of the array of listeners for the event named eventName
.
+ +For `EventEmitter`s this behaves exactly the same as calling `.listeners` on +the emitter. + +For `EventTarget`s this is the only way to get the event listeners for the +event target. This is useful for debugging and diagnostic purposes. + +```js +const { getEventListeners, EventEmitter } = require('events') + +{ + const ee = new EventEmitter() + const listener = () => console.log('Events are fun') + ee.on('foo', listener) + getEventListeners(ee, 'foo') // [listener] +} +{ + const et = new EventTarget() + const listener = () => console.log('Events are fun') + et.addEventListener('foo', listener) + getEventListeners(et, 'foo') // [listener] +} +``` + +
+emitter
name
string | symbol
getEventListeners(emitter, name) =>
listenerCount
(emitter, eventName) – A class method that returns the number of listeners for the given eventName
registered on the given emitter
.
+ +```js +const { EventEmitter, listenerCount } = require('events') +const myEmitter = new EventEmitter() +myEmitter.on('event', () => {}) +myEmitter.on('event', () => {}) +console.log(listenerCount(myEmitter, 'event')) +// Prints: 2 +``` + +
+emitter
– The emitter to queryeventName
– The event name
+string | symbol
listenerCount(emitter, eventName) =>
on
(emitter, eventName, options) – ```js
+const { on, EventEmitter } = require('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: + +```js +const { on, EventEmitter } = require('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()); +```` + +
+emitter
eventName
– The name of the event being listened forstring
options
on(emitter, eventName, options) =>
once
(emitter, eventName, options) – 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](https://dom.spec.whatwg.org/#interface-eventtarget) interface, which has no special`'error'` event +semantics and does not listen to the `'error'` event. + +```js +const { once, EventEmitter } = require('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.log('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: + +```js +const { EventEmitter, once } = require('events') + +const ee = new EventEmitter() + +once(ee, 'error') + .then(([err]) => console.log('ok', err.message)) + .catch(err => console.log('error', err.message)) + +ee.emit('error', new Error('boom')) + +// Prints: ok boom +``` + +An `AbortSignal` can be used to cancel waiting for the event: + +```js +const { EventEmitter, once } = require('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() // Abort waiting for the event +ee.emit('foo') // Prints: Waiting for the event was canceled! +``` + +
+emitter
eventName
string | symbol
options
once(emitter, eventName, options) =>
emitter
eventName
string
options
once(emitter, eventName, options) =>
setMaxListeners
(n, eventTargets) – By default EventEmitter
s 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 EventEmitter.setMaxListeners()
method allows the default limit to be
+modified (if eventTargets is empty) or modify the limit specified in every EventTarget
| EventEmitter
passed as arguments.
+The value can be set toInfinity
(or 0
) to indicate an unlimited number of listeners.
+ +```js +EventEmitter.setMaxListeners(20) +// Equivalent to +EventEmitter.defaultMaxListeners = 20 + +const eventTarget = new EventTarget() +// Only way to increase limit for `EventTarget` instances +// as these doesn't expose its own `setMaxListeners` method +EventEmitter.setMaxListeners(20, eventTarget) +``` + +
+n
number
eventTargets
setMaxListeners(n, eventTargets) =>
Writable
boolean boolean number boolean boolean number number boolean typeof captureRejectionSymbol boolean typeof errorMonitor
+
+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.
+
+#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L543 destroyed
– Is true
after writable.destroy()
has been called.#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L504 writable
– Is true
if it is safe to call writable.write()
, which means
+the stream has not been destroyed, errored or ended.#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L538 writableCorked
– Number of times writable.uncork()
needs to be
+called in order to fully uncork the stream.#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L510 writableEnded
– Is true
after writable.end()
has been called. This property
+does not indicate whether the data has been flushed, for this use writable.writableFinished
instead.#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L515 writableFinished
– Is set to true
immediately before the 'finish'
event is emitted.#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L520 writableHighWaterMark
– Return the value of highWaterMark
passed when creating this Writable
.#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L527 writableLength
– This property contains the number of bytes (or objects) in the queue
+ready to be written. The value provides introspection data regarding
+the status of the highWaterMark
.#
src/.fastpm/-/@types/node@17.0.45/stream.d.ts#L532 writableObjectMode
– Getter for the property objectMode
of a given Writable
stream.#
src/.fastpm/-/@types/node@17.0.45/events.d.ts#L301 captureRejectionSymbol
#
src/.fastpm/-/@types/node@17.0.45/events.d.ts#L306 captureRejections
– Sets or gets the default captureRejection value for all emitters.#
src/.fastpm/-/@types/node@17.0.45/events.d.ts#L300 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.
_construct(callback) =>
_destroy
(error, callback) #
error
null
| Error
_destroy(error, callback) =>
_final
(callback)
_final(callback) =>
_write
(chunk, encoding, callback) _write(chunk, encoding, callback) =>
_writev
(chunks, callback) { #
chunks
callback
(error) #
error
null
| Error
callback(error) =>
_writev(chunks, callback) =>
addListener
(event, listener) – Event emitter
+The defined events on documents including:
+1. close
+2. drain
+3. error
+4. finish
+5. pipe
+6. unpipeaddListener(event, listener) =>
event
"drain"
listener
()
listener() =>
addListener(event, listener) =>
event
"error"
listener
(err) Error#
err
listener(err) =>
addListener(event, listener) =>
event
"finish"
listener
()
listener() =>
addListener(event, listener) =>
event
"pipe"
addListener(event, listener) =>
event
"unpipe"
addListener(event, listener) =>
event
string | symbol
listener
(args) any []#
args
listener(args) =>
addListener(event, listener) =>
cork
() – The writable.cork()
method forces all written data to be buffered in memory.
+The buffered data will be flushed when either the {@link uncork} or {@link end} methods are called.
+ +The primary intent of `writable.cork()` is to accommodate a situation in which +several small chunks are written to the stream in rapid succession. Instead of +immediately forwarding them to the underlying destination, `writable.cork()`buffers all the chunks until `writable.uncork()` is called, which will pass them +all to `writable._writev()`, if present. This prevents a head-of-line blocking +situation where data is being buffered while waiting for the first small chunk +to be processed. However, use of `writable.cork()` without implementing`writable._writev()` may have an adverse effect on throughput. + +See also: `writable.uncork()`, `writable._writev()`. + +
+cork() =>
destroy
(error) – Destroy the stream. Optionally emit an 'error'
event, and emit a 'close'
event (unless emitClose
is set to false
). After this call, the writable
+stream has ended and subsequent calls to write()
or end()
will result in
+an ERR_STREAM_DESTROYED
error.
+This is a destructive and immediate way to destroy a stream. Previous calls towrite()
may not have drained, and may trigger an ERR_STREAM_DESTROYED
error.
+Use end()
instead of destroy if data should flush before close, or wait for
+the 'drain'
event before destroying the stream.
+ +Once `destroy()` has been called any further calls will be a no-op and no +further errors except from `_destroy()` may be emitted as `'error'`. + +Implementors should not override this method, +but instead implement `writable._destroy()`. + +
+error
– Optional, an error to emit with 'error'
event.
+Error
destroy(error) =>
emit
(event) – Synchronously calls each of the listeners registered for the event namedeventName
, in the order they were registered, passing the supplied arguments
+to each.
+ +Returns `true` if the event had listeners, `false` otherwise. + +```js +const EventEmitter = require('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 +``` + +
+event
"close"
emit(event) =>
event
"drain"
emit(event) =>
event
"error"
err
Error
emit(event, err) =>
event
"finish"
emit(event) =>
event
"pipe"
src
emit(event, src) =>
event
"unpipe"
src
emit(event, src) =>
event
string | symbol
args
any []
emit(event, args) =>
end
(cb) – Calling the writable.end()
method signals that no more data will be written
+to the Writable
. The optional chunk
and encoding
arguments allow one
+final additional chunk of data to be written immediately before closing the
+stream.
+ +Calling the {@link write} method after calling {@link end} will raise an error. + +```js +// Write 'hello, ' and then end with 'world!'. +const fs = require('fs') +const file = fs.createWriteStream('example.txt') +file.write('hello, ') +file.end('world!') +// Writing more now is not allowed! +``` + +
+cb
()
cb() =>
end(cb) =>
chunk
any
cb
()
cb() =>
end(chunk, cb) =>
chunk
any
encoding
cb
()
cb() =>
end(chunk, encoding, cb) =>
eventNames
() – Returns an array listing the events for which the emitter has registered
+listeners. The values in the array are strings or Symbol
s.
+ +```js +const EventEmitter = require('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) ] +``` + +
+eventNames() =>
getMaxListeners
() – Returns the current max listener value for the EventEmitter
which is either
+set by emitter.setMaxListeners(n)
or defaults to {@link defaultMaxListeners}.
getMaxListeners() =>
listenerCount
(eventName) – Returns the number of listeners listening to the event named eventName
. string | symbol#
eventName
– The name of the event being listened for
+
listenerCount(eventName) =>
listeners
(eventName) – Returns a copy of the array of listeners for the event named eventName
.
+ +```js +server.on('connection', stream => { + console.log('someone connected!') +}) +console.log(util.inspect(server.listeners('connection'))) +// Prints: [ [Function] ] +``` + +
+eventName
string | symbol
listeners(eventName) =>
off
(eventName, listener) – Alias for emitter.removeListener()
. string | symbol#
eventName
off(eventName, listener) =>
on
(event, listener) – 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.
+ +```js +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. + +```js +const myEE = new EventEmitter() +myEE.on('foo', () => console.log('a')) +myEE.prependListener('foo', () => console.log('b')) +myEE.emit('foo') +// Prints: +// b +// a +``` + +
+event
"close"
listener
()
listener() =>
on(event, listener) =>
event
"drain"
listener
()
listener() =>
on(event, listener) =>
event
"error"
listener
(err) Error#
err
listener(err) =>
on(event, listener) =>
event
"finish"
listener
()
listener() =>
on(event, listener) =>
event
"pipe"
on(event, listener) =>
event
"unpipe"
on(event, listener) =>
event
string | symbol
listener
(args) any []#
args
listener(args) =>
on(event, listener) =>
once
(event, listener) – Adds a one-timelistener
function for the event named eventName
. The
+next time eventName
is triggered, this listener is removed and then invoked.
+ +```js +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. + +```js +const myEE = new EventEmitter() +myEE.once('foo', () => console.log('a')) +myEE.prependOnceListener('foo', () => console.log('b')) +myEE.emit('foo') +// Prints: +// b +// a +``` + +
+event
"close"
listener
()
listener() =>
once(event, listener) =>
event
"drain"
listener
()
listener() =>
once(event, listener) =>
event
"error"
listener
(err) Error#
err
listener(err) =>
once(event, listener) =>
event
"finish"
listener
()
listener() =>
once(event, listener) =>
event
"pipe"
once(event, listener) =>
event
"unpipe"
once(event, listener) =>
event
string | symbol
listener
(args) any []#
args
listener(args) =>
once(event, listener) =>
pipe
(destination, { end }) { #
options
pipe<T extends WritableStream<T>>(destination, { end }) =>
prependListener
(event, listener) – 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.
+ +```js +server.prependListener('connection', stream => { + console.log('someone connected!') +}) +``` + +Returns a reference to the `EventEmitter`, so that calls can be chained. + +
+event
"close"
listener
()
listener() =>
prependListener(event, listener) =>
event
"drain"
listener
()
listener() =>
prependListener(event, listener) =>
event
"error"
listener
(err) Error#
err
listener(err) =>
prependListener(event, listener) =>
event
"finish"
listener
()
listener() =>
prependListener(event, listener) =>
event
"pipe"
prependListener(event, listener) =>
event
"unpipe"
prependListener(event, listener) =>
event
string | symbol
listener
(args) any []#
args
listener(args) =>
prependListener(event, listener) =>
prependOnceListener
(event, listener) – Adds a one-timelistener
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.
+ +```js +server.prependOnceListener('connection', stream => { + console.log('Ah, we have our first user!') +}) +``` + +Returns a reference to the `EventEmitter`, so that calls can be chained. + +
+event
"close"
listener
()
listener() =>
prependOnceListener(event, listener) =>
event
"drain"
listener
()
listener() =>
prependOnceListener(event, listener) =>
event
"error"
listener
(err) Error#
err
listener(err) =>
prependOnceListener(event, listener) =>
event
"finish"
listener
()
listener() =>
prependOnceListener(event, listener) =>
event
"pipe"
prependOnceListener(event, listener) =>
event
"unpipe"
prependOnceListener(event, listener) =>
event
string | symbol
listener
(args) any []#
args
listener(args) =>
prependOnceListener(event, listener) =>
rawListeners
(eventName) – Returns a copy of the array of listeners for the event named eventName
,
+including any wrappers (such as those created by .once()
).
+ +```js +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') +``` + +
+eventName
string | symbol
rawListeners(eventName) =>
removeAllListeners
(event) – 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. + +
+event
string | symbol
removeAllListeners(event) =>
removeListener
(event, listener) – Removes the specified listener
from the listener array for the event namedeventName
.
+ +```js +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. + +```js +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 indices 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: + +```js +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. + +
+event
"close"
listener
()
listener() =>
removeListener(event, listener) =>
event
"drain"
listener
()
listener() =>
removeListener(event, listener) =>
event
"error"
listener
(err) Error#
err
listener(err) =>
removeListener(event, listener) =>
event
"finish"
listener
()
listener() =>
removeListener(event, listener) =>
event
"pipe"
removeListener(event, listener) =>
event
"unpipe"
removeListener(event, listener) =>
event
string | symbol
listener
(args) any []#
args
listener(args) =>
removeListener(event, listener) =>
setDefaultEncoding
(encoding) – The writable.setDefaultEncoding()
method sets the default encoding
for a Writable
stream. #
encoding
– The new default encoding
+
setDefaultEncoding(encoding) =>
setMaxListeners
(n) – By default EventEmitter
s 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 toInfinity
(or 0
) to indicate an unlimited number of listeners.
+ +Returns a reference to the `EventEmitter`, so that calls can be chained. + +
+n
number
setMaxListeners(n) =>
uncork
() – The writable.uncork()
method flushes all data buffered since {@link cork} was called.
+ +When using `writable.cork()` and `writable.uncork()` to manage the buffering +of writes to a stream, it is recommended that calls to `writable.uncork()` be +deferred using `process.nextTick()`. Doing so allows batching of all`writable.write()` calls that occur within a given Node.js event loop phase. + +```js +stream.cork() +stream.write('some ') +stream.write('data ') +process.nextTick(() => stream.uncork()) +``` + +If the `writable.cork()` method is called multiple times on a stream, the +same number of calls to `writable.uncork()` must be called to flush the buffered +data. + +```js +stream.cork() +stream.write('some ') +stream.cork() +stream.write('data ') +process.nextTick(() => { + stream.uncork() + // The data will not be flushed until uncork() is called a second time. + stream.uncork() +}) +``` + +See also: `writable.cork()`. + +
+uncork() =>
write
(chunk, callback) – The writable.write()
method writes some data to the stream, and calls the
+supplied callback
once the data has been fully handled. If an error
+occurs, the callback
will be called with the error as its
+first argument. The callback
is called asynchronously and before 'error'
is
+emitted.
+ +The return value is `true` if the internal buffer is less than the`highWaterMark` configured when the stream was created after admitting `chunk`. +If `false` is returned, further attempts to write data to the stream should +stop until the `'drain'` event is emitted. + +While a stream is not draining, calls to `write()` will buffer `chunk`, and +return false. Once all currently buffered chunks are drained (accepted for +delivery by the operating system), the `'drain'` event will be emitted. +It is recommended that once `write()` returns false, no more chunks be written +until the `'drain'` event is emitted. While calling `write()` on a stream that +is not draining is allowed, Node.js will buffer all written chunks until +maximum memory usage occurs, at which point it will abort unconditionally. +Even before it aborts, high memory usage will cause poor garbage collector +performance and high RSS (which is not typically released back to the system, +even after the memory is no longer required). Since TCP sockets may never +drain if the remote peer does not read the data, writing a socket that is +not draining may lead to a remotely exploitable vulnerability. + +Writing data while the stream is not draining is particularly +problematic for a `Transform`, because the `Transform` streams are paused +by default until they are piped or a `'data'` or `'readable'` event handler +is added. + +If the data to be written can be generated or fetched on demand, it is +recommended to encapsulate the logic into a `Readable` and use {@link pipe}. However, if calling `write()` is preferred, it is +possible to respect backpressure and avoid memory issues using the `'drain'` event: + +```js +function write(data, cb) { + if (!stream.write(data)) { + stream.once('drain', cb) + } else { + process.nextTick(cb) + } +} + +// Wait for cb to be called before doing any other write. +write('hello', () => { + console.log('Write completed, do more writes now.') +}) +``` + +A `Writable` stream in object mode will always ignore the `encoding` argument. + +
+chunk
– Optional data to write. For streams not operating in object mode, chunk
must be a string, Buffer
or Uint8Array
. For object mode streams, chunk
may be any
+JavaScript value other than null
.any
callback
(error) undefined | #
error
null
| Error
callback(error) =>
write(chunk, callback) =>
chunk
any
encoding
callback
(error) undefined | #
error
null
| Error
callback(error) =>
write(chunk, encoding, callback) =>
getEventListeners
(emitter, name) – Returns a copy of the array of listeners for the event named eventName
.
+ +For `EventEmitter`s this behaves exactly the same as calling `.listeners` on +the emitter. + +For `EventTarget`s this is the only way to get the event listeners for the +event target. This is useful for debugging and diagnostic purposes. + +```js +const { getEventListeners, EventEmitter } = require('events') + +{ + const ee = new EventEmitter() + const listener = () => console.log('Events are fun') + ee.on('foo', listener) + getEventListeners(ee, 'foo') // [listener] +} +{ + const et = new EventTarget() + const listener = () => console.log('Events are fun') + et.addEventListener('foo', listener) + getEventListeners(et, 'foo') // [listener] +} +``` + +
+emitter
name
string | symbol
getEventListeners(emitter, name) =>
listenerCount
(emitter, eventName) – A class method that returns the number of listeners for the given eventName
registered on the given emitter
.
+ +```js +const { EventEmitter, listenerCount } = require('events') +const myEmitter = new EventEmitter() +myEmitter.on('event', () => {}) +myEmitter.on('event', () => {}) +console.log(listenerCount(myEmitter, 'event')) +// Prints: 2 +``` + +
+emitter
– The emitter to queryeventName
– The event name
+string | symbol
listenerCount(emitter, eventName) =>
on
(emitter, eventName, options) – ```js
+const { on, EventEmitter } = require('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: + +```js +const { on, EventEmitter } = require('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()); +```` + +
+emitter
eventName
– The name of the event being listened forstring
options
on(emitter, eventName, options) =>
once
(emitter, eventName, options) – 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](https://dom.spec.whatwg.org/#interface-eventtarget) interface, which has no special`'error'` event +semantics and does not listen to the `'error'` event. + +```js +const { once, EventEmitter } = require('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.log('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: + +```js +const { EventEmitter, once } = require('events') + +const ee = new EventEmitter() + +once(ee, 'error') + .then(([err]) => console.log('ok', err.message)) + .catch(err => console.log('error', err.message)) + +ee.emit('error', new Error('boom')) + +// Prints: ok boom +``` + +An `AbortSignal` can be used to cancel waiting for the event: + +```js +const { EventEmitter, once } = require('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() // Abort waiting for the event +ee.emit('foo') // Prints: Waiting for the event was canceled! +``` + +
+emitter
eventName
string | symbol
options
once(emitter, eventName, options) =>
emitter
eventName
string
options
once(emitter, eventName, options) =>
setMaxListeners
(n, eventTargets) – By default EventEmitter
s 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 EventEmitter.setMaxListeners()
method allows the default limit to be
+modified (if eventTargets is empty) or modify the limit specified in every EventTarget
| EventEmitter
passed as arguments.
+The value can be set toInfinity
(or 0
) to indicate an unlimited number of listeners.
+ +```js +EventEmitter.setMaxListeners(20) +// Equivalent to +EventEmitter.defaultMaxListeners = 20 + +const eventTarget = new EventTarget() +// Only way to increase limit for `EventTarget` instances +// as these doesn't expose its own `setMaxListeners` method +EventEmitter.setMaxListeners(20, eventTarget) +``` + +
+n
number
eventTargets
setMaxListeners(n, eventTargets) =>
X509Certificate
– Encapsulates an X509 certificate and provides read-only access to
+its information.+ +```js +const { X509Certificate } = await import('crypto') + +const x509 = new X509Certificate('{... pem encoded cert ...}') + +console.log(x509.subject) +``` + +
+ boolean string string string undefined | string string string [] string string undefined | string string string string Pick<X509CheckOptions, checkEmail(email, options) => #
src/.fastpm/-/@types/node@17.0.45/crypto.d.ts#L3174 constructor
(buffer)
#
src/.fastpm/-/@types/node@17.0.45/crypto.d.ts#L3100 ca
– Will be `true` if this is a Certificate Authority (ca) certificate.#
src/.fastpm/-/@types/node@17.0.45/crypto.d.ts#L3105 fingerprint
– The SHA-1 fingerprint of this certificate.#
src/.fastpm/-/@types/node@17.0.45/crypto.d.ts#L3110 fingerprint256
– The SHA-256 fingerprint of this certificate.#
src/.fastpm/-/@types/node@17.0.45/crypto.d.ts#L3115 fingerprint512
– The SHA-512 fingerprint of this certificate.#
src/.fastpm/-/@types/node@17.0.45/crypto.d.ts#L3132 infoAccess
– The information access content of this certificate or undefined
if not
+available.#
src/.fastpm/-/@types/node@17.0.45/crypto.d.ts#L3142 issuer
– The issuer identification included in this certificate.#
src/.fastpm/-/@types/node@17.0.45/crypto.d.ts#L3148 issuerCertificate
– The issuer certificate or undefined
if the issuer certificate is not
+available.#
src/.fastpm/-/@types/node@17.0.45/crypto.d.ts#L3137 keyUsage
– An array detailing the key usages for this certificate.#
src/.fastpm/-/@types/node@17.0.45/crypto.d.ts#L3153 publicKey
– The public key KeyObject
for this certificate.#
src/.fastpm/-/@types/node@17.0.45/crypto.d.ts#L3158 raw
– A Buffer
containing the DER encoding of this certificate.#
src/.fastpm/-/@types/node@17.0.45/crypto.d.ts#L3163 serialNumber
– The serial number of this certificate.#
src/.fastpm/-/@types/node@17.0.45/crypto.d.ts#L3120 subject
– The complete subject of this certificate.#
src/.fastpm/-/@types/node@17.0.45/crypto.d.ts#L3126 subjectAltName
– The subject alternative name specified for this certificate or undefined
+if not available.#
src/.fastpm/-/@types/node@17.0.45/crypto.d.ts#L3168 validFrom
– The date/time from which this certificate is considered valid.#
src/.fastpm/-/@types/node@17.0.45/crypto.d.ts#L3173 validTo
– The date/time until which this certificate is considered valid.#
src/.fastpm/-/@types/node@17.0.45/crypto.d.ts#L3180 checkEmail
(email, options) – Checks whether the certificate matches the given email address.
#
email
#
options
"subject"
>undefined | string
checkHost
(name, options) – Checks whether the certificate matches the given host name.checkHost(name, options) =>
checkIP
(ip) – Checks whether the certificate matches the given IP address (IPv4 or IPv6). string#
ip
checkIP(ip) =>
checkIssued
(otherCert) – Checks whether this certificate was issued by the given otherCert
. #
otherCert
checkIssued(otherCert) =>
checkPrivateKey
(privateKey) – Checks whether the public key for this certificate is consistent with
+the given private key.
checkPrivateKey(privateKey) =>
toJSON
() – There is no standard JSON encoding for X509 certificates. ThetoJSON()
method returns a string containing the PEM encoded
+certificate.
toJSON() =>
toLegacyObject
() – Returns information about this certificate using the legacy certificate object
encoding.
toLegacyObject() =>
toString
() – Returns the PEM-encoded certificate.
toString() =>
verify
(publicKey) – Verifies that this certificate was signed by the given public key.
+Does not perform any other validation checks on the certificate.
verify(publicKey) =>
default
– Contains plugins to process CSS. Create one Processor
instance,
+initialize its plugins, and then use that instance on numerous CSS files.+ +```js +const processor = postcss([autoprefixer, postcssNested]) +processor.process(css1).then(result => console.log(result.css)) +processor.process(css2).then(result => console.log(result.css)) +``` + +
+ Plugin | TransformCallback | Transformer []
+
+```js
+const processor = postcss([autoprefixer, postcssNested])
+processor.plugins.length //=> 2
+```
+
+ string
+
+```js
+if (result.processor.version.split('.')[0] !== '6') {
+ throw new Error('This plugin works only with PostCSS 6')
+}
+```
+
+
+
+```js
+processor.process(css, { from: 'a.css', to: 'a.out.css' })
+ .then(result => {
+ console.log(result.css)
+ })
+```
+
+#
src/.fastpm/-/postcss@8.4.14/lib/processor.d.ts#L43 plugins
– Plugins added to this processor.#
src/.fastpm/-/postcss@8.4.14/lib/processor.d.ts#L33 version
– Current PostCSS version.#
src/.fastpm/-/postcss@8.4.14/lib/processor.d.ts#L98 process
(css, options) – Parses source CSS and returns a LazyResult
Promise proxy.
+Because some plugins can be asynchronous it doesn’t make
+any transformations. Transformations will be applied
+in the LazyResult
methods.
options
process(css, options) =>
use
(plugin) – Adds a plugin to be used as a CSS processor.
+ +PostCSS plugin can be in 4 formats: + +- A plugin in `Plugin` format. +- A plugin creator function with `pluginCreator.postcss = true`. + PostCSS will call this function without argument to get plugin. +- A function. PostCSS will pass the function a @{link Root} + as the first argument and current `Result` instance + as the second. +- Another `Processor` instance. PostCSS will copy plugins + from that instance into this one. + +Plugins can also be added by passing them as arguments when creating +a `postcss` instance (see [`postcss(plugins)`]). + +Asynchronous plugins should return a `Promise` instance. + +```js +const processor = postcss() + .use(autoprefixer) + .use(postcssNested) +``` + +
+plugin
– PostCSS plugin or Processor
with plugins.use(plugin) =>
default
– Represents a CSS file and contains all its parsed nodes.+ +```js +const root = postcss.parse('a{color:black} b{z-index:2}') +root.type //=> 'root' +root.nodes.length //=> 2 +``` + +
+ ChildNode []
+
+```js
+const root = postcss.parse('a { color: black }')
+root.nodes.length //=> 1
+root.nodes[0].selector //=> 'a'
+root.nodes[0].nodes[0].prop //=> 'color'
+```
+
+ undefined | default
+
+```js
+root.nodes[0].parent === root
+```
+
+
+
+Every parser saves its own properties,
+but the default CSS parser uses:
+
+- `before`: the space symbols before the node. It also stores `*`
+ and `_` symbols before the declaration (IE hack).
+- `after`: the space symbols after the last child of the node
+ to the end of the node.
+- `between`: the symbols between the property and value
+ for declarations, selector and `{` for rules, or last parameter
+ and `{` for at-rules.
+- `semicolon`: contains true if the last child has
+ an (optional) semicolon.
+- `afterName`: the space between the at-rule name and its parameters.
+- `left`: the space symbols between `/*` and the comment’s text.
+- `right`: the space symbols between the comment’s text
+ and
+
+The property is used in source map generation.
+
+If you create a node manually (e.g., with `postcss.decl()`),
+that node will not have a `source` property and will be absent
+from the source map. For this reason, the plugin developer should
+consider cloning nodes to create new ones (in which case the new node’s
+source will reference the original, cloned node) or setting
+the `source` property manually.
+
+```js
+decl.source.input.from //=> '/home/ai/a.sass'
+decl.source.start //=> { line: 10, column: 2 }
+decl.source.end //=> { line: 10, column: 12 }
+```
+
+```js
+// Bad
+const prefixed = postcss.decl({
+ prop: '-moz-' + decl.prop,
+ value: decl.value,
+})
+
+// Good
+const prefixed = decl.clone({ prop: '-moz-' + decl.prop })
+```
+
+```js
+if (atrule.name === 'add-link') {
+ const rule = postcss.rule({ selector: 'a', source: atrule.source })
+ atrule.parent.insertBefore(atrule, rule)
+}
+```
+
+
+
+```js
+new Declaration({ prop: 'color', value: 'black' }).type //=> 'decl'
+```
+
+
+
+Just alias for `node.parent.insertAfter(node, add)`.
+
+```js
+decl.after('color: black')
+```
+
+ string | default | ChildProps | default [] after(newNode) => #
src/.fastpm/-/postcss@8.4.14/lib/container.d.ts#L43 nodes
– An array containing the container’s children.#
src/.fastpm/-/postcss@8.4.14/lib/root.d.ts#L53 parent
– The node’s parent node.#
src/.fastpm/-/postcss@8.4.14/lib/root.d.ts#L54 raws
– Information to generate byte-to-byte equal node string as it was
+in the origin input.
*/
.
+- `important`: the content of the important statement,
+ if it is not just `!important`.
+
+PostCSS cleans selectors, declaration values and at-rule parameters
+from comments and extra spaces, but it stores origin content in raws
+properties. As such, if you don’t change a declaration’s value,
+PostCSS will use the raw value with comments.
+
+```js
+const root = postcss.parse('a {\n color:black\n}')
+root.first.first.raws //=> { before: '\n ', between: ':' }
+```
+
+#
src/.fastpm/-/postcss@8.4.14/lib/node.d.ts#L156 source
– The input source of the node.
#
src/.fastpm/-/postcss@8.4.14/lib/root.d.ts#L52 type
– tring representing the node’s type. Possible values are root
, atrule
,
+rule
, decl
, or comment
."root"
#
src/.fastpm/-/postcss@8.4.14/lib/node.d.ts#L401 after
(newNode) – Insert new node after current node to current node’s parent.
#
newNode
– New node.
append
(nodes) – Inserts new nodes to the end of the container.
+ +```js +const decl1 = new Declaration({ prop: 'color', value: 'black' }) +const decl2 = new Declaration({ prop: 'background-color', value: 'white' }) +rule.append(decl1, decl2) + +root.append({ name: 'charset', params: '"UTF-8"' }) // at-rule +root.append({ selector: 'a' }) // rule +rule.append({ prop: 'color', value: 'black' }) // declaration +rule.append({ text: 'Comment' }) // comment + +root.append('a {}') +root.first.append('color: black; z-index: 1') +``` + +
+nodes
– New nodes.string | string [] | default | ChildProps | default [] | ChildProps [] []
append(nodes) =>
assign
(overrides) – Assigns properties to the current node.
+ +```js +decl.assign({ prop: 'word-wrap', value: 'break-word' }) +``` + +
+overrides
object | RootProps
assign(overrides) =>
before
(newNode) – Insert new node before current node to current node’s parent.
+ +Just alias for `node.parent.insertBefore(node, add)`. + +```js +decl.before('content: ""') +``` + +
+newNode
– New node.string | default | ChildProps | default []
before(newNode) =>
cleanRaws
(keepBetween) – Clear the code style properties for the node and its children.
+ +```js +node.raws.before //=> ' ' +node.cleanRaws() +node.raws.before //=> undefined +``` + +
+keepBetween
– Keep the raws.between
symbols.
+boolean
cleanRaws(keepBetween) =>
clone
(overrides) – Returns an exact clone of the node.
+ +The resulting cloned node and its (cloned) children will retain +code style properties. + +```js +decl.raws.before //=> "\n " +const cloned = decl.clone({ prop: '-moz-' + decl.prop }) +cloned.raws.before //=> "\n " +cloned.toString() //=> -moz-transform: scale(0) +``` + +
+overrides
– New properties to override in the clone.object
clone(overrides) =>
cloneAfter
(overrides) – Shortcut to clone the node and insert the resulting cloned node
+after the current node. object#
overrides
– New properties to override in the clone.
cloneAfter(overrides) =>
cloneBefore
(overrides) – Shortcut to clone the node and insert the resulting cloned node
+before the current node.
+ +```js +decl.cloneBefore({ prop: '-moz-' + decl.prop }) +``` + +
+overrides
– Mew properties to override in the clone.
+object
cloneBefore(overrides) =>
each
(callback) – Iterates through the container’s immediate children,
+calling callback
for each child.
+ +Returning `false` in the callback will break iteration. + +This method only iterates through the container’s immediate children. +If you need to recursively iterate through all the container’s descendant +nodes, use `Container#walk`. + +Unlike the for `{}`-cycle or `Array#forEach` this iterator is safe +if you are mutating the array of child nodes during iteration. +PostCSS will adjust the current index to match the mutations. + +```js +const root = postcss.parse('a { color: black; z-index: 1 }') +const rule = root.first + +for (const decl of rule.nodes) { + decl.cloneBefore({ prop: '-webkit-' + decl.prop }) + // Cycle will be infinite, because cloneBefore moves the current node + // to the next index +} + +rule.each(decl => { + decl.cloneBefore({ prop: '-webkit-' + decl.prop }) + // Will be executed only for color and z-index +}) +``` + +
+each(callback) =>
false
error
(message, options) – Returns a CssSyntaxError
instance containing the original position
+of the node in the source, showing line and column numbers and also
+a small excerpt to facilitate debugging.
+ +If present, an input source map will be used to get the original position +of the source, even from a previous compilation step +(e.g., from Sass compilation). + +This method produces very useful error messages. + +```js +if (!variables[name]) { + throw decl.error(`Unknown variable ${name}`, { word: name }) + // CssSyntaxError: postcss-vars:a.sass:4:3: Unknown variable $black + // color: $black + // a + // ^ + // background: white +} +``` + +
+message
– Error description.string
options
error(message, options) =>
every
(condition) – Returns true
if callback returns true
+for all of the container’s children.
+ +```js +const noPrefixes = rule.every(i => i.prop[0] !== '-') +``` + +
+condition
(node, index, nodes) number#
index
condition(node, index, nodes) =>
every(condition) =>
index
(child) – Returns a child
’s index within the Container#nodes
array.
+ +```js +rule.index(rule.nodes[2]) //=> 2 +``` + +
+child
– Child of the current container.number | ChildNode
index(child) =>
insertAfter
(oldNode, newNode) – Insert new node after old node within the container. string | string [] | ChildNode | ChildNode [] | ChildProps | ChildProps []#
newNode
– New node.
insertAfter(oldNode, newNode) =>
insertBefore
(oldNode, newNode) – Insert new node before old node within the container.
+ +```js +rule.insertBefore(decl, decl.clone({ prop: '-webkit-' + decl.prop })) +``` + +
+oldNode
– Child or child’s index.number | ChildNode
newNode
– New node.string | string [] | ChildNode | ChildNode [] | ChildProps | ChildProps []
insertBefore(oldNode, newNode) =>
next
() – Returns the next child of the node’s parent.
+Returns undefined
if the current node is the last child.
+ +```js +if (comment.text === 'delete next') { + const next = comment.next() + if (next) { + next.remove() + } +} +``` + +
+next() =>
positionBy
(opts) – Get the position for a word or an index inside the node. Pick<WarningOptions, #
opts
– Options."word"
| "index"
>
positionBy(opts) =>
positionInside
(index) – Convert string index to line/column. number#
index
– The symbol number in the node’s string.
positionInside(index) =>
prepend
(nodes) – Inserts new nodes to the start of the container.
+ +```js +const decl1 = new Declaration({ prop: 'color', value: 'black' }) +const decl2 = new Declaration({ prop: 'background-color', value: 'white' }) +rule.prepend(decl1, decl2) + +root.append({ name: 'charset', params: '"UTF-8"' }) // at-rule +root.append({ selector: 'a' }) // rule +rule.append({ prop: 'color', value: 'black' }) // declaration +rule.append({ text: 'Comment' }) // comment + +root.append('a {}') +root.first.append('color: black; z-index: 1') +``` + +
+nodes
– New nodes.string | string [] | default | ChildProps | default [] | ChildProps [] []
prepend(nodes) =>
prev
() – Returns the previous child of the node’s parent.
+Returns undefined
if the current node is the first child.
+ +```js +const annotation = decl.prev() +if (annotation.type === 'comment') { + readAnnotation(annotation.text) +} +``` + +
+prev() =>
push
(child) – Add child to the end of the node.
+ +```js +rule.push(new Declaration({ prop: 'color', value: 'black' })) +``` + +
+child
– New node.push(child) =>
rangeBy
(opts) – Get the range for a word or start and end index inside the node.
+The start index is inclusive; the end index is exclusive. Pick<WarningOptions, #
opts
– Options."word"
| "index"
| "endIndex"
>
rangeBy(opts) =>
raw
(prop, defaultType) – Returns a Node#raws
value. If the node is missing
+the code style property (because the node was manually built or cloned),
+PostCSS will try to autodetect the code style property by looking
+at other nodes in the tree.
+ +```js +const root = postcss.parse('a { background: white }') +root.nodes[0].append({ prop: 'color', value: 'black' }) +root.nodes[0].nodes[1].raws.before //=> undefined +root.nodes[0].nodes[1].raw('before') //=> ' ' +``` + +
+prop
– Name of code style property.string
defaultType
– Name of default value, it can be missed
+if the value is the same as prop.string
raw(prop, defaultType) =>
remove
() – Removes the node from its parent and cleans the parent properties
+from the node and its children.
+ +```js +if (decl.prop.match(/^-webkit-/)) { + decl.remove() +} +``` + +
+remove() =>
removeAll
() – Removes all children from the container
+and cleans their parent properties.
+ +```js +rule.removeAll() +rule.nodes.length //=> 0 +``` + +
+removeAll() =>
removeChild
(child) – Removes node from the container and cleans the parent properties
+from the node and its children.
+ +```js +rule.nodes.length //=> 5 +rule.removeChild(decl) +rule.nodes.length //=> 4 +decl.parent //=> undefined +``` + +
+child
– Child or child’s index.number | ChildNode
removeChild(child) =>
replaceValues
(pattern, options, replaced) – Passes all declaration values within the container that match pattern
+through callback, replacing those values with the returned result
+of callback.
+ +This method is useful if you are using a custom unit or function +and need to iterate through all values. + +```js +root.replaceValues(/\d+rem/, { fast: 'rem' }, string => { + return 15 * parseInt(string) + 'px' +}) +``` + +
+pattern
– Replace pattern.string | RegExp
options
replaceValues(pattern, options, replaced) =>
pattern
string | RegExp
replaced
string |
replaceValues(pattern, replaced) =>
replaceWith
(nodes) – Inserts node(s) before the current node and removes the current node.
+ +```js +AtRule: { + mixin: + ; + ;(atrule => { + atrule.replaceWith(mixinRules[atrule.params]) + }) +} +``` + +
+nodes
– Mode(s) to replace current one.ChildNode | ChildNode [] | ChildProps | ChildProps [] []
replaceWith(nodes) =>
root
() – Finds the Root instance of the node’s tree.
+ +```js +root.nodes[0].nodes[0].root() === root +``` + +
+root() =>
some
(condition) – Returns true
if callback returns true
for (at least) one
+of the container’s children.
+ +```js +const hasPrefix = rule.some(i => i.prop[0] === '-') +``` + +
+condition
(node, index, nodes) number#
index
condition(node, index, nodes) =>
some(condition) =>
toJSON
() – Fix circular links on JSON.stringify()
.
toJSON() =>
toResult
(options) – Returns a Result
instance representing the root’s CSS.
+ +```js +const root1 = postcss.parse(css1, { from: 'a.css' }) +const root2 = postcss.parse(css2, { from: 'b.css' }) +root1.append(root2) +const result = root1.toResult({ to: 'all.css', map: true }) +``` + +
+options
toResult(options) =>
toString
(stringifier) – Returns a CSS string representing the node.
+ +```js +new Rule({ selector: 'a' }).toString() //=> "a {}" +``` + +
+stringifier
– A syntax to use in string generation.toString(stringifier) =>
walk
(callback) – Traverses the container’s descendant nodes, calling callback
+for each node.
+ +Like container.each(), this method is safe to use +if you are mutating arrays during iteration. + +If you only need to iterate through the container’s immediate children, +use `Container#each`. + +```js +root.walk(node => { + // Traverses all descendant nodes. +}) +``` + +
+walk(callback) =>
false
walkAtRules
(nameFilter, callback) – Traverses the container’s descendant nodes, calling callback
+for each at-rule node.
+ +If you pass a filter, iteration will only happen over at-rules +that have matching names. + +Like `Container#each`, this method is safe +to use if you are mutating arrays during iteration. + +```js +root.walkAtRules(rule => { + if (isOld(rule.name)) rule.remove() +}) + +let first = false +root.walkAtRules('charset', rule => { + if (!first) { + first = true + } else { + rule.remove() + } +}) +``` + +
+nameFilter
string | RegExp
walkAtRules(nameFilter, callback) =>
false
walkAtRules(callback) =>
false
walkComments
(callback) – Traverses the container’s descendant nodes, calling callback
+for each comment node.
+ +Like `Container#each`, this method is safe +to use if you are mutating arrays during iteration. + +```js +root.walkComments(comment => { + comment.remove() +}) +``` + +
+callback
(comment, indexed) number#
indexed
callback(comment, indexed) =>
false
| voidwalkComments(callback) =>
false
callback
(comment, indexed) number#
indexed
callback(comment, indexed) =>
false
| voidwalkComments(callback) =>
false
walkDecls
(propFilter, callback) – Traverses the container’s descendant nodes, calling callback
+for each declaration node.
+ +If you pass a filter, iteration will only happen over declarations +with matching properties. + +```js +root.walkDecls(decl => { + checkPropertySupport(decl.prop) +}) + +root.walkDecls('border-radius', decl => { + decl.remove() +}) + +root.walkDecls(/^background/, decl => { + decl.value = takeFirstColorFromGradient(decl.value) +}) +``` + +Like `Container#each`, this method is safe +to use if you are mutating arrays during iteration. + +
+propFilter
string | RegExp
walkDecls(propFilter, callback) =>
false
walkDecls(callback) =>
false
walkRules
(selectorFilter, callback) – Traverses the container’s descendant nodes, calling callback
+for each rule node.
+ +If you pass a filter, iteration will only happen over rules +with matching selectors. + +Like `Container#each`, this method is safe +to use if you are mutating arrays during iteration. + +```js +const selectors = [] +root.walkRules(rule => { + selectors.push(rule.selector) +}) +console.log(`Your CSS uses ${selectors.length} selectors`) +``` + +
+selectorFilter
string | RegExp
walkRules(selectorFilter, callback) =>
false
walkRules(callback) =>
false
warn
(result, text, opts) – This method is provided as a convenience wrapper for Result#warn
.
+ +```js +Declaration: { + bad: + ; + ;((decl, { result }) => { + decl.warn(result, 'Deprecated property bad') + }) +} +``` + +
+result
– The Result
instance that will receive the warning.text
– Warning message.string
opts
– Warning Options.
+warn(result, text, opts) =>
default
– Represents a file and contains all its parsed nodes.+ +**Experimental:** some aspects of this node could change within minor +or patch version releases. + +```js +const document = htmlParser( + '' +) +document.type //=> 'document' +document.nodes.length //=> 2 +``` + +
+ default []
+
+```js
+const root = postcss.parse('a { color: black }')
+root.nodes.length //=> 1
+root.nodes[0].selector //=> 'a'
+root.nodes[0].nodes[0].prop //=> 'color'
+```
+
+ undefined
+
+```js
+root.nodes[0].parent === root
+```
+
+ any
+
+Every parser saves its own properties,
+but the default CSS parser uses:
+
+- `before`: the space symbols before the node. It also stores `*`
+ and `_` symbols before the declaration (IE hack).
+- `after`: the space symbols after the last child of the node
+ to the end of the node.
+- `between`: the symbols between the property and value
+ for declarations, selector and `{` for rules, or last parameter
+ and `{` for at-rules.
+- `semicolon`: contains true if the last child has
+ an (optional) semicolon.
+- `afterName`: the space between the at-rule name and its parameters.
+- `left`: the space symbols between `/*` and the comment’s text.
+- `right`: the space symbols between the comment’s text
+ and
+
+The property is used in source map generation.
+
+If you create a node manually (e.g., with `postcss.decl()`),
+that node will not have a `source` property and will be absent
+from the source map. For this reason, the plugin developer should
+consider cloning nodes to create new ones (in which case the new node’s
+source will reference the original, cloned node) or setting
+the `source` property manually.
+
+```js
+decl.source.input.from //=> '/home/ai/a.sass'
+decl.source.start //=> { line: 10, column: 2 }
+decl.source.end //=> { line: 10, column: 12 }
+```
+
+```js
+// Bad
+const prefixed = postcss.decl({
+ prop: '-moz-' + decl.prop,
+ value: decl.value,
+})
+
+// Good
+const prefixed = decl.clone({ prop: '-moz-' + decl.prop })
+```
+
+```js
+if (atrule.name === 'add-link') {
+ const rule = postcss.rule({ selector: 'a', source: atrule.source })
+ atrule.parent.insertBefore(atrule, rule)
+}
+```
+
+
+
+```js
+new Declaration({ prop: 'color', value: 'black' }).type //=> 'decl'
+```
+
+
+
+Just alias for `node.parent.insertAfter(node, add)`.
+
+```js
+decl.after('color: black')
+```
+
+ string | default | ChildProps | default [] after(newNode) => #
src/.fastpm/-/postcss@8.4.14/lib/container.d.ts#L43 nodes
– An array containing the container’s children.#
src/.fastpm/-/postcss@8.4.14/lib/document.d.ts#L37 parent
– The node’s parent node.#
src/.fastpm/-/postcss@8.4.14/lib/node.d.ts#L191 raws
– Information to generate byte-to-byte equal node string as it was
+in the origin input.*/
.
+- `important`: the content of the important statement,
+ if it is not just `!important`.
+
+PostCSS cleans selectors, declaration values and at-rule parameters
+from comments and extra spaces, but it stores origin content in raws
+properties. As such, if you don’t change a declaration’s value,
+PostCSS will use the raw value with comments.
+
+```js
+const root = postcss.parse('a {\n color:black\n}')
+root.first.first.raws //=> { before: '\n ', between: ':' }
+```
+
+#
src/.fastpm/-/postcss@8.4.14/lib/node.d.ts#L156 source
– The input source of the node.
#
src/.fastpm/-/postcss@8.4.14/lib/document.d.ts#L36 type
– tring representing the node’s type. Possible values are root
, atrule
,
+rule
, decl
, or comment
."document"
#
src/.fastpm/-/postcss@8.4.14/lib/node.d.ts#L401 after
(newNode) – Insert new node after current node to current node’s parent.
#
newNode
– New node.
append
(nodes) – Inserts new nodes to the end of the container.
+ +```js +const decl1 = new Declaration({ prop: 'color', value: 'black' }) +const decl2 = new Declaration({ prop: 'background-color', value: 'white' }) +rule.append(decl1, decl2) + +root.append({ name: 'charset', params: '"UTF-8"' }) // at-rule +root.append({ selector: 'a' }) // rule +rule.append({ prop: 'color', value: 'black' }) // declaration +rule.append({ text: 'Comment' }) // comment + +root.append('a {}') +root.first.append('color: black; z-index: 1') +``` + +
+nodes
– New nodes.string | string [] | default | ChildProps | default [] | ChildProps [] []
append(nodes) =>
assign
(overrides) – Assigns properties to the current node.
+ +```js +decl.assign({ prop: 'word-wrap', value: 'break-word' }) +``` + +
+overrides
– New properties to override the node.object
assign(overrides) =>
before
(newNode) – Insert new node before current node to current node’s parent.
+ +Just alias for `node.parent.insertBefore(node, add)`. + +```js +decl.before('content: ""') +``` + +
+newNode
– New node.string | default | ChildProps | default []
before(newNode) =>
cleanRaws
(keepBetween) – Clear the code style properties for the node and its children.
+ +```js +node.raws.before //=> ' ' +node.cleanRaws() +node.raws.before //=> undefined +``` + +
+keepBetween
– Keep the raws.between
symbols.
+boolean
cleanRaws(keepBetween) =>
clone
(overrides) – Returns an exact clone of the node.
+ +The resulting cloned node and its (cloned) children will retain +code style properties. + +```js +decl.raws.before //=> "\n " +const cloned = decl.clone({ prop: '-moz-' + decl.prop }) +cloned.raws.before //=> "\n " +cloned.toString() //=> -moz-transform: scale(0) +``` + +
+overrides
– New properties to override in the clone.object
clone(overrides) =>
cloneAfter
(overrides) – Shortcut to clone the node and insert the resulting cloned node
+after the current node. object#
overrides
– New properties to override in the clone.
cloneAfter(overrides) =>
cloneBefore
(overrides) – Shortcut to clone the node and insert the resulting cloned node
+before the current node.
+ +```js +decl.cloneBefore({ prop: '-moz-' + decl.prop }) +``` + +
+overrides
– Mew properties to override in the clone.
+object
cloneBefore(overrides) =>
each
(callback) – Iterates through the container’s immediate children,
+calling callback
for each child.
+ +Returning `false` in the callback will break iteration. + +This method only iterates through the container’s immediate children. +If you need to recursively iterate through all the container’s descendant +nodes, use `Container#walk`. + +Unlike the for `{}`-cycle or `Array#forEach` this iterator is safe +if you are mutating the array of child nodes during iteration. +PostCSS will adjust the current index to match the mutations. + +```js +const root = postcss.parse('a { color: black; z-index: 1 }') +const rule = root.first + +for (const decl of rule.nodes) { + decl.cloneBefore({ prop: '-webkit-' + decl.prop }) + // Cycle will be infinite, because cloneBefore moves the current node + // to the next index +} + +rule.each(decl => { + decl.cloneBefore({ prop: '-webkit-' + decl.prop }) + // Will be executed only for color and z-index +}) +``` + +
+each(callback) =>
false
error
(message, options) – Returns a CssSyntaxError
instance containing the original position
+of the node in the source, showing line and column numbers and also
+a small excerpt to facilitate debugging.
+ +If present, an input source map will be used to get the original position +of the source, even from a previous compilation step +(e.g., from Sass compilation). + +This method produces very useful error messages. + +```js +if (!variables[name]) { + throw decl.error(`Unknown variable ${name}`, { word: name }) + // CssSyntaxError: postcss-vars:a.sass:4:3: Unknown variable $black + // color: $black + // a + // ^ + // background: white +} +``` + +
+message
– Error description.string
options
error(message, options) =>
every
(condition) – Returns true
if callback returns true
+for all of the container’s children.
+ +```js +const noPrefixes = rule.every(i => i.prop[0] !== '-') +``` + +
+condition
(node, index, nodes) number#
index
condition(node, index, nodes) =>
every(condition) =>
index
(child) – Returns a child
’s index within the Container#nodes
array.
+ +```js +rule.index(rule.nodes[2]) //=> 2 +``` + +
+child
– Child of the current container.number | default
index(child) =>
insertAfter
(oldNode, newNode) – Insert new node after old node within the container. string | string [] | default | ChildProps | ChildProps [] | default []#
newNode
– New node.
insertAfter(oldNode, newNode) =>
insertBefore
(oldNode, newNode) – Insert new node before old node within the container.
+ +```js +rule.insertBefore(decl, decl.clone({ prop: '-webkit-' + decl.prop })) +``` + +
+oldNode
– Child or child’s index.number | default
newNode
– New node.string | string [] | default | ChildProps | ChildProps [] | default []
insertBefore(oldNode, newNode) =>
next
() – Returns the next child of the node’s parent.
+Returns undefined
if the current node is the last child.
+ +```js +if (comment.text === 'delete next') { + const next = comment.next() + if (next) { + next.remove() + } +} +``` + +
+next() =>
positionBy
(opts) – Get the position for a word or an index inside the node. Pick<WarningOptions, #
opts
– Options."word"
| "index"
>
positionBy(opts) =>
positionInside
(index) – Convert string index to line/column. number#
index
– The symbol number in the node’s string.
positionInside(index) =>
prepend
(nodes) – Inserts new nodes to the start of the container.
+ +```js +const decl1 = new Declaration({ prop: 'color', value: 'black' }) +const decl2 = new Declaration({ prop: 'background-color', value: 'white' }) +rule.prepend(decl1, decl2) + +root.append({ name: 'charset', params: '"UTF-8"' }) // at-rule +root.append({ selector: 'a' }) // rule +rule.append({ prop: 'color', value: 'black' }) // declaration +rule.append({ text: 'Comment' }) // comment + +root.append('a {}') +root.first.append('color: black; z-index: 1') +``` + +
+nodes
– New nodes.string | string [] | default | ChildProps | default [] | ChildProps [] []
prepend(nodes) =>
prev
() – Returns the previous child of the node’s parent.
+Returns undefined
if the current node is the first child.
+ +```js +const annotation = decl.prev() +if (annotation.type === 'comment') { + readAnnotation(annotation.text) +} +``` + +
+prev() =>
push
(child) – Add child to the end of the node.
+ +```js +rule.push(new Declaration({ prop: 'color', value: 'black' })) +``` + +
+child
– New node.push(child) =>
rangeBy
(opts) – Get the range for a word or start and end index inside the node.
+The start index is inclusive; the end index is exclusive. Pick<WarningOptions, #
opts
– Options."word"
| "index"
| "endIndex"
>
rangeBy(opts) =>
raw
(prop, defaultType) – Returns a Node#raws
value. If the node is missing
+the code style property (because the node was manually built or cloned),
+PostCSS will try to autodetect the code style property by looking
+at other nodes in the tree.
+ +```js +const root = postcss.parse('a { background: white }') +root.nodes[0].append({ prop: 'color', value: 'black' }) +root.nodes[0].nodes[1].raws.before //=> undefined +root.nodes[0].nodes[1].raw('before') //=> ' ' +``` + +
+prop
– Name of code style property.string
defaultType
– Name of default value, it can be missed
+if the value is the same as prop.string
raw(prop, defaultType) =>
remove
() – Removes the node from its parent and cleans the parent properties
+from the node and its children.
+ +```js +if (decl.prop.match(/^-webkit-/)) { + decl.remove() +} +``` + +
+remove() =>
removeAll
() – Removes all children from the container
+and cleans their parent properties.
+ +```js +rule.removeAll() +rule.nodes.length //=> 0 +``` + +
+removeAll() =>
removeChild
(child) – Removes node from the container and cleans the parent properties
+from the node and its children.
+ +```js +rule.nodes.length //=> 5 +rule.removeChild(decl) +rule.nodes.length //=> 4 +decl.parent //=> undefined +``` + +
+child
– Child or child’s index.number | default
removeChild(child) =>
replaceValues
(pattern, options, replaced) – Passes all declaration values within the container that match pattern
+through callback, replacing those values with the returned result
+of callback.
+ +This method is useful if you are using a custom unit or function +and need to iterate through all values. + +```js +root.replaceValues(/\d+rem/, { fast: 'rem' }, string => { + return 15 * parseInt(string) + 'px' +}) +``` + +
+pattern
– Replace pattern.string | RegExp
options
replaceValues(pattern, options, replaced) =>
pattern
string | RegExp
replaced
string |
replaceValues(pattern, replaced) =>
replaceWith
(nodes) – Inserts node(s) before the current node and removes the current node.
+ +```js +AtRule: { + mixin: + ; + ;(atrule => { + atrule.replaceWith(mixinRules[atrule.params]) + }) +} +``` + +
+nodes
– Mode(s) to replace current one.ChildNode | ChildNode [] | ChildProps | ChildProps [] []
replaceWith(nodes) =>
root
() – Finds the Root instance of the node’s tree.
+ +```js +root.nodes[0].nodes[0].root() === root +``` + +
+root() =>
some
(condition) – Returns true
if callback returns true
for (at least) one
+of the container’s children.
+ +```js +const hasPrefix = rule.some(i => i.prop[0] === '-') +``` + +
+condition
(node, index, nodes) number#
index
condition(node, index, nodes) =>
some(condition) =>
toJSON
() – Fix circular links on JSON.stringify()
.
toJSON() =>
toResult
(options) – Returns a Result
instance representing the document’s CSS roots.
+ +```js +const root1 = postcss.parse(css1, { from: 'a.css' }) +const root2 = postcss.parse(css2, { from: 'b.css' }) +const document = postcss.document() +document.append(root1) +document.append(root2) +const result = document.toResult({ to: 'all.css', map: true }) +``` + +
+options
toResult(options) =>
toString
(stringifier) – Returns a CSS string representing the node.
+ +```js +new Rule({ selector: 'a' }).toString() //=> "a {}" +``` + +
+stringifier
– A syntax to use in string generation.toString(stringifier) =>
walk
(callback) – Traverses the container’s descendant nodes, calling callback
+for each node.
+ +Like container.each(), this method is safe to use +if you are mutating arrays during iteration. + +If you only need to iterate through the container’s immediate children, +use `Container#each`. + +```js +root.walk(node => { + // Traverses all descendant nodes. +}) +``` + +
+walk(callback) =>
false
walkAtRules
(nameFilter, callback) – Traverses the container’s descendant nodes, calling callback
+for each at-rule node.
+ +If you pass a filter, iteration will only happen over at-rules +that have matching names. + +Like `Container#each`, this method is safe +to use if you are mutating arrays during iteration. + +```js +root.walkAtRules(rule => { + if (isOld(rule.name)) rule.remove() +}) + +let first = false +root.walkAtRules('charset', rule => { + if (!first) { + first = true + } else { + rule.remove() + } +}) +``` + +
+nameFilter
string | RegExp
walkAtRules(nameFilter, callback) =>
false
walkAtRules(callback) =>
false
walkComments
(callback) – Traverses the container’s descendant nodes, calling callback
+for each comment node.
+ +Like `Container#each`, this method is safe +to use if you are mutating arrays during iteration. + +```js +root.walkComments(comment => { + comment.remove() +}) +``` + +
+callback
(comment, indexed) number#
indexed
callback(comment, indexed) =>
false
| voidwalkComments(callback) =>
false
callback
(comment, indexed) number#
indexed
callback(comment, indexed) =>
false
| voidwalkComments(callback) =>
false
walkDecls
(propFilter, callback) – Traverses the container’s descendant nodes, calling callback
+for each declaration node.
+ +If you pass a filter, iteration will only happen over declarations +with matching properties. + +```js +root.walkDecls(decl => { + checkPropertySupport(decl.prop) +}) + +root.walkDecls('border-radius', decl => { + decl.remove() +}) + +root.walkDecls(/^background/, decl => { + decl.value = takeFirstColorFromGradient(decl.value) +}) +``` + +Like `Container#each`, this method is safe +to use if you are mutating arrays during iteration. + +
+propFilter
string | RegExp
walkDecls(propFilter, callback) =>
false
walkDecls(callback) =>
false
walkRules
(selectorFilter, callback) – Traverses the container’s descendant nodes, calling callback
+for each rule node.
+ +If you pass a filter, iteration will only happen over rules +with matching selectors. + +Like `Container#each`, this method is safe +to use if you are mutating arrays during iteration. + +```js +const selectors = [] +root.walkRules(rule => { + selectors.push(rule.selector) +}) +console.log(`Your CSS uses ${selectors.length} selectors`) +``` + +
+selectorFilter
string | RegExp
walkRules(selectorFilter, callback) =>
false
walkRules(callback) =>
false
warn
(result, text, opts) – This method is provided as a convenience wrapper for Result#warn
.
+ +```js +Declaration: { + bad: + ; + ;((decl, { result }) => { + decl.warn(result, 'Deprecated property bad') + }) +} +``` + +
+result
– The Result
instance that will receive the warning.text
– Warning message.string
opts
– Warning Options.
+warn(result, text, opts) =>
default
– The Root
, AtRule
, and Rule
container nodes
+inherit some common methods to help work with their children.+ +Note that all containers can store any content. If you write a rule inside +a rule, PostCSS will parse it. + +
+ Child []
+
+```js
+const root = postcss.parse('a { color: black }')
+root.nodes.length //=> 1
+root.nodes[0].selector //=> 'a'
+root.nodes[0].nodes[0].prop //=> 'color'
+```
+
+ any
+
+Every parser saves its own properties,
+but the default CSS parser uses:
+
+- `before`: the space symbols before the node. It also stores `*`
+ and `_` symbols before the declaration (IE hack).
+- `after`: the space symbols after the last child of the node
+ to the end of the node.
+- `between`: the symbols between the property and value
+ for declarations, selector and `{` for rules, or last parameter
+ and `{` for at-rules.
+- `semicolon`: contains true if the last child has
+ an (optional) semicolon.
+- `afterName`: the space between the at-rule name and its parameters.
+- `left`: the space symbols between `/*` and the comment’s text.
+- `right`: the space symbols between the comment’s text
+ and
+
+The property is used in source map generation.
+
+If you create a node manually (e.g., with `postcss.decl()`),
+that node will not have a `source` property and will be absent
+from the source map. For this reason, the plugin developer should
+consider cloning nodes to create new ones (in which case the new node’s
+source will reference the original, cloned node) or setting
+the `source` property manually.
+
+```js
+decl.source.input.from //=> '/home/ai/a.sass'
+decl.source.start //=> { line: 10, column: 2 }
+decl.source.end //=> { line: 10, column: 12 }
+```
+
+```js
+// Bad
+const prefixed = postcss.decl({
+ prop: '-moz-' + decl.prop,
+ value: decl.value,
+})
+
+// Good
+const prefixed = decl.clone({ prop: '-moz-' + decl.prop })
+```
+
+```js
+if (atrule.name === 'add-link') {
+ const rule = postcss.rule({ selector: 'a', source: atrule.source })
+ atrule.parent.insertBefore(atrule, rule)
+}
+```
+
+ string
+
+```js
+new Declaration({ prop: 'color', value: 'black' }).type //=> 'decl'
+```
+
+#
constructor
(defaults)
#
src/.fastpm/-/postcss@8.4.14/lib/container.d.ts#L43 nodes
– An array containing the container’s children.#
src/.fastpm/-/postcss@8.4.14/lib/node.d.ts#L118 parent
– The node’s parent node.#
src/.fastpm/-/postcss@8.4.14/lib/node.d.ts#L191 raws
– Information to generate byte-to-byte equal node string as it was
+in the origin input.*/
.
+- `important`: the content of the important statement,
+ if it is not just `!important`.
+
+PostCSS cleans selectors, declaration values and at-rule parameters
+from comments and extra spaces, but it stores origin content in raws
+properties. As such, if you don’t change a declaration’s value,
+PostCSS will use the raw value with comments.
+
+```js
+const root = postcss.parse('a {\n color:black\n}')
+root.first.first.raws //=> { before: '\n ', between: ':' }
+```
+
+#
src/.fastpm/-/postcss@8.4.14/lib/node.d.ts#L156 source
– The input source of the node.
#
src/.fastpm/-/postcss@8.4.14/lib/node.d.ts#L109 type
– tring representing the node’s type. Possible values are root
, atrule
,
+rule
, decl
, or comment
.#
src/.fastpm/-/postcss@8.4.14/lib/node.d.ts#L401 after
(newNode) – Insert new node after current node to current node’s parent.
append
(nodes) – Inserts new nodes to the end of the container.
+ +```js +const decl1 = new Declaration({ prop: 'color', value: 'black' }) +const decl2 = new Declaration({ prop: 'background-color', value: 'white' }) +rule.append(decl1, decl2) + +root.append({ name: 'charset', params: '"UTF-8"' }) // at-rule +root.append({ selector: 'a' }) // rule +rule.append({ prop: 'color', value: 'black' }) // declaration +rule.append({ text: 'Comment' }) // comment + +root.append('a {}') +root.first.append('color: black; z-index: 1') +``` + +
+nodes
– New nodes.string | string [] | default | ChildProps | default [] | ChildProps [] []
append(nodes) =>
assign
(overrides) – Assigns properties to the current node.
+ +```js +decl.assign({ prop: 'word-wrap', value: 'break-word' }) +``` + +
+overrides
– New properties to override the node.object
assign(overrides) =>
before
(newNode) – Insert new node before current node to current node’s parent.
+ +Just alias for `node.parent.insertBefore(node, add)`. + +```js +decl.before('content: ""') +``` + +
+newNode
– New node.string | default | ChildProps | default []
before(newNode) =>
cleanRaws
(keepBetween) – Clear the code style properties for the node and its children.
+ +```js +node.raws.before //=> ' ' +node.cleanRaws() +node.raws.before //=> undefined +``` + +
+keepBetween
– Keep the raws.between
symbols.
+boolean
cleanRaws(keepBetween) =>
clone
(overrides) – Returns an exact clone of the node.
+ +The resulting cloned node and its (cloned) children will retain +code style properties. + +```js +decl.raws.before //=> "\n " +const cloned = decl.clone({ prop: '-moz-' + decl.prop }) +cloned.raws.before //=> "\n " +cloned.toString() //=> -moz-transform: scale(0) +``` + +
+overrides
– New properties to override in the clone.object
clone(overrides) =>
cloneAfter
(overrides) – Shortcut to clone the node and insert the resulting cloned node
+after the current node. object#
overrides
– New properties to override in the clone.
cloneAfter(overrides) =>
cloneBefore
(overrides) – Shortcut to clone the node and insert the resulting cloned node
+before the current node.
+ +```js +decl.cloneBefore({ prop: '-moz-' + decl.prop }) +``` + +
+overrides
– Mew properties to override in the clone.
+object
cloneBefore(overrides) =>
each
(callback) – Iterates through the container’s immediate children,
+calling callback
for each child.
+ +Returning `false` in the callback will break iteration. + +This method only iterates through the container’s immediate children. +If you need to recursively iterate through all the container’s descendant +nodes, use `Container#walk`. + +Unlike the for `{}`-cycle or `Array#forEach` this iterator is safe +if you are mutating the array of child nodes during iteration. +PostCSS will adjust the current index to match the mutations. + +```js +const root = postcss.parse('a { color: black; z-index: 1 }') +const rule = root.first + +for (const decl of rule.nodes) { + decl.cloneBefore({ prop: '-webkit-' + decl.prop }) + // Cycle will be infinite, because cloneBefore moves the current node + // to the next index +} + +rule.each(decl => { + decl.cloneBefore({ prop: '-webkit-' + decl.prop }) + // Will be executed only for color and z-index +}) +``` + +
+each(callback) =>
false
error
(message, options) – Returns a CssSyntaxError
instance containing the original position
+of the node in the source, showing line and column numbers and also
+a small excerpt to facilitate debugging.
+ +If present, an input source map will be used to get the original position +of the source, even from a previous compilation step +(e.g., from Sass compilation). + +This method produces very useful error messages. + +```js +if (!variables[name]) { + throw decl.error(`Unknown variable ${name}`, { word: name }) + // CssSyntaxError: postcss-vars:a.sass:4:3: Unknown variable $black + // color: $black + // a + // ^ + // background: white +} +``` + +
+message
– Error description.string
options
error(message, options) =>
every
(condition) – Returns true
if callback returns true
+for all of the container’s children.
+ +```js +const noPrefixes = rule.every(i => i.prop[0] !== '-') +``` + +
+condition
(node, index, nodes) number#
index
condition(node, index, nodes) =>
every(condition) =>
index
(child) – Returns a child
’s index within the Container#nodes
array.
+ +```js +rule.index(rule.nodes[2]) //=> 2 +``` + +
+child
– Child of the current container.number | Child
index(child) =>
insertAfter
(oldNode, newNode) – Insert new node after old node within the container. string | string [] | Child | Child [] | ChildProps | ChildProps []#
newNode
– New node.
insertAfter(oldNode, newNode) =>
insertBefore
(oldNode, newNode) – Insert new node before old node within the container.
+ +```js +rule.insertBefore(decl, decl.clone({ prop: '-webkit-' + decl.prop })) +``` + +
+oldNode
– Child or child’s index.number | Child
newNode
– New node.string | string [] | Child | Child [] | ChildProps | ChildProps []
insertBefore(oldNode, newNode) =>
next
() – Returns the next child of the node’s parent.
+Returns undefined
if the current node is the last child.
+ +```js +if (comment.text === 'delete next') { + const next = comment.next() + if (next) { + next.remove() + } +} +``` + +
+next() =>
positionBy
(opts) – Get the position for a word or an index inside the node. Pick<WarningOptions, #
opts
– Options."word"
| "index"
>
positionBy(opts) =>
positionInside
(index) – Convert string index to line/column. number#
index
– The symbol number in the node’s string.
positionInside(index) =>
prepend
(nodes) – Inserts new nodes to the start of the container.
+ +```js +const decl1 = new Declaration({ prop: 'color', value: 'black' }) +const decl2 = new Declaration({ prop: 'background-color', value: 'white' }) +rule.prepend(decl1, decl2) + +root.append({ name: 'charset', params: '"UTF-8"' }) // at-rule +root.append({ selector: 'a' }) // rule +rule.append({ prop: 'color', value: 'black' }) // declaration +rule.append({ text: 'Comment' }) // comment + +root.append('a {}') +root.first.append('color: black; z-index: 1') +``` + +
+nodes
– New nodes.string | string [] | default | ChildProps | default [] | ChildProps [] []
prepend(nodes) =>
prev
() – Returns the previous child of the node’s parent.
+Returns undefined
if the current node is the first child.
+ +```js +const annotation = decl.prev() +if (annotation.type === 'comment') { + readAnnotation(annotation.text) +} +``` + +
+prev() =>
push
(child) – Add child to the end of the node.
+ +```js +rule.push(new Declaration({ prop: 'color', value: 'black' })) +``` + +
+child
– New node.push(child) =>
rangeBy
(opts) – Get the range for a word or start and end index inside the node.
+The start index is inclusive; the end index is exclusive. Pick<WarningOptions, #
opts
– Options."word"
| "index"
| "endIndex"
>
rangeBy(opts) =>
raw
(prop, defaultType) – Returns a Node#raws
value. If the node is missing
+the code style property (because the node was manually built or cloned),
+PostCSS will try to autodetect the code style property by looking
+at other nodes in the tree.
+ +```js +const root = postcss.parse('a { background: white }') +root.nodes[0].append({ prop: 'color', value: 'black' }) +root.nodes[0].nodes[1].raws.before //=> undefined +root.nodes[0].nodes[1].raw('before') //=> ' ' +``` + +
+prop
– Name of code style property.string
defaultType
– Name of default value, it can be missed
+if the value is the same as prop.string
raw(prop, defaultType) =>
remove
() – Removes the node from its parent and cleans the parent properties
+from the node and its children.
+ +```js +if (decl.prop.match(/^-webkit-/)) { + decl.remove() +} +``` + +
+remove() =>
removeAll
() – Removes all children from the container
+and cleans their parent properties.
+ +```js +rule.removeAll() +rule.nodes.length //=> 0 +``` + +
+removeAll() =>
removeChild
(child) – Removes node from the container and cleans the parent properties
+from the node and its children.
+ +```js +rule.nodes.length //=> 5 +rule.removeChild(decl) +rule.nodes.length //=> 4 +decl.parent //=> undefined +``` + +
+child
– Child or child’s index.number | Child
removeChild(child) =>
replaceValues
(pattern, options, replaced) – Passes all declaration values within the container that match pattern
+through callback, replacing those values with the returned result
+of callback.
+ +This method is useful if you are using a custom unit or function +and need to iterate through all values. + +```js +root.replaceValues(/\d+rem/, { fast: 'rem' }, string => { + return 15 * parseInt(string) + 'px' +}) +``` + +
+pattern
– Replace pattern.string | RegExp
options
replaceValues(pattern, options, replaced) =>
pattern
string | RegExp
replaced
string |
replaceValues(pattern, replaced) =>
replaceWith
(nodes) – Inserts node(s) before the current node and removes the current node.
+ +```js +AtRule: { + mixin: + ; + ;(atrule => { + atrule.replaceWith(mixinRules[atrule.params]) + }) +} +``` + +
+nodes
– Mode(s) to replace current one.ChildNode | ChildNode [] | ChildProps | ChildProps [] []
replaceWith(nodes) =>
root
() – Finds the Root instance of the node’s tree.
+ +```js +root.nodes[0].nodes[0].root() === root +``` + +
+root() =>
some
(condition) – Returns true
if callback returns true
for (at least) one
+of the container’s children.
+ +```js +const hasPrefix = rule.some(i => i.prop[0] === '-') +``` + +
+condition
(node, index, nodes) number#
index
condition(node, index, nodes) =>
some(condition) =>
toJSON
() – Fix circular links on JSON.stringify()
.
toJSON() =>
toString
(stringifier) – Returns a CSS string representing the node.
+ +```js +new Rule({ selector: 'a' }).toString() //=> "a {}" +``` + +
+stringifier
– A syntax to use in string generation.toString(stringifier) =>
walk
(callback) – Traverses the container’s descendant nodes, calling callback
+for each node.
+ +Like container.each(), this method is safe to use +if you are mutating arrays during iteration. + +If you only need to iterate through the container’s immediate children, +use `Container#each`. + +```js +root.walk(node => { + // Traverses all descendant nodes. +}) +``` + +
+walk(callback) =>
false
walkAtRules
(nameFilter, callback) – Traverses the container’s descendant nodes, calling callback
+for each at-rule node.
+ +If you pass a filter, iteration will only happen over at-rules +that have matching names. + +Like `Container#each`, this method is safe +to use if you are mutating arrays during iteration. + +```js +root.walkAtRules(rule => { + if (isOld(rule.name)) rule.remove() +}) + +let first = false +root.walkAtRules('charset', rule => { + if (!first) { + first = true + } else { + rule.remove() + } +}) +``` + +
+nameFilter
string | RegExp
walkAtRules(nameFilter, callback) =>
false
walkAtRules(callback) =>
false
walkComments
(callback) – Traverses the container’s descendant nodes, calling callback
+for each comment node.
+ +Like `Container#each`, this method is safe +to use if you are mutating arrays during iteration. + +```js +root.walkComments(comment => { + comment.remove() +}) +``` + +
+callback
(comment, indexed) number#
indexed
callback(comment, indexed) =>
false
| voidwalkComments(callback) =>
false
callback
(comment, indexed) number#
indexed
callback(comment, indexed) =>
false
| voidwalkComments(callback) =>
false
walkDecls
(propFilter, callback) – Traverses the container’s descendant nodes, calling callback
+for each declaration node.
+ +If you pass a filter, iteration will only happen over declarations +with matching properties. + +```js +root.walkDecls(decl => { + checkPropertySupport(decl.prop) +}) + +root.walkDecls('border-radius', decl => { + decl.remove() +}) + +root.walkDecls(/^background/, decl => { + decl.value = takeFirstColorFromGradient(decl.value) +}) +``` + +Like `Container#each`, this method is safe +to use if you are mutating arrays during iteration. + +
+propFilter
string | RegExp
walkDecls(propFilter, callback) =>
false
walkDecls(callback) =>
false
walkRules
(selectorFilter, callback) – Traverses the container’s descendant nodes, calling callback
+for each rule node.
+ +If you pass a filter, iteration will only happen over rules +with matching selectors. + +Like `Container#each`, this method is safe +to use if you are mutating arrays during iteration. + +```js +const selectors = [] +root.walkRules(rule => { + selectors.push(rule.selector) +}) +console.log(`Your CSS uses ${selectors.length} selectors`) +``` + +
+selectorFilter
string | RegExp
walkRules(selectorFilter, callback) =>
false
walkRules(callback) =>
false
warn
(result, text, opts) – This method is provided as a convenience wrapper for Result#warn
.
+ +```js +Declaration: { + bad: + ; + ;((decl, { result }) => { + decl.warn(result, 'Deprecated property bad') + }) +} +``` + +
+result
– The Result
instance that will receive the warning.text
– Warning message.string
opts
– Warning Options.
+warn(result, text, opts) =>
default
– Provides the result of the PostCSS transformations.+ +A Result instance is returned by `LazyResult#then` +or `Root#toResult` methods. + +```js +postcss([autoprefixer]).process(css).then(result => { + console.log(result.css) +}) +``` + +```js +const result2 = postcss.parse(css).toResult() +``` + +
+ string
+
+```js
+postcss.parse('a{}').toResult().css //=> "a{}"
+```
+
+
+
+```js
+result.map.toJSON() //=> { version: 3, file: 'a.css', … }
+```
+
+```js
+if (result.map) {
+ fs.writeFileSync(result.opts.to + '.map', result.map.toString())
+}
+```
+
+ Message []
+
+```js
+AtRule: {
+ import: (atRule, { result }) {
+ const importedFile = parseImport(atRule)
+ result.messages.push({
+ type: 'dependency',
+ plugin: 'postcss-import',
+ file: importedFile,
+ parent: result.opts.from
+ })
+ }
+}
+```
+
+
+
+```js
+root.toResult(opts).opts === opts
+```
+
+
+
+```js
+for (const plugin of result.processor.plugins) {
+ if (plugin.postcssPlugin === 'postcss-bad') {
+ throw 'postcss-good is incompatible with postcss-bad'
+ }
+})
+```
+
+
+
+```js
+result + '' === result.css
+```
+
+ toString() => #
src/.fastpm/-/postcss@8.4.14/lib/result.d.ts#L117 css
– A CSS string representing of Result#root
.#
src/.fastpm/-/postcss@8.4.14/lib/result.d.ts#L138 lastPlugin
– Last runned PostCSS plugin.#
src/.fastpm/-/postcss@8.4.14/lib/result.d.ts#L133 map
– An instance of SourceMapGenerator
class from the source-map
library,
+representing changes to the Result#root
instance.
#
src/.fastpm/-/postcss@8.4.14/lib/result.d.ts#L89 messages
– Contains messages from plugins (e.g., warnings or custom messages).
+Each message should have type and plugin properties.#
src/.fastpm/-/postcss@8.4.14/lib/result.d.ts#L108 opts
– Options from the Processor#process
or Root#toResult
call
+that produced this Result instance.]
#
src/.fastpm/-/postcss@8.4.14/lib/result.d.ts#L69 processor
– The Processor instance used for this transformation.
#
src/.fastpm/-/postcss@8.4.14/lib/result.d.ts#L98 root
– Root node after all transformations.#
src/.fastpm/-/postcss@8.4.14/lib/result.d.ts#L166 toString
() – Returns for Result#css
content.
string
warn
(message, options) – Creates an instance of Warning
and adds it to Result#messages
.
+ +```js +if (decl.important) { + result.warn('Avoid !important', { node: decl, word: '!important' }) +} +``` + +
+message
string
options
warn(message, options) =>
warnings
() – Returns warnings from plugins. Filters Warning
instances
+from Result#messages
.
+ +```js +result.warnings().forEach(warn => { + console.warn(warn.toString()) +}) +``` + +
+warnings() =>
default
– A Promise proxy for the result of PostCSS transformations.+ +A `LazyResult` instance is returned by `Processor#process`. + +```js +const lazy = postcss([autoprefixer]).process(css) +``` + +
+
+
+It implements standard Promise API.
+
+```js
+postcss([autoprefixer]).process(css).then(result => {
+ console.log(result.css)
+}).catch(error => {
+ console.error(error)
+})
+```
+
+#
src/.fastpm/-/postcss@8.4.14/lib/lazy-result.d.ts#L46 catch
# (onrejected) – Attaches a callback for only the rejection of the Promise.
<TResult>(onrejected) =>
finally
+
+It implements standard Promise API.
+
+```js
+postcss([autoprefixer]).process(css).finally(() => {
+ console.log('processing ended')
+})
+```
+
+# (onfinally) – Attaches a callback that is invoked when the Promise is settled (fulfilled or rejected). The
+resolved value cannot be modified from the callback.
(onfinally) =>
then
+
+It implements standard Promise API.
+
+```js
+postcss([autoprefixer]).process(css, { from: cssPath }).then(result => {
+ console.log(result.css)
+})
+```
+
+# (onfulfilled, onrejected) – Attaches callbacks for the resolution and/or rejection of the Promise.
onrejected
– The callback to execute when the Promise is rejected.null
|
<TResult1, TResult2>(onfulfilled, onrejected) =>
[toStringTag]
content
css
map
messages
opts
processor
root
async
() – Run plugin in async way and return Result
.
async() =>
sync
() – Run plugin in sync way and return Result
.
sync() =>
toString
() – Alias for the LazyResult#css
property.
+ +```js +lazy + '' === lazy.css +``` + +
+toString() =>
warnings
() – Processes input CSS through synchronous plugins
+and calls Result#warnings
.
warnings() =>
default
– A Promise proxy for the result of PostCSS transformations.
+This lazy result instance doesn't parse css unless NoWorkResult#root
or Result#root
+are accessed. See the example below for details.
+A NoWork
instance is returned by Processor#process
ONLY when no plugins defined.+ +```js +const noWorkResult = postcss().process(css) // No plugins are defined. +// CSS is not parsed +let root = noWorkResult.root // now css is parsed because we accessed the root +``` + +
+
<TResult>(onrejected) =>
finally
(onfinally) =>
then
onrejected
– The callback to execute when the Promise is rejected.null
|
<TResult1, TResult2>(onfulfilled, onrejected) =>
[toStringTag]
content
css
map
messages
opts
processor
root
async
()
async() =>
sync
()
sync() =>
toString
()
toString() =>
warnings
()
warnings() =>
default
– The CSS parser throws this error for broken CSS.+ +Custom parsers can throw this error for broken custom syntax using +the `Node#error` method. + +PostCSS will use the input source map to detect the original error location. +If you wrote a Sass file, compiled it to CSS and then parsed it with PostCSS, +PostCSS will show the original position in the Sass file. + +If you need the position in the PostCSS input +(e.g., to debug the previous compiler), use `error.input.file`. + +```js +// Raising error from plugin +throw node.error('Unknown variable', { plugin: 'postcss-vars' }) +``` + +```js +// Catching and checking syntax error +try { + postcss.parse('a{') +} catch (error) { + if (error.name === 'CssSyntaxError') { + error //=> CssSyntaxError + } +} +``` + +
+ string number | RangePosition number | RangePosition string string string number
+
+```js
+error.column //=> 1
+error.input.column //=> 4
+```
+
+PostCSS will use the input source map to detect the original location.
+If you need the position in the PostCSS input, use `error.input.column`.
+
+ number
+
+```js
+error.endColumn //=> 1
+error.input.endColumn //=> 4
+```
+
+PostCSS will use the input source map to detect the original location.
+If you need the position in the PostCSS input, use `error.input.endColumn`.
+
+ number
+
+```js
+error.endLine //=> 3
+error.input.endLine //=> 4
+```
+
+PostCSS will use the input source map to detect the original location.
+If you need the position in the PostCSS input, use `error.input.endLine`.
+
+ string
+
+```js
+error.file //=> 'a.sass'
+error.input.file //=> 'a.css'
+```
+
+PostCSS will use the input source map to detect the original location.
+If you need the position in the PostCSS input, use `error.input.file`.
+
+
+
+```js
+error.input.file //=> 'a.css'
+error.file //=> 'a.sass'
+```
+
+ number
+
+```js
+error.line //=> 2
+error.input.line //=> 4
+```
+
+PostCSS will use the input source map to detect the original location.
+If you need the position in the PostCSS input, use `error.input.line`.
+
+ string
+
+```js
+error.message //=> 'a.css:1:1: Unclosed block'
+```
+
+
+
+```js
+if (error.name === 'CssSyntaxError') {
+ error //=> CssSyntaxError
+}
+```
+
+ string
+
+```js
+error.plugin //=> 'postcss-vars'
+```
+
+ string
+
+```js
+error.message //=> 'Unclosed block'
+```
+
+ string
+
+```js
+error.source //=> 'a { b {} }'
+error.input.source //=> 'a b { }'
+```
+
+
+
+If the CSS has an input source map without `sourceContent`,
+this method will return an empty string.
+
+```js
+error.showSourceCode() //=> " 4 | }
+// 5 | a {
+// > 6 | bad
+// | ^
+// 7 | }
+// 8 | b {"
+```
+
+ boolean showSourceCode(color) => #
src/.fastpm/-/postcss@8.4.14/lib/css-syntax-error.d.ts#L60 constructor
(message, lineOrStartPos, columnOrEndPos, source, file, plugin) – Instantiates a CSS syntax error. Can be instantiated for a single position
+or for a range.
#
new default
() – Instantiates a CSS syntax error. Can be instantiated for a single position
+or for a range.
#
message
– Error message.#
lineOrStartPos
– If for a single position, the line number, or if for
+a range, the inclusive start position of the error.#
columnOrEndPos
– If for a single position, the column number, or if for
+a range, the exclusive end position of the error.#
source
– Source code of the broken file.#
file
– Absolute path to the broken file.#
plugin
– PostCSS plugin name, if error came from plugin.
+#
src/.fastpm/-/postcss@8.4.14/lib/css-syntax-error.d.ts#L141 column
– Source column of the error.#
src/.fastpm/-/postcss@8.4.14/lib/css-syntax-error.d.ts#L169 endColumn
– Source column of the error's end, exclusive. Provided if the error pertains
+to a range.#
src/.fastpm/-/postcss@8.4.14/lib/css-syntax-error.d.ts#L155 endLine
– Source line of the error's end, exclusive. Provided if the error pertains
+to a range.#
src/.fastpm/-/postcss@8.4.14/lib/css-syntax-error.d.ts#L115 file
– Absolute path to the broken file.#
src/.fastpm/-/postcss@8.4.14/lib/css-syntax-error.d.ts#L202 input
– Input object with PostCSS internal information
+about input file. If input has source map
+from previous tool, PostCSS will use origin
+(for example, Sass) source. You can use this
+object to get PostCSS input source.
#
src/.fastpm/-/postcss@8.4.14/lib/css-syntax-error.d.ts#L128 line
– Source line of the error.#
src/.fastpm/-/postcss@8.4.14/lib/css-syntax-error.d.ts#L102 message
– Full error text in the GNU error format
+with plugin, file, line and column.#
src/.fastpm/-/postcss@8.4.14/lib/css-syntax-error.d.ts#L83 name
– Always equal to 'CssSyntaxError'
. You should always check error type
+by error.name === 'CssSyntaxError'
+instead of error instanceof CssSyntaxError
,
+because npm could have several PostCSS versions."CssSyntaxError"
#
src/.fastpm/-/postcss@8.4.14/lib/css-syntax-error.d.ts#L188 plugin
– Plugin name, if error came from plugin.#
src/.fastpm/-/postcss@8.4.14/lib/css-syntax-error.d.ts#L92 reason
– Error message.#
src/.fastpm/-/postcss@8.4.14/lib/css-syntax-error.d.ts#L179 source
– Source code of the broken file.#
src/.fastpm/-/postcss@8.4.14/lib/css-syntax-error.d.ts#L238 showSourceCode
(color) – Returns a few lines of CSS source that caused the error.
#
color
– Whether arrow will be colored red by terminal
+color codes. By default, PostCSS will detect
+color support by process.stdout.isTTY
+and process.env.NODE_DISABLE_COLORS
.string
toString
() – Returns error position, message and source code of the broken part.
+ +```js +error.toString() //=> "CssSyntaxError: app.css:1:1: Unclosed block +// > 1 | a { +// | ^" +``` + +
+toString() =>
default
– Represents a plugin’s warning. It can be created using Node#warn
.+ +```js +if (decl.important) { + decl.warn(result, 'Avoid !important', { word: '!important' }) +} +``` + +
+ number
+
+```js
+warning.column //=> 6
+```
+
+ number
+
+```js
+warning.endColumn //=> 4
+```
+
+ number
+
+```js
+warning.endLine //=> 6
+```
+
+ number
+
+```js
+warning.line //=> 5
+```
+
+
+
+```js
+warning.node.toString() //=> 'color: white !important'
+```
+
+ string
+
+```js
+warning.plugin //=> 'postcss-important'
+```
+
+ string
+
+```js
+warning.text //=> 'Try to avoid !important'
+```
+
+
+
+```js
+warning.toString() //=> 'postcss-lint:a.css:10:14: Avoid !important'
+```
+
+ toString() => #
src/.fastpm/-/postcss@8.4.14/lib/warning.d.ts#L126 constructor
(text, opts)
#
src/.fastpm/-/postcss@8.4.14/lib/warning.d.ts#L102 column
– Column for inclusive start position in the input file with this warning’s source.#
src/.fastpm/-/postcss@8.4.14/lib/warning.d.ts#L120 endColumn
– Column for exclusive end position in the input file with this warning’s source.#
src/.fastpm/-/postcss@8.4.14/lib/warning.d.ts#L111 endLine
– Line for exclusive end position in the input file with this warning’s source.#
src/.fastpm/-/postcss@8.4.14/lib/warning.d.ts#L93 line
– Line for inclusive start position in the input file with this warning’s source.#
src/.fastpm/-/postcss@8.4.14/lib/warning.d.ts#L84 node
– Contains the CSS node that caused the warning.
#
src/.fastpm/-/postcss@8.4.14/lib/warning.d.ts#L75 plugin
– The name of the plugin that created this warning.
+When you call Node#warn
it will fill this property automatically.#
src/.fastpm/-/postcss@8.4.14/lib/warning.d.ts#L65 text
– The warning message.#
src/.fastpm/-/postcss@8.4.14/lib/warning.d.ts#L56 type
– Type to filter warnings from Result#messages
.
+Always equal to "warning"
."warning"
#
src/.fastpm/-/postcss@8.4.14/lib/warning.d.ts#L137 toString
() – Returns a warning position and message.
string
default
– All node classes inherit the following common methods.+ +You should not extend this classes to create AST for selector or value +parser. + +
+ any
+
+Every parser saves its own properties,
+but the default CSS parser uses:
+
+- `before`: the space symbols before the node. It also stores `*`
+ and `_` symbols before the declaration (IE hack).
+- `after`: the space symbols after the last child of the node
+ to the end of the node.
+- `between`: the symbols between the property and value
+ for declarations, selector and `{` for rules, or last parameter
+ and `{` for at-rules.
+- `semicolon`: contains true if the last child has
+ an (optional) semicolon.
+- `afterName`: the space between the at-rule name and its parameters.
+- `left`: the space symbols between `/*` and the comment’s text.
+- `right`: the space symbols between the comment’s text
+ and
+
+The property is used in source map generation.
+
+If you create a node manually (e.g., with `postcss.decl()`),
+that node will not have a `source` property and will be absent
+from the source map. For this reason, the plugin developer should
+consider cloning nodes to create new ones (in which case the new node’s
+source will reference the original, cloned node) or setting
+the `source` property manually.
+
+```js
+decl.source.input.from //=> '/home/ai/a.sass'
+decl.source.start //=> { line: 10, column: 2 }
+decl.source.end //=> { line: 10, column: 12 }
+```
+
+```js
+// Bad
+const prefixed = postcss.decl({
+ prop: '-moz-' + decl.prop,
+ value: decl.value,
+})
+
+// Good
+const prefixed = decl.clone({ prop: '-moz-' + decl.prop })
+```
+
+```js
+if (atrule.name === 'add-link') {
+ const rule = postcss.rule({ selector: 'a', source: atrule.source })
+ atrule.parent.insertBefore(atrule, rule)
+}
+```
+
+ string
+
+```js
+new Declaration({ prop: 'color', value: 'black' }).type //=> 'decl'
+```
+
+
+
+Just alias for `node.parent.insertAfter(node, add)`.
+
+```js
+decl.after('color: black')
+```
+
+ string | default | ChildProps | default [] after(newNode) => #
src/.fastpm/-/postcss@8.4.14/lib/node.d.ts#L118 parent
– The node’s parent node.#
src/.fastpm/-/postcss@8.4.14/lib/node.d.ts#L191 raws
– Information to generate byte-to-byte equal node string as it was
+in the origin input.*/
.
+- `important`: the content of the important statement,
+ if it is not just `!important`.
+
+PostCSS cleans selectors, declaration values and at-rule parameters
+from comments and extra spaces, but it stores origin content in raws
+properties. As such, if you don’t change a declaration’s value,
+PostCSS will use the raw value with comments.
+
+```js
+const root = postcss.parse('a {\n color:black\n}')
+root.first.first.raws //=> { before: '\n ', between: ':' }
+```
+
+#
src/.fastpm/-/postcss@8.4.14/lib/node.d.ts#L156 source
– The input source of the node.
#
src/.fastpm/-/postcss@8.4.14/lib/node.d.ts#L109 type
– tring representing the node’s type. Possible values are root
, atrule
,
+rule
, decl
, or comment
.#
src/.fastpm/-/postcss@8.4.14/lib/node.d.ts#L401 after
(newNode) – Insert new node after current node to current node’s parent.
#
newNode
– New node.
assign
(overrides) – Assigns properties to the current node.
+ +```js +decl.assign({ prop: 'word-wrap', value: 'break-word' }) +``` + +
+overrides
– New properties to override the node.object
assign(overrides) =>
before
(newNode) – Insert new node before current node to current node’s parent.
+ +Just alias for `node.parent.insertBefore(node, add)`. + +```js +decl.before('content: ""') +``` + +
+newNode
– New node.string | default | ChildProps | default []
before(newNode) =>
cleanRaws
(keepBetween) – Clear the code style properties for the node and its children.
+ +```js +node.raws.before //=> ' ' +node.cleanRaws() +node.raws.before //=> undefined +``` + +
+keepBetween
– Keep the raws.between
symbols.
+boolean
cleanRaws(keepBetween) =>
clone
(overrides) – Returns an exact clone of the node.
+ +The resulting cloned node and its (cloned) children will retain +code style properties. + +```js +decl.raws.before //=> "\n " +const cloned = decl.clone({ prop: '-moz-' + decl.prop }) +cloned.raws.before //=> "\n " +cloned.toString() //=> -moz-transform: scale(0) +``` + +
+overrides
– New properties to override in the clone.object
clone(overrides) =>
cloneAfter
(overrides) – Shortcut to clone the node and insert the resulting cloned node
+after the current node. object#
overrides
– New properties to override in the clone.
cloneAfter(overrides) =>
cloneBefore
(overrides) – Shortcut to clone the node and insert the resulting cloned node
+before the current node.
+ +```js +decl.cloneBefore({ prop: '-moz-' + decl.prop }) +``` + +
+overrides
– Mew properties to override in the clone.
+object
cloneBefore(overrides) =>
error
(message, options) – Returns a CssSyntaxError
instance containing the original position
+of the node in the source, showing line and column numbers and also
+a small excerpt to facilitate debugging.
+ +If present, an input source map will be used to get the original position +of the source, even from a previous compilation step +(e.g., from Sass compilation). + +This method produces very useful error messages. + +```js +if (!variables[name]) { + throw decl.error(`Unknown variable ${name}`, { word: name }) + // CssSyntaxError: postcss-vars:a.sass:4:3: Unknown variable $black + // color: $black + // a + // ^ + // background: white +} +``` + +
+message
– Error description.string
options
error(message, options) =>
next
() – Returns the next child of the node’s parent.
+Returns undefined
if the current node is the last child.
+ +```js +if (comment.text === 'delete next') { + const next = comment.next() + if (next) { + next.remove() + } +} +``` + +
+next() =>
positionBy
(opts) – Get the position for a word or an index inside the node. Pick<WarningOptions, #
opts
– Options."word"
| "index"
>
positionBy(opts) =>
positionInside
(index) – Convert string index to line/column. number#
index
– The symbol number in the node’s string.
positionInside(index) =>
prev
() – Returns the previous child of the node’s parent.
+Returns undefined
if the current node is the first child.
+ +```js +const annotation = decl.prev() +if (annotation.type === 'comment') { + readAnnotation(annotation.text) +} +``` + +
+prev() =>
rangeBy
(opts) – Get the range for a word or start and end index inside the node.
+The start index is inclusive; the end index is exclusive. Pick<WarningOptions, #
opts
– Options."word"
| "index"
| "endIndex"
>
rangeBy(opts) =>
raw
(prop, defaultType) – Returns a Node#raws
value. If the node is missing
+the code style property (because the node was manually built or cloned),
+PostCSS will try to autodetect the code style property by looking
+at other nodes in the tree.
+ +```js +const root = postcss.parse('a { background: white }') +root.nodes[0].append({ prop: 'color', value: 'black' }) +root.nodes[0].nodes[1].raws.before //=> undefined +root.nodes[0].nodes[1].raw('before') //=> ' ' +``` + +
+prop
– Name of code style property.string
defaultType
– Name of default value, it can be missed
+if the value is the same as prop.string
raw(prop, defaultType) =>
remove
() – Removes the node from its parent and cleans the parent properties
+from the node and its children.
+ +```js +if (decl.prop.match(/^-webkit-/)) { + decl.remove() +} +``` + +
+remove() =>
replaceWith
(nodes) – Inserts node(s) before the current node and removes the current node.
+ +```js +AtRule: { + mixin: + ; + ;(atrule => { + atrule.replaceWith(mixinRules[atrule.params]) + }) +} +``` + +
+nodes
– Mode(s) to replace current one.ChildNode | ChildNode [] | ChildProps | ChildProps [] []
replaceWith(nodes) =>
root
() – Finds the Root instance of the node’s tree.
+ +```js +root.nodes[0].nodes[0].root() === root +``` + +
+root() =>
toJSON
() – Fix circular links on JSON.stringify()
.
toJSON() =>
toString
(stringifier) – Returns a CSS string representing the node.
+ +```js +new Rule({ selector: 'a' }).toString() //=> "a {}" +``` + +
+stringifier
– A syntax to use in string generation.toString(stringifier) =>
warn
(result, text, opts) – This method is provided as a convenience wrapper for Result#warn
.
+ +```js +Declaration: { + bad: + ; + ;((decl, { result }) => { + decl.warn(result, 'Deprecated property bad') + }) +} +``` + +
+result
– The Result
instance that will receive the warning.text
– Warning message.string
opts
– Warning Options.
+warn(result, text, opts) =>
default
– Represents a CSS declaration.+ +```js +Once (root, { Declaration }) { + let color = new Declaration({ prop: 'color', value: 'black' }) + root.append(color) +} +``` + +```js +const root = postcss.parse('a { color: black }') +const decl = root.first.first +decl.type //=> 'decl' +decl.toString() //=> ' color: black' +``` + +
+ boolean
+
+```js
+const root = postcss.parse('a { color: black !important; color: red }')
+root.first.first.important //=> true
+root.first.last.important //=> undefined
+```
+
+ string
+
+```js
+const root = postcss.parse('a { color: black }')
+const decl = root.first.first
+decl.prop //=> 'color'
+```
+
+
+
+Every parser saves its own properties,
+but the default CSS parser uses:
+
+- `before`: the space symbols before the node. It also stores `*`
+ and `_` symbols before the declaration (IE hack).
+- `after`: the space symbols after the last child of the node
+ to the end of the node.
+- `between`: the symbols between the property and value
+ for declarations, selector and `{` for rules, or last parameter
+ and `{` for at-rules.
+- `semicolon`: contains true if the last child has
+ an (optional) semicolon.
+- `afterName`: the space between the at-rule name and its parameters.
+- `left`: the space symbols between `/*` and the comment’s text.
+- `right`: the space symbols between the comment’s text
+ and
+
+The property is used in source map generation.
+
+If you create a node manually (e.g., with `postcss.decl()`),
+that node will not have a `source` property and will be absent
+from the source map. For this reason, the plugin developer should
+consider cloning nodes to create new ones (in which case the new node’s
+source will reference the original, cloned node) or setting
+the `source` property manually.
+
+```js
+decl.source.input.from //=> '/home/ai/a.sass'
+decl.source.start //=> { line: 10, column: 2 }
+decl.source.end //=> { line: 10, column: 12 }
+```
+
+```js
+// Bad
+const prefixed = postcss.decl({
+ prop: '-moz-' + decl.prop,
+ value: decl.value,
+})
+
+// Good
+const prefixed = decl.clone({ prop: '-moz-' + decl.prop })
+```
+
+```js
+if (atrule.name === 'add-link') {
+ const rule = postcss.rule({ selector: 'a', source: atrule.source })
+ atrule.parent.insertBefore(atrule, rule)
+}
+```
+
+
+
+```js
+new Declaration({ prop: 'color', value: 'black' }).type //=> 'decl'
+```
+
+ string
+
+This value will be cleaned of comments. If the source value contained
+comments, those comments will be available in the `raws` property.
+If you have not changed the value, the result of `decl.toString()`
+will include the original raws value (comments and all).
+
+```js
+const root = postcss.parse('a { color: black }')
+const decl = root.first.first
+decl.value //=> 'black'
+```
+
+ boolean
+
+```js
+const root = postcss.parse(':root { --one: 1 }')
+let one = root.first.first
+one.variable //=> true
+```
+
+```js
+const root = postcss.parse('$one: 1')
+let one = root.first
+one.variable //=> true
+```
+
+
+
+Just alias for `node.parent.insertAfter(node, add)`.
+
+```js
+decl.after('color: black')
+```
+
+ string | default | ChildProps | default [] after(newNode) => #
src/.fastpm/-/postcss@8.4.14/lib/declaration.d.ts#L99 important
– true
if the declaration has an !important
annotation.#
src/.fastpm/-/postcss@8.4.14/lib/declaration.d.ts#L60 parent
– The node’s parent node.#
src/.fastpm/-/postcss@8.4.14/lib/declaration.d.ts#L72 prop
– The declaration's property name.#
src/.fastpm/-/postcss@8.4.14/lib/declaration.d.ts#L61 raws
– Information to generate byte-to-byte equal node string as it was
+in the origin input.
*/
.
+- `important`: the content of the important statement,
+ if it is not just `!important`.
+
+PostCSS cleans selectors, declaration values and at-rule parameters
+from comments and extra spaces, but it stores origin content in raws
+properties. As such, if you don’t change a declaration’s value,
+PostCSS will use the raw value with comments.
+
+```js
+const root = postcss.parse('a {\n color:black\n}')
+root.first.first.raws //=> { before: '\n ', between: ':' }
+```
+
+#
src/.fastpm/-/postcss@8.4.14/lib/node.d.ts#L156 source
– The input source of the node.
#
src/.fastpm/-/postcss@8.4.14/lib/declaration.d.ts#L59 type
– tring representing the node’s type. Possible values are root
, atrule
,
+rule
, decl
, or comment
."decl"
#
src/.fastpm/-/postcss@8.4.14/lib/declaration.d.ts#L88 value
– The declaration’s value.#
src/.fastpm/-/postcss@8.4.14/lib/declaration.d.ts#L117 variable
– true
if declaration is declaration of CSS Custom Property
+or Sass variable.#
src/.fastpm/-/postcss@8.4.14/lib/node.d.ts#L401 after
(newNode) – Insert new node after current node to current node’s parent.
#
newNode
– New node.
assign
(overrides) – Assigns properties to the current node.
+ +```js +decl.assign({ prop: 'word-wrap', value: 'break-word' }) +``` + +
+overrides
object | DeclarationProps
assign(overrides) =>
before
(newNode) – Insert new node before current node to current node’s parent.
+ +Just alias for `node.parent.insertBefore(node, add)`. + +```js +decl.before('content: ""') +``` + +
+newNode
– New node.string | default | ChildProps | default []
before(newNode) =>
cleanRaws
(keepBetween) – Clear the code style properties for the node and its children.
+ +```js +node.raws.before //=> ' ' +node.cleanRaws() +node.raws.before //=> undefined +``` + +
+keepBetween
– Keep the raws.between
symbols.
+boolean
cleanRaws(keepBetween) =>
clone
(overrides) – Returns an exact clone of the node.
+ +The resulting cloned node and its (cloned) children will retain +code style properties. + +```js +decl.raws.before //=> "\n " +const cloned = decl.clone({ prop: '-moz-' + decl.prop }) +cloned.raws.before //=> "\n " +cloned.toString() //=> -moz-transform: scale(0) +``` + +
+overrides
Partial<DeclarationProps>
clone(overrides) =>
cloneAfter
(overrides) – Shortcut to clone the node and insert the resulting cloned node
+after the current node. Partial<DeclarationProps>#
overrides
cloneAfter(overrides) =>
cloneBefore
(overrides) – Shortcut to clone the node and insert the resulting cloned node
+before the current node.
+ +```js +decl.cloneBefore({ prop: '-moz-' + decl.prop }) +``` + +
+overrides
Partial<DeclarationProps>
cloneBefore(overrides) =>
error
(message, options) – Returns a CssSyntaxError
instance containing the original position
+of the node in the source, showing line and column numbers and also
+a small excerpt to facilitate debugging.
+ +If present, an input source map will be used to get the original position +of the source, even from a previous compilation step +(e.g., from Sass compilation). + +This method produces very useful error messages. + +```js +if (!variables[name]) { + throw decl.error(`Unknown variable ${name}`, { word: name }) + // CssSyntaxError: postcss-vars:a.sass:4:3: Unknown variable $black + // color: $black + // a + // ^ + // background: white +} +``` + +
+message
– Error description.string
options
error(message, options) =>
next
() – Returns the next child of the node’s parent.
+Returns undefined
if the current node is the last child.
+ +```js +if (comment.text === 'delete next') { + const next = comment.next() + if (next) { + next.remove() + } +} +``` + +
+next() =>
positionBy
(opts) – Get the position for a word or an index inside the node. Pick<WarningOptions, #
opts
– Options."word"
| "index"
>
positionBy(opts) =>
positionInside
(index) – Convert string index to line/column. number#
index
– The symbol number in the node’s string.
positionInside(index) =>
prev
() – Returns the previous child of the node’s parent.
+Returns undefined
if the current node is the first child.
+ +```js +const annotation = decl.prev() +if (annotation.type === 'comment') { + readAnnotation(annotation.text) +} +``` + +
+prev() =>
rangeBy
(opts) – Get the range for a word or start and end index inside the node.
+The start index is inclusive; the end index is exclusive. Pick<WarningOptions, #
opts
– Options."word"
| "index"
| "endIndex"
>
rangeBy(opts) =>
raw
(prop, defaultType) – Returns a Node#raws
value. If the node is missing
+the code style property (because the node was manually built or cloned),
+PostCSS will try to autodetect the code style property by looking
+at other nodes in the tree.
+ +```js +const root = postcss.parse('a { background: white }') +root.nodes[0].append({ prop: 'color', value: 'black' }) +root.nodes[0].nodes[1].raws.before //=> undefined +root.nodes[0].nodes[1].raw('before') //=> ' ' +``` + +
+prop
– Name of code style property.string
defaultType
– Name of default value, it can be missed
+if the value is the same as prop.string
raw(prop, defaultType) =>
remove
() – Removes the node from its parent and cleans the parent properties
+from the node and its children.
+ +```js +if (decl.prop.match(/^-webkit-/)) { + decl.remove() +} +``` + +
+remove() =>
replaceWith
(nodes) – Inserts node(s) before the current node and removes the current node.
+ +```js +AtRule: { + mixin: + ; + ;(atrule => { + atrule.replaceWith(mixinRules[atrule.params]) + }) +} +``` + +
+nodes
– Mode(s) to replace current one.ChildNode | ChildNode [] | ChildProps | ChildProps [] []
replaceWith(nodes) =>
root
() – Finds the Root instance of the node’s tree.
+ +```js +root.nodes[0].nodes[0].root() === root +``` + +
+root() =>
toJSON
() – Fix circular links on JSON.stringify()
.
toJSON() =>
toString
(stringifier) – Returns a CSS string representing the node.
+ +```js +new Rule({ selector: 'a' }).toString() //=> "a {}" +``` + +
+stringifier
– A syntax to use in string generation.toString(stringifier) =>
warn
(result, text, opts) – This method is provided as a convenience wrapper for Result#warn
.
+ +```js +Declaration: { + bad: + ; + ;((decl, { result }) => { + decl.warn(result, 'Deprecated property bad') + }) +} +``` + +
+result
– The Result
instance that will receive the warning.text
– Warning message.string
opts
– Warning Options.
+warn(result, text, opts) =>
default
– Represents a CSS rule: a selector followed by a declaration block.+ +```js +Once (root, { Rule }) { + let a = new Rule({ selector: 'a' }) + a.append(…) + root.append(a) +} +``` + +```js +const root = postcss.parse('a{}') +const rule = root.first +rule.type //=> 'rule' +rule.toString() //=> 'a{}' +``` + +
+ ChildNode []
+
+```js
+const root = postcss.parse('a { color: black }')
+root.nodes.length //=> 1
+root.nodes[0].selector //=> 'a'
+root.nodes[0].nodes[0].prop //=> 'color'
+```
+
+
+
+Every parser saves its own properties,
+but the default CSS parser uses:
+
+- `before`: the space symbols before the node. It also stores `*`
+ and `_` symbols before the declaration (IE hack).
+- `after`: the space symbols after the last child of the node
+ to the end of the node.
+- `between`: the symbols between the property and value
+ for declarations, selector and `{` for rules, or last parameter
+ and `{` for at-rules.
+- `semicolon`: contains true if the last child has
+ an (optional) semicolon.
+- `afterName`: the space between the at-rule name and its parameters.
+- `left`: the space symbols between `/*` and the comment’s text.
+- `right`: the space symbols between the comment’s text
+ and string
+
+```js
+const root = postcss.parse('a, b { }')
+const rule = root.first
+rule.selector //=> 'a, b'
+```
+
+ string []
+
+```js
+const root = postcss.parse('a, b { }')
+const rule = root.first
+
+rule.selector //=> 'a, b'
+rule.selectors //=> ['a', 'b']
+
+rule.selectors = ['a', 'strong']
+rule.selector //=> 'a, strong'
+```
+
+
+
+The property is used in source map generation.
+
+If you create a node manually (e.g., with `postcss.decl()`),
+that node will not have a `source` property and will be absent
+from the source map. For this reason, the plugin developer should
+consider cloning nodes to create new ones (in which case the new node’s
+source will reference the original, cloned node) or setting
+the `source` property manually.
+
+```js
+decl.source.input.from //=> '/home/ai/a.sass'
+decl.source.start //=> { line: 10, column: 2 }
+decl.source.end //=> { line: 10, column: 12 }
+```
+
+```js
+// Bad
+const prefixed = postcss.decl({
+ prop: '-moz-' + decl.prop,
+ value: decl.value,
+})
+
+// Good
+const prefixed = decl.clone({ prop: '-moz-' + decl.prop })
+```
+
+```js
+if (atrule.name === 'add-link') {
+ const rule = postcss.rule({ selector: 'a', source: atrule.source })
+ atrule.parent.insertBefore(atrule, rule)
+}
+```
+
+
+
+```js
+new Declaration({ prop: 'color', value: 'black' }).type //=> 'decl'
+```
+
+
+
+Just alias for `node.parent.insertAfter(node, add)`.
+
+```js
+decl.after('color: black')
+```
+
+ string | default | ChildProps | default [] after(newNode) => #
src/.fastpm/-/postcss@8.4.14/lib/container.d.ts#L43 nodes
– An array containing the container’s children.#
src/.fastpm/-/postcss@8.4.14/lib/rule.d.ts#L68 parent
– The node’s parent node.#
src/.fastpm/-/postcss@8.4.14/lib/rule.d.ts#L69 raws
– Information to generate byte-to-byte equal node string as it was
+in the origin input.
*/
.
+- `important`: the content of the important statement,
+ if it is not just `!important`.
+
+PostCSS cleans selectors, declaration values and at-rule parameters
+from comments and extra spaces, but it stores origin content in raws
+properties. As such, if you don’t change a declaration’s value,
+PostCSS will use the raw value with comments.
+
+```js
+const root = postcss.parse('a {\n color:black\n}')
+root.first.first.raws //=> { before: '\n ', between: ':' }
+```
+
+#
src/.fastpm/-/postcss@8.4.14/lib/rule.d.ts#L80 selector
– The rule’s full selector represented as a string.#
src/.fastpm/-/postcss@8.4.14/lib/rule.d.ts#L97 selectors
– An array containing the rule’s individual selectors.
+Groups of selectors are split at commas.#
src/.fastpm/-/postcss@8.4.14/lib/node.d.ts#L156 source
– The input source of the node.
#
src/.fastpm/-/postcss@8.4.14/lib/rule.d.ts#L67 type
– tring representing the node’s type. Possible values are root
, atrule
,
+rule
, decl
, or comment
."rule"
#
src/.fastpm/-/postcss@8.4.14/lib/node.d.ts#L401 after
(newNode) – Insert new node after current node to current node’s parent.
#
newNode
– New node.
append
(nodes) – Inserts new nodes to the end of the container.
+ +```js +const decl1 = new Declaration({ prop: 'color', value: 'black' }) +const decl2 = new Declaration({ prop: 'background-color', value: 'white' }) +rule.append(decl1, decl2) + +root.append({ name: 'charset', params: '"UTF-8"' }) // at-rule +root.append({ selector: 'a' }) // rule +rule.append({ prop: 'color', value: 'black' }) // declaration +rule.append({ text: 'Comment' }) // comment + +root.append('a {}') +root.first.append('color: black; z-index: 1') +``` + +
+nodes
– New nodes.string | string [] | default | ChildProps | default [] | ChildProps [] []
append(nodes) =>
assign
(overrides) – Assigns properties to the current node.
+ +```js +decl.assign({ prop: 'word-wrap', value: 'break-word' }) +``` + +
+overrides
object | RuleProps
assign(overrides) =>
before
(newNode) – Insert new node before current node to current node’s parent.
+ +Just alias for `node.parent.insertBefore(node, add)`. + +```js +decl.before('content: ""') +``` + +
+newNode
– New node.string | default | ChildProps | default []
before(newNode) =>
cleanRaws
(keepBetween) – Clear the code style properties for the node and its children.
+ +```js +node.raws.before //=> ' ' +node.cleanRaws() +node.raws.before //=> undefined +``` + +
+keepBetween
– Keep the raws.between
symbols.
+boolean
cleanRaws(keepBetween) =>
clone
(overrides) – Returns an exact clone of the node.
+ +The resulting cloned node and its (cloned) children will retain +code style properties. + +```js +decl.raws.before //=> "\n " +const cloned = decl.clone({ prop: '-moz-' + decl.prop }) +cloned.raws.before //=> "\n " +cloned.toString() //=> -moz-transform: scale(0) +``` + +
+overrides
Partial<RuleProps>
clone(overrides) =>
cloneAfter
(overrides) – Shortcut to clone the node and insert the resulting cloned node
+after the current node.
cloneAfter(overrides) =>
cloneBefore
(overrides) – Shortcut to clone the node and insert the resulting cloned node
+before the current node.
+ +```js +decl.cloneBefore({ prop: '-moz-' + decl.prop }) +``` + +
+overrides
Partial<RuleProps>
cloneBefore(overrides) =>
each
(callback) – Iterates through the container’s immediate children,
+calling callback
for each child.
+ +Returning `false` in the callback will break iteration. + +This method only iterates through the container’s immediate children. +If you need to recursively iterate through all the container’s descendant +nodes, use `Container#walk`. + +Unlike the for `{}`-cycle or `Array#forEach` this iterator is safe +if you are mutating the array of child nodes during iteration. +PostCSS will adjust the current index to match the mutations. + +```js +const root = postcss.parse('a { color: black; z-index: 1 }') +const rule = root.first + +for (const decl of rule.nodes) { + decl.cloneBefore({ prop: '-webkit-' + decl.prop }) + // Cycle will be infinite, because cloneBefore moves the current node + // to the next index +} + +rule.each(decl => { + decl.cloneBefore({ prop: '-webkit-' + decl.prop }) + // Will be executed only for color and z-index +}) +``` + +
+each(callback) =>
false
error
(message, options) – Returns a CssSyntaxError
instance containing the original position
+of the node in the source, showing line and column numbers and also
+a small excerpt to facilitate debugging.
+ +If present, an input source map will be used to get the original position +of the source, even from a previous compilation step +(e.g., from Sass compilation). + +This method produces very useful error messages. + +```js +if (!variables[name]) { + throw decl.error(`Unknown variable ${name}`, { word: name }) + // CssSyntaxError: postcss-vars:a.sass:4:3: Unknown variable $black + // color: $black + // a + // ^ + // background: white +} +``` + +
+message
– Error description.string
options
error(message, options) =>
every
(condition) – Returns true
if callback returns true
+for all of the container’s children.
+ +```js +const noPrefixes = rule.every(i => i.prop[0] !== '-') +``` + +
+condition
(node, index, nodes) number#
index
condition(node, index, nodes) =>
every(condition) =>
index
(child) – Returns a child
’s index within the Container#nodes
array.
+ +```js +rule.index(rule.nodes[2]) //=> 2 +``` + +
+child
– Child of the current container.number | ChildNode
index(child) =>
insertAfter
(oldNode, newNode) – Insert new node after old node within the container. string | string [] | ChildNode | ChildNode [] | ChildProps | ChildProps []#
newNode
– New node.
insertAfter(oldNode, newNode) =>
insertBefore
(oldNode, newNode) – Insert new node before old node within the container.
+ +```js +rule.insertBefore(decl, decl.clone({ prop: '-webkit-' + decl.prop })) +``` + +
+oldNode
– Child or child’s index.number | ChildNode
newNode
– New node.string | string [] | ChildNode | ChildNode [] | ChildProps | ChildProps []
insertBefore(oldNode, newNode) =>
next
() – Returns the next child of the node’s parent.
+Returns undefined
if the current node is the last child.
+ +```js +if (comment.text === 'delete next') { + const next = comment.next() + if (next) { + next.remove() + } +} +``` + +
+next() =>
positionBy
(opts) – Get the position for a word or an index inside the node. Pick<WarningOptions, #
opts
– Options."word"
| "index"
>
positionBy(opts) =>
positionInside
(index) – Convert string index to line/column. number#
index
– The symbol number in the node’s string.
positionInside(index) =>
prepend
(nodes) – Inserts new nodes to the start of the container.
+ +```js +const decl1 = new Declaration({ prop: 'color', value: 'black' }) +const decl2 = new Declaration({ prop: 'background-color', value: 'white' }) +rule.prepend(decl1, decl2) + +root.append({ name: 'charset', params: '"UTF-8"' }) // at-rule +root.append({ selector: 'a' }) // rule +rule.append({ prop: 'color', value: 'black' }) // declaration +rule.append({ text: 'Comment' }) // comment + +root.append('a {}') +root.first.append('color: black; z-index: 1') +``` + +
+nodes
– New nodes.string | string [] | default | ChildProps | default [] | ChildProps [] []
prepend(nodes) =>
prev
() – Returns the previous child of the node’s parent.
+Returns undefined
if the current node is the first child.
+ +```js +const annotation = decl.prev() +if (annotation.type === 'comment') { + readAnnotation(annotation.text) +} +``` + +
+prev() =>
push
(child) – Add child to the end of the node.
+ +```js +rule.push(new Declaration({ prop: 'color', value: 'black' })) +``` + +
+child
– New node.push(child) =>
rangeBy
(opts) – Get the range for a word or start and end index inside the node.
+The start index is inclusive; the end index is exclusive. Pick<WarningOptions, #
opts
– Options."word"
| "index"
| "endIndex"
>
rangeBy(opts) =>
raw
(prop, defaultType) – Returns a Node#raws
value. If the node is missing
+the code style property (because the node was manually built or cloned),
+PostCSS will try to autodetect the code style property by looking
+at other nodes in the tree.
+ +```js +const root = postcss.parse('a { background: white }') +root.nodes[0].append({ prop: 'color', value: 'black' }) +root.nodes[0].nodes[1].raws.before //=> undefined +root.nodes[0].nodes[1].raw('before') //=> ' ' +``` + +
+prop
– Name of code style property.string
defaultType
– Name of default value, it can be missed
+if the value is the same as prop.string
raw(prop, defaultType) =>
remove
() – Removes the node from its parent and cleans the parent properties
+from the node and its children.
+ +```js +if (decl.prop.match(/^-webkit-/)) { + decl.remove() +} +``` + +
+remove() =>
removeAll
() – Removes all children from the container
+and cleans their parent properties.
+ +```js +rule.removeAll() +rule.nodes.length //=> 0 +``` + +
+removeAll() =>
removeChild
(child) – Removes node from the container and cleans the parent properties
+from the node and its children.
+ +```js +rule.nodes.length //=> 5 +rule.removeChild(decl) +rule.nodes.length //=> 4 +decl.parent //=> undefined +``` + +
+child
– Child or child’s index.number | ChildNode
removeChild(child) =>
replaceValues
(pattern, options, replaced) – Passes all declaration values within the container that match pattern
+through callback, replacing those values with the returned result
+of callback.
+ +This method is useful if you are using a custom unit or function +and need to iterate through all values. + +```js +root.replaceValues(/\d+rem/, { fast: 'rem' }, string => { + return 15 * parseInt(string) + 'px' +}) +``` + +
+pattern
– Replace pattern.string | RegExp
options
replaceValues(pattern, options, replaced) =>
pattern
string | RegExp
replaced
string |
replaceValues(pattern, replaced) =>
replaceWith
(nodes) – Inserts node(s) before the current node and removes the current node.
+ +```js +AtRule: { + mixin: + ; + ;(atrule => { + atrule.replaceWith(mixinRules[atrule.params]) + }) +} +``` + +
+nodes
– Mode(s) to replace current one.ChildNode | ChildNode [] | ChildProps | ChildProps [] []
replaceWith(nodes) =>
root
() – Finds the Root instance of the node’s tree.
+ +```js +root.nodes[0].nodes[0].root() === root +``` + +
+root() =>
some
(condition) – Returns true
if callback returns true
for (at least) one
+of the container’s children.
+ +```js +const hasPrefix = rule.some(i => i.prop[0] === '-') +``` + +
+condition
(node, index, nodes) number#
index
condition(node, index, nodes) =>
some(condition) =>
toJSON
() – Fix circular links on JSON.stringify()
.
toJSON() =>
toString
(stringifier) – Returns a CSS string representing the node.
+ +```js +new Rule({ selector: 'a' }).toString() //=> "a {}" +``` + +
+stringifier
– A syntax to use in string generation.toString(stringifier) =>
walk
(callback) – Traverses the container’s descendant nodes, calling callback
+for each node.
+ +Like container.each(), this method is safe to use +if you are mutating arrays during iteration. + +If you only need to iterate through the container’s immediate children, +use `Container#each`. + +```js +root.walk(node => { + // Traverses all descendant nodes. +}) +``` + +
+walk(callback) =>
false
walkAtRules
(nameFilter, callback) – Traverses the container’s descendant nodes, calling callback
+for each at-rule node.
+ +If you pass a filter, iteration will only happen over at-rules +that have matching names. + +Like `Container#each`, this method is safe +to use if you are mutating arrays during iteration. + +```js +root.walkAtRules(rule => { + if (isOld(rule.name)) rule.remove() +}) + +let first = false +root.walkAtRules('charset', rule => { + if (!first) { + first = true + } else { + rule.remove() + } +}) +``` + +
+nameFilter
string | RegExp
walkAtRules(nameFilter, callback) =>
false
walkAtRules(callback) =>
false
walkComments
(callback) – Traverses the container’s descendant nodes, calling callback
+for each comment node.
+ +Like `Container#each`, this method is safe +to use if you are mutating arrays during iteration. + +```js +root.walkComments(comment => { + comment.remove() +}) +``` + +
+callback
(comment, indexed) number#
indexed
callback(comment, indexed) =>
false
| voidwalkComments(callback) =>
false
callback
(comment, indexed) number#
indexed
callback(comment, indexed) =>
false
| voidwalkComments(callback) =>
false
walkDecls
(propFilter, callback) – Traverses the container’s descendant nodes, calling callback
+for each declaration node.
+ +If you pass a filter, iteration will only happen over declarations +with matching properties. + +```js +root.walkDecls(decl => { + checkPropertySupport(decl.prop) +}) + +root.walkDecls('border-radius', decl => { + decl.remove() +}) + +root.walkDecls(/^background/, decl => { + decl.value = takeFirstColorFromGradient(decl.value) +}) +``` + +Like `Container#each`, this method is safe +to use if you are mutating arrays during iteration. + +
+propFilter
string | RegExp
walkDecls(propFilter, callback) =>
false
walkDecls(callback) =>
false
walkRules
(selectorFilter, callback) – Traverses the container’s descendant nodes, calling callback
+for each rule node.
+ +If you pass a filter, iteration will only happen over rules +with matching selectors. + +Like `Container#each`, this method is safe +to use if you are mutating arrays during iteration. + +```js +const selectors = [] +root.walkRules(rule => { + selectors.push(rule.selector) +}) +console.log(`Your CSS uses ${selectors.length} selectors`) +``` + +
+selectorFilter
string | RegExp
walkRules(selectorFilter, callback) =>
false
walkRules(callback) =>
false
warn
(result, text, opts) – This method is provided as a convenience wrapper for Result#warn
.
+ +```js +Declaration: { + bad: + ; + ;((decl, { result }) => { + decl.warn(result, 'Deprecated property bad') + }) +} +``` + +
+result
– The Result
instance that will receive the warning.text
– Warning message.string
opts
– Warning Options.
+warn(result, text, opts) =>
default
– Represents an at-rule.+ +```js +Once (root, { AtRule }) { + let media = new AtRule({ name: 'media', params: 'print' }) + media.append(…) + root.append(media) +} +``` + +If it’s followed in the CSS by a {} block, this node will have +a nodes property representing its children. + +```js +const root = postcss.parse('@charset "UTF-8"; @media print {}') + +const charset = root.first +charset.type //=> 'atrule' +charset.nodes //=> undefined + +const media = root.last +media.nodes //=> [] +``` + +
+ string
+
+```js
+const root = postcss.parse('@media print {}')
+media.name //=> 'media'
+const media = root.first
+```
+
+ ChildNode []
+
+```js
+const root = postcss.parse('a { color: black }')
+root.nodes.length //=> 1
+root.nodes[0].selector //=> 'a'
+root.nodes[0].nodes[0].prop //=> 'color'
+```
+
+ string
+
+```js
+const root = postcss.parse('@media print, screen {}')
+const media = root.first
+media.params //=> 'print, screen'
+```
+
+
+
+Every parser saves its own properties,
+but the default CSS parser uses:
+
+- `before`: the space symbols before the node. It also stores `*`
+ and `_` symbols before the declaration (IE hack).
+- `after`: the space symbols after the last child of the node
+ to the end of the node.
+- `between`: the symbols between the property and value
+ for declarations, selector and `{` for rules, or last parameter
+ and `{` for at-rules.
+- `semicolon`: contains true if the last child has
+ an (optional) semicolon.
+- `afterName`: the space between the at-rule name and its parameters.
+- `left`: the space symbols between `/*` and the comment’s text.
+- `right`: the space symbols between the comment’s text
+ and
+
+The property is used in source map generation.
+
+If you create a node manually (e.g., with `postcss.decl()`),
+that node will not have a `source` property and will be absent
+from the source map. For this reason, the plugin developer should
+consider cloning nodes to create new ones (in which case the new node’s
+source will reference the original, cloned node) or setting
+the `source` property manually.
+
+```js
+decl.source.input.from //=> '/home/ai/a.sass'
+decl.source.start //=> { line: 10, column: 2 }
+decl.source.end //=> { line: 10, column: 12 }
+```
+
+```js
+// Bad
+const prefixed = postcss.decl({
+ prop: '-moz-' + decl.prop,
+ value: decl.value,
+})
+
+// Good
+const prefixed = decl.clone({ prop: '-moz-' + decl.prop })
+```
+
+```js
+if (atrule.name === 'add-link') {
+ const rule = postcss.rule({ selector: 'a', source: atrule.source })
+ atrule.parent.insertBefore(atrule, rule)
+}
+```
+
+
+
+```js
+new Declaration({ prop: 'color', value: 'black' }).type //=> 'decl'
+```
+
+
+
+Just alias for `node.parent.insertAfter(node, add)`.
+
+```js
+decl.after('color: black')
+```
+
+ string | default | ChildProps | default [] after(newNode) => #
src/.fastpm/-/postcss@8.4.14/lib/at-rule.d.ts#L87 name
– The at-rule’s name immediately follows the @
.#
src/.fastpm/-/postcss@8.4.14/lib/container.d.ts#L43 nodes
– An array containing the container’s children.#
src/.fastpm/-/postcss@8.4.14/lib/at-rule.d.ts#L99 params
– The at-rule’s parameters, the values that follow the at-rule’s name
+but precede any {} block.#
src/.fastpm/-/postcss@8.4.14/lib/at-rule.d.ts#L75 parent
– The node’s parent node.#
src/.fastpm/-/postcss@8.4.14/lib/at-rule.d.ts#L76 raws
– Information to generate byte-to-byte equal node string as it was
+in the origin input.
*/
.
+- `important`: the content of the important statement,
+ if it is not just `!important`.
+
+PostCSS cleans selectors, declaration values and at-rule parameters
+from comments and extra spaces, but it stores origin content in raws
+properties. As such, if you don’t change a declaration’s value,
+PostCSS will use the raw value with comments.
+
+```js
+const root = postcss.parse('a {\n color:black\n}')
+root.first.first.raws //=> { before: '\n ', between: ':' }
+```
+
+#
src/.fastpm/-/postcss@8.4.14/lib/node.d.ts#L156 source
– The input source of the node.
#
src/.fastpm/-/postcss@8.4.14/lib/at-rule.d.ts#L74 type
– tring representing the node’s type. Possible values are root
, atrule
,
+rule
, decl
, or comment
."atrule"
#
src/.fastpm/-/postcss@8.4.14/lib/node.d.ts#L401 after
(newNode) – Insert new node after current node to current node’s parent.
#
newNode
– New node.
append
(nodes) – Inserts new nodes to the end of the container.
+ +```js +const decl1 = new Declaration({ prop: 'color', value: 'black' }) +const decl2 = new Declaration({ prop: 'background-color', value: 'white' }) +rule.append(decl1, decl2) + +root.append({ name: 'charset', params: '"UTF-8"' }) // at-rule +root.append({ selector: 'a' }) // rule +rule.append({ prop: 'color', value: 'black' }) // declaration +rule.append({ text: 'Comment' }) // comment + +root.append('a {}') +root.first.append('color: black; z-index: 1') +``` + +
+nodes
– New nodes.string | string [] | default | ChildProps | default [] | ChildProps [] []
append(nodes) =>
assign
(overrides) – Assigns properties to the current node.
+ +```js +decl.assign({ prop: 'word-wrap', value: 'break-word' }) +``` + +
+overrides
object | AtRuleProps
assign(overrides) =>
before
(newNode) – Insert new node before current node to current node’s parent.
+ +Just alias for `node.parent.insertBefore(node, add)`. + +```js +decl.before('content: ""') +``` + +
+newNode
– New node.string | default | ChildProps | default []
before(newNode) =>
cleanRaws
(keepBetween) – Clear the code style properties for the node and its children.
+ +```js +node.raws.before //=> ' ' +node.cleanRaws() +node.raws.before //=> undefined +``` + +
+keepBetween
– Keep the raws.between
symbols.
+boolean
cleanRaws(keepBetween) =>
clone
(overrides) – Returns an exact clone of the node.
+ +The resulting cloned node and its (cloned) children will retain +code style properties. + +```js +decl.raws.before //=> "\n " +const cloned = decl.clone({ prop: '-moz-' + decl.prop }) +cloned.raws.before //=> "\n " +cloned.toString() //=> -moz-transform: scale(0) +``` + +
+overrides
Partial<AtRuleProps>
clone(overrides) =>
cloneAfter
(overrides) – Shortcut to clone the node and insert the resulting cloned node
+after the current node. Partial<AtRuleProps>#
overrides
cloneAfter(overrides) =>
cloneBefore
(overrides) – Shortcut to clone the node and insert the resulting cloned node
+before the current node.
+ +```js +decl.cloneBefore({ prop: '-moz-' + decl.prop }) +``` + +
+overrides
Partial<AtRuleProps>
cloneBefore(overrides) =>
each
(callback) – Iterates through the container’s immediate children,
+calling callback
for each child.
+ +Returning `false` in the callback will break iteration. + +This method only iterates through the container’s immediate children. +If you need to recursively iterate through all the container’s descendant +nodes, use `Container#walk`. + +Unlike the for `{}`-cycle or `Array#forEach` this iterator is safe +if you are mutating the array of child nodes during iteration. +PostCSS will adjust the current index to match the mutations. + +```js +const root = postcss.parse('a { color: black; z-index: 1 }') +const rule = root.first + +for (const decl of rule.nodes) { + decl.cloneBefore({ prop: '-webkit-' + decl.prop }) + // Cycle will be infinite, because cloneBefore moves the current node + // to the next index +} + +rule.each(decl => { + decl.cloneBefore({ prop: '-webkit-' + decl.prop }) + // Will be executed only for color and z-index +}) +``` + +
+each(callback) =>
false
error
(message, options) – Returns a CssSyntaxError
instance containing the original position
+of the node in the source, showing line and column numbers and also
+a small excerpt to facilitate debugging.
+ +If present, an input source map will be used to get the original position +of the source, even from a previous compilation step +(e.g., from Sass compilation). + +This method produces very useful error messages. + +```js +if (!variables[name]) { + throw decl.error(`Unknown variable ${name}`, { word: name }) + // CssSyntaxError: postcss-vars:a.sass:4:3: Unknown variable $black + // color: $black + // a + // ^ + // background: white +} +``` + +
+message
– Error description.string
options
error(message, options) =>
every
(condition) – Returns true
if callback returns true
+for all of the container’s children.
+ +```js +const noPrefixes = rule.every(i => i.prop[0] !== '-') +``` + +
+condition
(node, index, nodes) number#
index
condition(node, index, nodes) =>
every(condition) =>
index
(child) – Returns a child
’s index within the Container#nodes
array.
+ +```js +rule.index(rule.nodes[2]) //=> 2 +``` + +
+child
– Child of the current container.number | ChildNode
index(child) =>
insertAfter
(oldNode, newNode) – Insert new node after old node within the container. string | string [] | ChildNode | ChildNode [] | ChildProps | ChildProps []#
newNode
– New node.
insertAfter(oldNode, newNode) =>
insertBefore
(oldNode, newNode) – Insert new node before old node within the container.
+ +```js +rule.insertBefore(decl, decl.clone({ prop: '-webkit-' + decl.prop })) +``` + +
+oldNode
– Child or child’s index.number | ChildNode
newNode
– New node.string | string [] | ChildNode | ChildNode [] | ChildProps | ChildProps []
insertBefore(oldNode, newNode) =>
next
() – Returns the next child of the node’s parent.
+Returns undefined
if the current node is the last child.
+ +```js +if (comment.text === 'delete next') { + const next = comment.next() + if (next) { + next.remove() + } +} +``` + +
+next() =>
positionBy
(opts) – Get the position for a word or an index inside the node. Pick<WarningOptions, #
opts
– Options."word"
| "index"
>
positionBy(opts) =>
positionInside
(index) – Convert string index to line/column. number#
index
– The symbol number in the node’s string.
positionInside(index) =>
prepend
(nodes) – Inserts new nodes to the start of the container.
+ +```js +const decl1 = new Declaration({ prop: 'color', value: 'black' }) +const decl2 = new Declaration({ prop: 'background-color', value: 'white' }) +rule.prepend(decl1, decl2) + +root.append({ name: 'charset', params: '"UTF-8"' }) // at-rule +root.append({ selector: 'a' }) // rule +rule.append({ prop: 'color', value: 'black' }) // declaration +rule.append({ text: 'Comment' }) // comment + +root.append('a {}') +root.first.append('color: black; z-index: 1') +``` + +
+nodes
– New nodes.string | string [] | default | ChildProps | default [] | ChildProps [] []
prepend(nodes) =>
prev
() – Returns the previous child of the node’s parent.
+Returns undefined
if the current node is the first child.
+ +```js +const annotation = decl.prev() +if (annotation.type === 'comment') { + readAnnotation(annotation.text) +} +``` + +
+prev() =>
push
(child) – Add child to the end of the node.
+ +```js +rule.push(new Declaration({ prop: 'color', value: 'black' })) +``` + +
+child
– New node.push(child) =>
rangeBy
(opts) – Get the range for a word or start and end index inside the node.
+The start index is inclusive; the end index is exclusive. Pick<WarningOptions, #
opts
– Options."word"
| "index"
| "endIndex"
>
rangeBy(opts) =>
raw
(prop, defaultType) – Returns a Node#raws
value. If the node is missing
+the code style property (because the node was manually built or cloned),
+PostCSS will try to autodetect the code style property by looking
+at other nodes in the tree.
+ +```js +const root = postcss.parse('a { background: white }') +root.nodes[0].append({ prop: 'color', value: 'black' }) +root.nodes[0].nodes[1].raws.before //=> undefined +root.nodes[0].nodes[1].raw('before') //=> ' ' +``` + +
+prop
– Name of code style property.string
defaultType
– Name of default value, it can be missed
+if the value is the same as prop.string
raw(prop, defaultType) =>
remove
() – Removes the node from its parent and cleans the parent properties
+from the node and its children.
+ +```js +if (decl.prop.match(/^-webkit-/)) { + decl.remove() +} +``` + +
+remove() =>
removeAll
() – Removes all children from the container
+and cleans their parent properties.
+ +```js +rule.removeAll() +rule.nodes.length //=> 0 +``` + +
+removeAll() =>
removeChild
(child) – Removes node from the container and cleans the parent properties
+from the node and its children.
+ +```js +rule.nodes.length //=> 5 +rule.removeChild(decl) +rule.nodes.length //=> 4 +decl.parent //=> undefined +``` + +
+child
– Child or child’s index.number | ChildNode
removeChild(child) =>
replaceValues
(pattern, options, replaced) – Passes all declaration values within the container that match pattern
+through callback, replacing those values with the returned result
+of callback.
+ +This method is useful if you are using a custom unit or function +and need to iterate through all values. + +```js +root.replaceValues(/\d+rem/, { fast: 'rem' }, string => { + return 15 * parseInt(string) + 'px' +}) +``` + +
+pattern
– Replace pattern.string | RegExp
options
replaceValues(pattern, options, replaced) =>
pattern
string | RegExp
replaced
string |
replaceValues(pattern, replaced) =>
replaceWith
(nodes) – Inserts node(s) before the current node and removes the current node.
+ +```js +AtRule: { + mixin: + ; + ;(atrule => { + atrule.replaceWith(mixinRules[atrule.params]) + }) +} +``` + +
+nodes
– Mode(s) to replace current one.ChildNode | ChildNode [] | ChildProps | ChildProps [] []
replaceWith(nodes) =>
root
() – Finds the Root instance of the node’s tree.
+ +```js +root.nodes[0].nodes[0].root() === root +``` + +
+root() =>
some
(condition) – Returns true
if callback returns true
for (at least) one
+of the container’s children.
+ +```js +const hasPrefix = rule.some(i => i.prop[0] === '-') +``` + +
+condition
(node, index, nodes) number#
index
condition(node, index, nodes) =>
some(condition) =>
toJSON
() – Fix circular links on JSON.stringify()
.
toJSON() =>
toString
(stringifier) – Returns a CSS string representing the node.
+ +```js +new Rule({ selector: 'a' }).toString() //=> "a {}" +``` + +
+stringifier
– A syntax to use in string generation.toString(stringifier) =>
walk
(callback) – Traverses the container’s descendant nodes, calling callback
+for each node.
+ +Like container.each(), this method is safe to use +if you are mutating arrays during iteration. + +If you only need to iterate through the container’s immediate children, +use `Container#each`. + +```js +root.walk(node => { + // Traverses all descendant nodes. +}) +``` + +
+walk(callback) =>
false
walkAtRules
(nameFilter, callback) – Traverses the container’s descendant nodes, calling callback
+for each at-rule node.
+ +If you pass a filter, iteration will only happen over at-rules +that have matching names. + +Like `Container#each`, this method is safe +to use if you are mutating arrays during iteration. + +```js +root.walkAtRules(rule => { + if (isOld(rule.name)) rule.remove() +}) + +let first = false +root.walkAtRules('charset', rule => { + if (!first) { + first = true + } else { + rule.remove() + } +}) +``` + +
+nameFilter
string | RegExp
walkAtRules(nameFilter, callback) =>
false
walkAtRules(callback) =>
false
walkComments
(callback) – Traverses the container’s descendant nodes, calling callback
+for each comment node.
+ +Like `Container#each`, this method is safe +to use if you are mutating arrays during iteration. + +```js +root.walkComments(comment => { + comment.remove() +}) +``` + +
+callback
(comment, indexed) number#
indexed
callback(comment, indexed) =>
false
| voidwalkComments(callback) =>
false
callback
(comment, indexed) number#
indexed
callback(comment, indexed) =>
false
| voidwalkComments(callback) =>
false
walkDecls
(propFilter, callback) – Traverses the container’s descendant nodes, calling callback
+for each declaration node.
+ +If you pass a filter, iteration will only happen over declarations +with matching properties. + +```js +root.walkDecls(decl => { + checkPropertySupport(decl.prop) +}) + +root.walkDecls('border-radius', decl => { + decl.remove() +}) + +root.walkDecls(/^background/, decl => { + decl.value = takeFirstColorFromGradient(decl.value) +}) +``` + +Like `Container#each`, this method is safe +to use if you are mutating arrays during iteration. + +
+propFilter
string | RegExp
walkDecls(propFilter, callback) =>
false
walkDecls(callback) =>
false
walkRules
(selectorFilter, callback) – Traverses the container’s descendant nodes, calling callback
+for each rule node.
+ +If you pass a filter, iteration will only happen over rules +with matching selectors. + +Like `Container#each`, this method is safe +to use if you are mutating arrays during iteration. + +```js +const selectors = [] +root.walkRules(rule => { + selectors.push(rule.selector) +}) +console.log(`Your CSS uses ${selectors.length} selectors`) +``` + +
+selectorFilter
string | RegExp
walkRules(selectorFilter, callback) =>
false
walkRules(callback) =>
false
warn
(result, text, opts) – This method is provided as a convenience wrapper for Result#warn
.
+ +```js +Declaration: { + bad: + ; + ;((decl, { result }) => { + decl.warn(result, 'Deprecated property bad') + }) +} +``` + +
+result
– The Result
instance that will receive the warning.text
– Warning message.string
opts
– Warning Options.
+warn(result, text, opts) =>
default
– Represents a comment between declarations or statements (rule and at-rules).+ +```js +Once (root, { Comment }) { + let note = new Comment({ text: 'Note: …' }) + root.append(note) +} +``` + +Comments inside selectors, at-rule parameters, or declaration values +will be stored in the `raws` properties explained above. + +
+
+
+Every parser saves its own properties,
+but the default CSS parser uses:
+
+- `before`: the space symbols before the node. It also stores `*`
+ and `_` symbols before the declaration (IE hack).
+- `after`: the space symbols after the last child of the node
+ to the end of the node.
+- `between`: the symbols between the property and value
+ for declarations, selector and `{` for rules, or last parameter
+ and `{` for at-rules.
+- `semicolon`: contains true if the last child has
+ an (optional) semicolon.
+- `afterName`: the space between the at-rule name and its parameters.
+- `left`: the space symbols between `/*` and the comment’s text.
+- `right`: the space symbols between the comment’s text
+ and
+
+The property is used in source map generation.
+
+If you create a node manually (e.g., with `postcss.decl()`),
+that node will not have a `source` property and will be absent
+from the source map. For this reason, the plugin developer should
+consider cloning nodes to create new ones (in which case the new node’s
+source will reference the original, cloned node) or setting
+the `source` property manually.
+
+```js
+decl.source.input.from //=> '/home/ai/a.sass'
+decl.source.start //=> { line: 10, column: 2 }
+decl.source.end //=> { line: 10, column: 12 }
+```
+
+```js
+// Bad
+const prefixed = postcss.decl({
+ prop: '-moz-' + decl.prop,
+ value: decl.value,
+})
+
+// Good
+const prefixed = decl.clone({ prop: '-moz-' + decl.prop })
+```
+
+```js
+if (atrule.name === 'add-link') {
+ const rule = postcss.rule({ selector: 'a', source: atrule.source })
+ atrule.parent.insertBefore(atrule, rule)
+}
+```
+
+
+
+```js
+new Declaration({ prop: 'color', value: 'black' }).type //=> 'decl'
+```
+
+
+
+Just alias for `node.parent.insertAfter(node, add)`.
+
+```js
+decl.after('color: black')
+```
+
+ string | default | ChildProps | default [] after(newNode) => #
src/.fastpm/-/postcss@8.4.14/lib/comment.d.ts#L43 parent
– The node’s parent node.#
src/.fastpm/-/postcss@8.4.14/lib/comment.d.ts#L44 raws
– Information to generate byte-to-byte equal node string as it was
+in the origin input.
*/
.
+- `important`: the content of the important statement,
+ if it is not just `!important`.
+
+PostCSS cleans selectors, declaration values and at-rule parameters
+from comments and extra spaces, but it stores origin content in raws
+properties. As such, if you don’t change a declaration’s value,
+PostCSS will use the raw value with comments.
+
+```js
+const root = postcss.parse('a {\n color:black\n}')
+root.first.first.raws //=> { before: '\n ', between: ':' }
+```
+
+#
src/.fastpm/-/postcss@8.4.14/lib/node.d.ts#L156 source
– The input source of the node.
#
src/.fastpm/-/postcss@8.4.14/lib/comment.d.ts#L42 type
– tring representing the node’s type. Possible values are root
, atrule
,
+rule
, decl
, or comment
."comment"
#
src/.fastpm/-/postcss@8.4.14/lib/node.d.ts#L401 after
(newNode) – Insert new node after current node to current node’s parent.
#
newNode
– New node.
assign
(overrides) – Assigns properties to the current node.
+ +```js +decl.assign({ prop: 'word-wrap', value: 'break-word' }) +``` + +
+overrides
object | CommentProps
assign(overrides) =>
before
(newNode) – Insert new node before current node to current node’s parent.
+ +Just alias for `node.parent.insertBefore(node, add)`. + +```js +decl.before('content: ""') +``` + +
+newNode
– New node.string | default | ChildProps | default []
before(newNode) =>
cleanRaws
(keepBetween) – Clear the code style properties for the node and its children.
+ +```js +node.raws.before //=> ' ' +node.cleanRaws() +node.raws.before //=> undefined +``` + +
+keepBetween
– Keep the raws.between
symbols.
+boolean
cleanRaws(keepBetween) =>
clone
(overrides) – Returns an exact clone of the node.
+ +The resulting cloned node and its (cloned) children will retain +code style properties. + +```js +decl.raws.before //=> "\n " +const cloned = decl.clone({ prop: '-moz-' + decl.prop }) +cloned.raws.before //=> "\n " +cloned.toString() //=> -moz-transform: scale(0) +``` + +
+overrides
Partial<CommentProps>
clone(overrides) =>
cloneAfter
(overrides) – Shortcut to clone the node and insert the resulting cloned node
+after the current node. Partial<CommentProps>#
overrides
cloneAfter(overrides) =>
cloneBefore
(overrides) – Shortcut to clone the node and insert the resulting cloned node
+before the current node.
+ +```js +decl.cloneBefore({ prop: '-moz-' + decl.prop }) +``` + +
+overrides
Partial<CommentProps>
cloneBefore(overrides) =>
error
(message, options) – Returns a CssSyntaxError
instance containing the original position
+of the node in the source, showing line and column numbers and also
+a small excerpt to facilitate debugging.
+ +If present, an input source map will be used to get the original position +of the source, even from a previous compilation step +(e.g., from Sass compilation). + +This method produces very useful error messages. + +```js +if (!variables[name]) { + throw decl.error(`Unknown variable ${name}`, { word: name }) + // CssSyntaxError: postcss-vars:a.sass:4:3: Unknown variable $black + // color: $black + // a + // ^ + // background: white +} +``` + +
+message
– Error description.string
options
error(message, options) =>
next
() – Returns the next child of the node’s parent.
+Returns undefined
if the current node is the last child.
+ +```js +if (comment.text === 'delete next') { + const next = comment.next() + if (next) { + next.remove() + } +} +``` + +
+next() =>
positionBy
(opts) – Get the position for a word or an index inside the node. Pick<WarningOptions, #
opts
– Options."word"
| "index"
>
positionBy(opts) =>
positionInside
(index) – Convert string index to line/column. number#
index
– The symbol number in the node’s string.
positionInside(index) =>
prev
() – Returns the previous child of the node’s parent.
+Returns undefined
if the current node is the first child.
+ +```js +const annotation = decl.prev() +if (annotation.type === 'comment') { + readAnnotation(annotation.text) +} +``` + +
+prev() =>
rangeBy
(opts) – Get the range for a word or start and end index inside the node.
+The start index is inclusive; the end index is exclusive. Pick<WarningOptions, #
opts
– Options."word"
| "index"
| "endIndex"
>
rangeBy(opts) =>
raw
(prop, defaultType) – Returns a Node#raws
value. If the node is missing
+the code style property (because the node was manually built or cloned),
+PostCSS will try to autodetect the code style property by looking
+at other nodes in the tree.
+ +```js +const root = postcss.parse('a { background: white }') +root.nodes[0].append({ prop: 'color', value: 'black' }) +root.nodes[0].nodes[1].raws.before //=> undefined +root.nodes[0].nodes[1].raw('before') //=> ' ' +``` + +
+prop
– Name of code style property.string
defaultType
– Name of default value, it can be missed
+if the value is the same as prop.string
raw(prop, defaultType) =>
remove
() – Removes the node from its parent and cleans the parent properties
+from the node and its children.
+ +```js +if (decl.prop.match(/^-webkit-/)) { + decl.remove() +} +``` + +
+remove() =>
replaceWith
(nodes) – Inserts node(s) before the current node and removes the current node.
+ +```js +AtRule: { + mixin: + ; + ;(atrule => { + atrule.replaceWith(mixinRules[atrule.params]) + }) +} +``` + +
+nodes
– Mode(s) to replace current one.ChildNode | ChildNode [] | ChildProps | ChildProps [] []
replaceWith(nodes) =>
root
() – Finds the Root instance of the node’s tree.
+ +```js +root.nodes[0].nodes[0].root() === root +``` + +
+root() =>
toJSON
() – Fix circular links on JSON.stringify()
.
toJSON() =>
toString
(stringifier) – Returns a CSS string representing the node.
+ +```js +new Rule({ selector: 'a' }).toString() //=> "a {}" +``` + +
+stringifier
– A syntax to use in string generation.toString(stringifier) =>
warn
(result, text, opts) – This method is provided as a convenience wrapper for Result#warn
.
+ +```js +Declaration: { + bad: + ; + ;((decl, { result }) => { + decl.warn(result, 'Deprecated property bad') + }) +} +``` + +
+result
– The Result
instance that will receive the warning.text
– Warning message.string
opts
– Warning Options.
+warn(result, text, opts) =>
default
– Represents the source CSS.+ +```js +const root = postcss.parse(css, { from: file }) +const input = root.source.input +``` + +
+ string
+
+```js
+const input = postcss.parse('a{}', { from: file }).input
+input.css //=> "a{}"
+```
+
+ string
+
+```js
+const root = postcss.parse(css, { from: 'a.css' })
+root.source.input.file //=> '/home/ai/a.css'
+```
+
+ boolean string
+
+```js
+const root = postcss.parse(css)
+root.source.input.file //=> undefined
+root.source.input.id //=> ""
+```
+
+
+
+```js
+root.source.input.map.consumer().sources //=> ['a.sass']
+```
+
+ number fromOffset(offset) => #
src/.fastpm/-/postcss@8.4.14/lib/input.d.ts#L102 constructor
(css, opts)
#
src/.fastpm/-/postcss@8.4.14/lib/input.d.ts#L58 css
– Input CSS source.#
src/.fastpm/-/postcss@8.4.14/lib/input.d.ts#L79 file
– The absolute path to the CSS source file defined
+with the from
option.#
src/.fastpm/-/postcss@8.4.14/lib/input.d.ts#L96 hasBOM
– The flag to indicate whether or not the source code has Unicode BOM.#
src/.fastpm/-/postcss@8.4.14/lib/input.d.ts#L91 id
– The unique ID of the CSS source. It will be created if from
option
+is not provided (because PostCSS does not know the file path).#
src/.fastpm/-/postcss@8.4.14/lib/input.d.ts#L68 map
– The input source map passed from a compilation step before PostCSS
+(for example, from Sass compiler).
#
src/.fastpm/-/postcss@8.4.14/lib/input.d.ts#L149 fromOffset
(offset) – Converts source offset to line and column.
#
offset
– Source offset.
+null
| {
origin
(line, column, endLine, endColumn) – Reads the input source map and returns a symbol position
+in the input source (e.g., in a Sass file that was compiled
+to CSS before being passed to PostCSS). Optionally takes an
+end position, exclusive.
+ +```js +root.source.input.origin(1, 1) //=> { file: 'a.css', line: 3, column: 1 } +root.source.input.origin(1, 1, 1, 4) +//=> { file: 'a.css', line: 3, column: 1, endLine: 3, endColumn: 4 } +``` + +
+line
– Line for inclusive start position in input CSS.number
column
– Column for inclusive start position in input CSS.number
endLine
– Line for exclusive end position in input CSS.number
endColumn
– Column for exclusive end position in input CSS.
+number
origin(line, column, endLine, endColumn) =>
false
| FilePositiondefault
– Source map information from input CSS.
+For example, source map after Sass compiler.+ +This class will automatically find source map in input CSS or in file system +near input file (according `from` option). + +```js +const root = parse(css, { from: 'a.sass.css' }) +root.input.map //=> PreviousMap +``` + +
+ string string boolean string
+
+It is lazy method, so it will create object only on first call
+and then it will use cache.
+
+ consumer() => #
src/.fastpm/-/postcss@8.4.14/lib/previous-map.d.ts#L53 constructor
(css, opts)
#
src/.fastpm/-/postcss@8.4.14/lib/previous-map.d.ts#L26 annotation
– sourceMappingURL
content.#
src/.fastpm/-/postcss@8.4.14/lib/previous-map.d.ts#L42 file
– The CSS source identifier. Contains Input#file
if the user
+set the from
option, or Input#id
if they did not.#
src/.fastpm/-/postcss@8.4.14/lib/previous-map.d.ts#L21 inline
– Was source map inlined by data-uri to input CSS.#
src/.fastpm/-/postcss@8.4.14/lib/previous-map.d.ts#L36 root
– The directory with source map file, if source map is in separated file.#
src/.fastpm/-/postcss@8.4.14/lib/previous-map.d.ts#L64 consumer
() – Create a instance of SourceMapGenerator
class
+from the source-map
library to work with source map information.
withContent
() – Does source map contains sourcesContent
with input source text.
withContent() =>
internal
typeof captureRejectionSymbol boolean typeof errorMonitor
+
+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.
+
+#
constructor
(options)
#
src/.fastpm/-/@types/node@17.0.45/events.d.ts#L301 captureRejectionSymbol
#
src/.fastpm/-/@types/node@17.0.45/events.d.ts#L306 captureRejections
– Sets or gets the default captureRejection value for all emitters.#
src/.fastpm/-/@types/node@17.0.45/events.d.ts#L300 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.
addListener(eventName, listener) =>
emit
(eventName, args) – Synchronously calls each of the listeners registered for the event namedeventName
, in the order they were registered, passing the supplied arguments
+to each.
+ +Returns `true` if the event had listeners, `false` otherwise. + +```js +const EventEmitter = require('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 +``` + +
+eventName
string | symbol
args
any []
emit(eventName, args) =>
eventNames
() – Returns an array listing the events for which the emitter has registered
+listeners. The values in the array are strings or Symbol
s.
+ +```js +const EventEmitter = require('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) ] +``` + +
+eventNames() =>
getMaxListeners
() – Returns the current max listener value for the EventEmitter
which is either
+set by emitter.setMaxListeners(n)
or defaults to {@link defaultMaxListeners}.
getMaxListeners() =>
listenerCount
(eventName) – Returns the number of listeners listening to the event named eventName
. string | symbol#
eventName
– The name of the event being listened for
+
listenerCount(eventName) =>
listeners
(eventName) – Returns a copy of the array of listeners for the event named eventName
.
+ +```js +server.on('connection', stream => { + console.log('someone connected!') +}) +console.log(util.inspect(server.listeners('connection'))) +// Prints: [ [Function] ] +``` + +
+eventName
string | symbol
listeners(eventName) =>
off
(eventName, listener) – Alias for emitter.removeListener()
. string | symbol#
eventName
off(eventName, listener) =>
on
(eventName, listener) – 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.
+ +```js +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. + +```js +const myEE = new EventEmitter() +myEE.on('foo', () => console.log('a')) +myEE.prependListener('foo', () => console.log('b')) +myEE.emit('foo') +// Prints: +// b +// a +``` + +
+eventName
– The name of the event.string | symbol
listener
(args) any []#
args
listener(args) =>
on(eventName, listener) =>
once
(eventName, listener) – Adds a one-timelistener
function for the event named eventName
. The
+next time eventName
is triggered, this listener is removed and then invoked.
+ +```js +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. + +```js +const myEE = new EventEmitter() +myEE.once('foo', () => console.log('a')) +myEE.prependOnceListener('foo', () => console.log('b')) +myEE.emit('foo') +// Prints: +// b +// a +``` + +
+eventName
– The name of the event.string | symbol
listener
(args) any []#
args
listener(args) =>
once(eventName, listener) =>
pipe
(destination, { end }) { #
options
pipe<T extends WritableStream<T>>(destination, { end }) =>
prependListener
(eventName, listener) – 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.
+ +```js +server.prependListener('connection', stream => { + console.log('someone connected!') +}) +``` + +Returns a reference to the `EventEmitter`, so that calls can be chained. + +
+eventName
– The name of the event.string | symbol
listener
(args) any []#
args
listener(args) =>
prependListener(eventName, listener) =>
prependOnceListener
(eventName, listener) – Adds a one-timelistener
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.
+ +```js +server.prependOnceListener('connection', stream => { + console.log('Ah, we have our first user!') +}) +``` + +Returns a reference to the `EventEmitter`, so that calls can be chained. + +
+eventName
– The name of the event.string | symbol
listener
(args) any []#
args
listener(args) =>
prependOnceListener(eventName, listener) =>
rawListeners
(eventName) – Returns a copy of the array of listeners for the event named eventName
,
+including any wrappers (such as those created by .once()
).
+ +```js +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') +``` + +
+eventName
string | symbol
rawListeners(eventName) =>
removeAllListeners
(event) – 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. + +
+event
string | symbol
removeAllListeners(event) =>
removeListener
(eventName, listener) – Removes the specified listener
from the listener array for the event namedeventName
.
+ +```js +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. + +```js +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 indices 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: + +```js +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. + +
+eventName
string | symbol
listener
(args) any []#
args
listener(args) =>
removeListener(eventName, listener) =>
setMaxListeners
(n) – By default EventEmitter
s 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 toInfinity
(or 0
) to indicate an unlimited number of listeners.
+ +Returns a reference to the `EventEmitter`, so that calls can be chained. + +
+n
number
setMaxListeners(n) =>
getEventListeners
(emitter, name) – Returns a copy of the array of listeners for the event named eventName
.
+ +For `EventEmitter`s this behaves exactly the same as calling `.listeners` on +the emitter. + +For `EventTarget`s this is the only way to get the event listeners for the +event target. This is useful for debugging and diagnostic purposes. + +```js +const { getEventListeners, EventEmitter } = require('events') + +{ + const ee = new EventEmitter() + const listener = () => console.log('Events are fun') + ee.on('foo', listener) + getEventListeners(ee, 'foo') // [listener] +} +{ + const et = new EventTarget() + const listener = () => console.log('Events are fun') + et.addEventListener('foo', listener) + getEventListeners(et, 'foo') // [listener] +} +``` + +
+emitter
name
string | symbol
getEventListeners(emitter, name) =>
listenerCount
(emitter, eventName) – A class method that returns the number of listeners for the given eventName
registered on the given emitter
.
+ +```js +const { EventEmitter, listenerCount } = require('events') +const myEmitter = new EventEmitter() +myEmitter.on('event', () => {}) +myEmitter.on('event', () => {}) +console.log(listenerCount(myEmitter, 'event')) +// Prints: 2 +``` + +
+emitter
– The emitter to queryeventName
– The event name
+string | symbol
listenerCount(emitter, eventName) =>
on
(emitter, eventName, options) – ```js
+const { on, EventEmitter } = require('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: + +```js +const { on, EventEmitter } = require('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()); +```` + +
+emitter
eventName
– The name of the event being listened forstring
options
on(emitter, eventName, options) =>
once
(emitter, eventName, options) – 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](https://dom.spec.whatwg.org/#interface-eventtarget) interface, which has no special`'error'` event +semantics and does not listen to the `'error'` event. + +```js +const { once, EventEmitter } = require('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.log('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: + +```js +const { EventEmitter, once } = require('events') + +const ee = new EventEmitter() + +once(ee, 'error') + .then(([err]) => console.log('ok', err.message)) + .catch(err => console.log('error', err.message)) + +ee.emit('error', new Error('boom')) + +// Prints: ok boom +``` + +An `AbortSignal` can be used to cancel waiting for the event: + +```js +const { EventEmitter, once } = require('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() // Abort waiting for the event +ee.emit('foo') // Prints: Waiting for the event was canceled! +``` + +
+emitter
eventName
string | symbol
options
once(emitter, eventName, options) =>
emitter
eventName
string
options
once(emitter, eventName, options) =>
setMaxListeners
(n, eventTargets) – By default EventEmitter
s 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 EventEmitter.setMaxListeners()
method allows the default limit to be
+modified (if eventTargets is empty) or modify the limit specified in every EventTarget
| EventEmitter
passed as arguments.
+The value can be set toInfinity
(or 0
) to indicate an unlimited number of listeners.
+ +```js +EventEmitter.setMaxListeners(20) +// Equivalent to +EventEmitter.defaultMaxListeners = 20 + +const eventTarget = new EventTarget() +// Only way to increase limit for `EventTarget` instances +// as these doesn't expose its own `setMaxListeners` method +EventEmitter.setMaxListeners(20, eventTarget) +``` + +
+n
number
eventTargets
setMaxListeners(n, eventTargets) =>
AcornNode
AddressInfo
AddressInfo
AgentOptions
boolean number number number number number#
src/.fastpm/-/@types/node@17.0.45/http.d.ts#L985 keepAlive
– Keep sockets around in a pool to be used by other requests in the future. Default = false#
src/.fastpm/-/@types/node@17.0.45/http.d.ts#L990 keepAliveMsecs
– When using HTTP KeepAlive, how often to send TCP KeepAlive packets over sockets being kept alive. Default = 1000.
+Only relevant if keepAlive is set to true.#
src/.fastpm/-/@types/node@17.0.45/http.d.ts#L1002 maxFreeSockets
– Maximum number of sockets to leave open in a free state. Only relevant if keepAlive is set to true. Default = 256.#
src/.fastpm/-/@types/node@17.0.45/http.d.ts#L994 maxSockets
– Maximum number of sockets to allow per host. Default for Node 0.10 is 5, default for Node 0.12 is Infinity#
src/.fastpm/-/@types/node@17.0.45/http.d.ts#L998 maxTotalSockets
– Maximum number of sockets allowed for all hosts in total. Each request will use a new socket until the maximum is reached. Default: Infinity.#
src/.fastpm/-/@types/node@17.0.45/net.d.ts#L47 onread
– If specified, incoming data is stored in a single buffer and passed to the supplied callback when data arrives on the socket.
+Note: this will cause the streaming functionality to not provide any data, however events like 'error', 'end', and 'close' will
+still be emitted as normal and methods like pause() and resume() will also behave as expected.#
src/.fastpm/-/@types/node@17.0.45/http.d.ts#L1011 scheduling
– Scheduling strategy to apply when picking the next free socket to use."fifo"
| "lifo"
#
src/.fastpm/-/@types/node@17.0.45/http.d.ts#L1006 timeout
– Socket timeout in milliseconds. This will set the timeout after the socket is connected.
Alias
#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L62 customResolver
– Instructs the plugin to use an alternative resolving algorithm,
+rather than the Rollup's resolver.null
| ResolveIdHook | ResolverObject
AnalyzeMetafileOptions
AsymmetricKeyDetails
number string string number number#
src/.fastpm/-/@types/node@17.0.45/crypto.d.ts#L526 divisorLength
– Size of q in bits (DSA).#
src/.fastpm/-/@types/node@17.0.45/crypto.d.ts#L514 hashAlgorithm
– Name of the message digest (RSA-PSS).#
src/.fastpm/-/@types/node@17.0.45/crypto.d.ts#L518 mgf1HashAlgorithm
– Name of the message digest used by MGF1 (RSA-PSS).#
src/.fastpm/-/@types/node@17.0.45/crypto.d.ts#L506 modulusLength
– Key size in bits (RSA, DSA).#
src/.fastpm/-/@types/node@17.0.45/crypto.d.ts#L522 saltLength
– Minimal salt length in bytes (RSA-PSS).
AtRuleProps
string | number#
src/.fastpm/-/postcss@8.4.14/lib/at-rule.d.ts#L43 params
– Parameters following the name of the at-rule.#
src/.fastpm/-/postcss@8.4.14/lib/at-rule.d.ts#L45 raws
– Information used to generate byte-to-byte equal node string as it was in the origin input.
AtRuleRaws
string string string string { #
src/.fastpm/-/postcss@8.4.14/lib/at-rule.d.ts#L13 after
– The space symbols after the last child of the node to the end of the node.#
src/.fastpm/-/postcss@8.4.14/lib/at-rule.d.ts#L18 afterName
– The space between the at-rule name and its parameters.#
src/.fastpm/-/postcss@8.4.14/lib/at-rule.d.ts#L8 before
– The space symbols before the node. It also stores *
+and _
symbols before the declaration (IE hack).#
src/.fastpm/-/postcss@8.4.14/lib/at-rule.d.ts#L23 between
– The symbols between the last parameter and {
for rules.#
src/.fastpm/-/postcss@8.4.14/lib/at-rule.d.ts#L33 params
– The rule’s selector with comments.
semicolon
– Contains true
if the last child has an (optional) semicolon.boolean
AwaitWriteFinishOptions
number number#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L98 pollInterval
– File size polling interval.#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L93 stabilityThreshold
– Amount of time in milliseconds for a file size to remain constant before emitting its event.
BlobOptions
string#
src/.fastpm/-/@types/node@17.0.45/buffer.d.ts#L111 type
– The Blob content-type. The intent is for type
to convey
+the MIME media type of the data, however no validation of the type format
+is performed.
Buffer
+
+- `0` is returned if `target` is the same as `buf`
+- `1` is returned if `target` should come _before_ `buf` when sorted.
+- `-1` is returned if `target` should come _after_ `buf` when sorted.
+
+```js
+import { Buffer } from 'buffer'
+
+const buf1 = Buffer.from('ABC')
+const buf2 = Buffer.from('BCD')
+const buf3 = Buffer.from('ABCD')
+
+console.log(buf1.compare(buf1))
+// Prints: 0
+console.log(buf1.compare(buf2))
+// Prints: -1
+console.log(buf1.compare(buf3))
+// Prints: -1
+console.log(buf2.compare(buf1))
+// Prints: 1
+console.log(buf2.compare(buf3))
+// Prints: 1
+console.log([buf1, buf2, buf3].sort(Buffer.compare))
+// Prints: [ Uint8Array number number number number compare(target, targetStart, targetEnd, sourceStart, sourceEnd) => #
compare
(target, targetStart, targetEnd, sourceStart, sourceEnd) – Compares buf
with target
and returns a number indicating whether buf
comes before, after, or is the same as target
in sort order.
+Comparison is based on the actual sequence of bytes in each Buffer
.
#
target
– A Buffer
or {@link Uint8Array} with which to compare buf
.#
targetStart
#
targetEnd
#
sourceStart
#
sourceEnd
0
| 1
| -1
copy
(target, targetStart, sourceStart, sourceEnd) – Copies data from a region of buf
to a region in target
, even if the target
memory region overlaps with buf
.
+ +[`TypedArray.prototype.set()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/set) performs the same operation, and is available +for all TypedArrays, including Node.js `Buffer`s, although it takes +different function arguments. + +```js +import { Buffer } from 'buffer' + +// Create two `Buffer` instances. +const buf1 = Buffer.allocUnsafe(26) +const buf2 = Buffer.allocUnsafe(26).fill('!') + +for (let i = 0; i < 26; i++) { + // 97 is the decimal ASCII value for 'a'. + buf1[i] = i + 97 +} + +// Copy `buf1` bytes 16 through 19 into `buf2` starting at byte 8 of `buf2`. +buf1.copy(buf2, 8, 16, 20) +// This is equivalent to: +// buf2.set(buf1.subarray(16, 20), 8); + +console.log(buf2.toString('ascii', 0, 25)) +// Prints: !!!!!!!!qrst!!!!!!!!!!!!! +``` + +```js +import { Buffer } from 'buffer' + +// Create a `Buffer` and copy data from one region to an overlapping region +// within the same `Buffer`. + +const buf = Buffer.allocUnsafe(26) + +for (let i = 0; i < 26; i++) { + // 97 is the decimal ASCII value for 'a'. + buf[i] = i + 97 +} + +buf.copy(buf, 0, 4, 10) + +console.log(buf.toString()) +// Prints: efghijghijklmnopqrstuvwxyz +``` + +
+target
– A Buffer
or {@link Uint8Array} to copy into.Uint8Array
targetStart
number
sourceStart
number
sourceEnd
number
copy(target, targetStart, sourceStart, sourceEnd) =>
entries
() – Creates and returns an iterator of [index, byte]
pairs from the contents
+of buf
.
+ +```js +import { Buffer } from 'buffer' + +// Log the entire contents of a `Buffer`. + +const buf = Buffer.from('buffer') + +for (const pair of buf.entries()) { + console.log(pair) +} +// Prints: +// [0, 98] +// [1, 117] +// [2, 102] +// [3, 102] +// [4, 101] +// [5, 114] +``` + +
+entries() =>
equals
(otherBuffer) – Returns true
if both buf
and otherBuffer
have exactly the same bytes,false
otherwise. Equivalent to buf.compare(otherBuffer) === 0
.
+ +```js +import { Buffer } from 'buffer' + +const buf1 = Buffer.from('ABC') +const buf2 = Buffer.from('414243', 'hex') +const buf3 = Buffer.from('ABCD') + +console.log(buf1.equals(buf2)) +// Prints: true +console.log(buf1.equals(buf3)) +// Prints: false +``` + +
+otherBuffer
– A Buffer
or {@link Uint8Array} with which to compare buf
.
+Uint8Array
equals(otherBuffer) =>
fill
(value, offset, end, encoding) – Fills buf
with the specified value
. If the offset
and end
are not given,
+the entire buf
will be filled:
+
+```js
+import { Buffer } from 'buffer'
+
+// Fill a `Buffer` with the ASCII character 'h'.
+
+const b = Buffer.allocUnsafe(50).fill('h')
+
+console.log(b.toString())
+// Prints: hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh
+```
+
+`value` is coerced to a `uint32` value if it is not a string, `Buffer`, or
+integer. If the resulting integer is greater than `255` (decimal), `buf` will be
+filled with `value & 255`.
+
+If the final write of a `fill()` operation falls on a multi-byte character,
+then only the bytes of that character that fit into `buf` are written:
+
+```js
+import { Buffer } from 'buffer'
+
+// Fill a `Buffer` with character that takes up two bytes in UTF-8.
+
+console.log(Buffer.allocUnsafe(5).fill('\u0222'))
+// Prints:
value
– The value with which to fill buf
.string | number | Uint8Array
offset
number
end
number
encoding
fill(value, offset, end, encoding) =>
includes
(value, byteOffset, encoding) – Equivalent to buf.indexOf() !== -1
.
+ +```js +import { Buffer } from 'buffer' + +const buf = Buffer.from('this is a buffer') + +console.log(buf.includes('this')) +// Prints: true +console.log(buf.includes('is')) +// Prints: true +console.log(buf.includes(Buffer.from('a buffer'))) +// Prints: true +console.log(buf.includes(97)) +// Prints: true (97 is the decimal ASCII value for 'a') +console.log(buf.includes(Buffer.from('a buffer example'))) +// Prints: false +console.log(buf.includes(Buffer.from('a buffer example').slice(0, 8))) +// Prints: true +console.log(buf.includes('this', 4)) +// Prints: false +``` + +
+value
– What to search for.string | number | Buffer
byteOffset
number
encoding
includes(value, byteOffset, encoding) =>
indexOf
(value, byteOffset, encoding) – If value
is:
+ +- a string, `value` is interpreted according to the character encoding in`encoding`. +- a `Buffer` or [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array), `value` will be used in its entirety. + To compare a partial `Buffer`, use `buf.slice()`. +- a number, `value` will be interpreted as an unsigned 8-bit integer + value between `0` and `255`. + +```js +import { Buffer } from 'buffer' + +const buf = Buffer.from('this is a buffer') + +console.log(buf.indexOf('this')) +// Prints: 0 +console.log(buf.indexOf('is')) +// Prints: 2 +console.log(buf.indexOf(Buffer.from('a buffer'))) +// Prints: 8 +console.log(buf.indexOf(97)) +// Prints: 8 (97 is the decimal ASCII value for 'a') +console.log(buf.indexOf(Buffer.from('a buffer example'))) +// Prints: -1 +console.log(buf.indexOf(Buffer.from('a buffer example').slice(0, 8))) +// Prints: 8 + +const utf16Buffer = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'utf16le') + +console.log(utf16Buffer.indexOf('\u03a3', 0, 'utf16le')) +// Prints: 4 +console.log(utf16Buffer.indexOf('\u03a3', -4, 'utf16le')) +// Prints: 6 +``` + +If `value` is not a string, number, or `Buffer`, this method will throw a`TypeError`. If `value` is a number, it will be coerced to a valid byte value, +an integer between 0 and 255. + +If `byteOffset` is not a number, it will be coerced to a number. If the result +of coercion is `NaN` or `0`, then the entire buffer will be searched. This +behavior matches [`String.prototype.indexOf()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf). + +```js +import { Buffer } from 'buffer' + +const b = Buffer.from('abcdef') + +// Passing a value that's a number, but not a valid byte. +// Prints: 2, equivalent to searching for 99 or 'c'. +console.log(b.indexOf(99.9)) +console.log(b.indexOf(256 + 99)) + +// Passing a byteOffset that coerces to NaN or 0. +// Prints: 1, searching the whole buffer. +console.log(b.indexOf('b', undefined)) +console.log(b.indexOf('b', {})) +console.log(b.indexOf('b', null)) +console.log(b.indexOf('b', [])) +``` + +If `value` is an empty string or empty `Buffer` and `byteOffset` is less +than `buf.length`, `byteOffset` will be returned. If `value` is empty and`byteOffset` is at least `buf.length`, `buf.length` will be returned. + +
+value
– What to search for.string | number | Uint8Array
byteOffset
number
encoding
indexOf(value, byteOffset, encoding) =>
keys
() – Creates and returns an iterator of buf
keys (indices).
+ +```js +import { Buffer } from 'buffer' + +const buf = Buffer.from('buffer') + +for (const key of buf.keys()) { + console.log(key) +} +// Prints: +// 0 +// 1 +// 2 +// 3 +// 4 +// 5 +``` + +
+keys() =>
lastIndexOf
(value, byteOffset, encoding) – Identical to buf.indexOf()
, except the last occurrence of value
is found
+rather than the first occurrence.
+ +```js +import { Buffer } from 'buffer' + +const buf = Buffer.from('this buffer is a buffer') + +console.log(buf.lastIndexOf('this')) +// Prints: 0 +console.log(buf.lastIndexOf('buffer')) +// Prints: 17 +console.log(buf.lastIndexOf(Buffer.from('buffer'))) +// Prints: 17 +console.log(buf.lastIndexOf(97)) +// Prints: 15 (97 is the decimal ASCII value for 'a') +console.log(buf.lastIndexOf(Buffer.from('yolo'))) +// Prints: -1 +console.log(buf.lastIndexOf('buffer', 5)) +// Prints: 5 +console.log(buf.lastIndexOf('buffer', 4)) +// Prints: -1 + +const utf16Buffer = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'utf16le') + +console.log(utf16Buffer.lastIndexOf('\u03a3', undefined, 'utf16le')) +// Prints: 6 +console.log(utf16Buffer.lastIndexOf('\u03a3', -5, 'utf16le')) +// Prints: 4 +``` + +If `value` is not a string, number, or `Buffer`, this method will throw a`TypeError`. If `value` is a number, it will be coerced to a valid byte value, +an integer between 0 and 255. + +If `byteOffset` is not a number, it will be coerced to a number. Any arguments +that coerce to `NaN`, like `{}` or `undefined`, will search the whole buffer. +This behavior matches [`String.prototype.lastIndexOf()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/lastIndexOf). + +```js +import { Buffer } from 'buffer' + +const b = Buffer.from('abcdef') + +// Passing a value that's a number, but not a valid byte. +// Prints: 2, equivalent to searching for 99 or 'c'. +console.log(b.lastIndexOf(99.9)) +console.log(b.lastIndexOf(256 + 99)) + +// Passing a byteOffset that coerces to NaN. +// Prints: 1, searching the whole buffer. +console.log(b.lastIndexOf('b', undefined)) +console.log(b.lastIndexOf('b', {})) + +// Passing a byteOffset that coerces to 0. +// Prints: -1, equivalent to passing 0. +console.log(b.lastIndexOf('b', null)) +console.log(b.lastIndexOf('b', [])) +``` + +If `value` is an empty string or empty `Buffer`, `byteOffset` will be returned. + +
+value
– What to search for.string | number | Uint8Array
byteOffset
number
encoding
lastIndexOf(value, byteOffset, encoding) =>
readBigInt64BE
(offset) – Reads a signed, big-endian 64-bit integer from buf
at the specified offset
.
+ +Integers read from a `Buffer` are interpreted as two's complement signed +values. + +
+offset
number
readBigInt64BE(offset) =>
readBigInt64LE
(offset) – Reads a signed, little-endian 64-bit integer from buf
at the specifiedoffset
.
+ +Integers read from a `Buffer` are interpreted as two's complement signed +values. + +
+offset
number
readBigInt64LE(offset) =>
readBigUInt64BE
(offset) – Reads an unsigned, big-endian 64-bit integer from buf
at the specifiedoffset
.
+ +This function is also available under the `readBigUint64BE` alias. + +```js +import { Buffer } from 'buffer' + +const buf = Buffer.from([0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff]) + +console.log(buf.readBigUInt64BE(0)) +// Prints: 4294967295n +``` + +
+offset
number
readBigUInt64BE(offset) =>
readBigUInt64LE
(offset) – Reads an unsigned, little-endian 64-bit integer from buf
at the specifiedoffset
.
+ +This function is also available under the `readBigUint64LE` alias. + +```js +import { Buffer } from 'buffer' + +const buf = Buffer.from([0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff]) + +console.log(buf.readBigUInt64LE(0)) +// Prints: 18446744069414584320n +``` + +
+offset
number
readBigUInt64LE(offset) =>
readBigUint64BE
(offset) number#
offset
readBigUint64BE(offset) =>
readBigUint64LE
(offset) number#
offset
readBigUint64LE(offset) =>
readDoubleBE
(offset) – Reads a 64-bit, big-endian double from buf
at the specified offset
.
+ +```js +import { Buffer } from 'buffer' + +const buf = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8]) + +console.log(buf.readDoubleBE(0)) +// Prints: 8.20788039913184e-304 +``` + +
+offset
number
readDoubleBE(offset) =>
readDoubleLE
(offset) – Reads a 64-bit, little-endian double from buf
at the specified offset
.
+ +```js +import { Buffer } from 'buffer' + +const buf = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8]) + +console.log(buf.readDoubleLE(0)) +// Prints: 5.447603722011605e-270 +console.log(buf.readDoubleLE(1)) +// Throws ERR_OUT_OF_RANGE. +``` + +
+offset
number
readDoubleLE(offset) =>
readFloatBE
(offset) – Reads a 32-bit, big-endian float from buf
at the specified offset
.
+ +```js +import { Buffer } from 'buffer' + +const buf = Buffer.from([1, 2, 3, 4]) + +console.log(buf.readFloatBE(0)) +// Prints: 2.387939260590663e-38 +``` + +
+offset
number
readFloatBE(offset) =>
readFloatLE
(offset) – Reads a 32-bit, little-endian float from buf
at the specified offset
.
+ +```js +import { Buffer } from 'buffer' + +const buf = Buffer.from([1, 2, 3, 4]) + +console.log(buf.readFloatLE(0)) +// Prints: 1.539989614439558e-36 +console.log(buf.readFloatLE(1)) +// Throws ERR_OUT_OF_RANGE. +``` + +
+offset
number
readFloatLE(offset) =>
readInt16BE
(offset) – Reads a signed, big-endian 16-bit integer from buf
at the specified offset
.
+ +Integers read from a `Buffer` are interpreted as two's complement signed values. + +```js +import { Buffer } from 'buffer' + +const buf = Buffer.from([0, 5]) + +console.log(buf.readInt16BE(0)) +// Prints: 5 +``` + +
+offset
number
readInt16BE(offset) =>
readInt16LE
(offset) – Reads a signed, little-endian 16-bit integer from buf
at the specifiedoffset
.
+ +Integers read from a `Buffer` are interpreted as two's complement signed values. + +```js +import { Buffer } from 'buffer' + +const buf = Buffer.from([0, 5]) + +console.log(buf.readInt16LE(0)) +// Prints: 1280 +console.log(buf.readInt16LE(1)) +// Throws ERR_OUT_OF_RANGE. +``` + +
+offset
number
readInt16LE(offset) =>
readInt32BE
(offset) – Reads a signed, big-endian 32-bit integer from buf
at the specified offset
.
+ +Integers read from a `Buffer` are interpreted as two's complement signed values. + +```js +import { Buffer } from 'buffer' + +const buf = Buffer.from([0, 0, 0, 5]) + +console.log(buf.readInt32BE(0)) +// Prints: 5 +``` + +
+offset
number
readInt32BE(offset) =>
readInt32LE
(offset) – Reads a signed, little-endian 32-bit integer from buf
at the specifiedoffset
.
+ +Integers read from a `Buffer` are interpreted as two's complement signed values. + +```js +import { Buffer } from 'buffer' + +const buf = Buffer.from([0, 0, 0, 5]) + +console.log(buf.readInt32LE(0)) +// Prints: 83886080 +console.log(buf.readInt32LE(1)) +// Throws ERR_OUT_OF_RANGE. +``` + +
+offset
number
readInt32LE(offset) =>
readInt8
(offset) – Reads a signed 8-bit integer from buf
at the specified offset
.
+ +Integers read from a `Buffer` are interpreted as two's complement signed values. + +```js +import { Buffer } from 'buffer' + +const buf = Buffer.from([-1, 5]) + +console.log(buf.readInt8(0)) +// Prints: -1 +console.log(buf.readInt8(1)) +// Prints: 5 +console.log(buf.readInt8(2)) +// Throws ERR_OUT_OF_RANGE. +``` + +
+offset
number
readInt8(offset) =>
readIntBE
(offset, byteLength) – Reads byteLength
number of bytes from buf
at the specified offset
and interprets the result as a big-endian, two's complement signed value
+supporting up to 48 bits of accuracy.
+ +```js +import { Buffer } from 'buffer' + +const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]) + +console.log(buf.readIntBE(0, 6).toString(16)) +// Prints: 1234567890ab +console.log(buf.readIntBE(1, 6).toString(16)) +// Throws ERR_OUT_OF_RANGE. +console.log(buf.readIntBE(1, 0).toString(16)) +// Throws ERR_OUT_OF_RANGE. +``` + +
+offset
– Number of bytes to skip before starting to read. Must satisfy 0 <= offset <= buf.length - byteLength
.number
byteLength
– Number of bytes to read. Must satisfy 0 < byteLength <= 6
.
+number
readIntBE(offset, byteLength) =>
readIntLE
(offset, byteLength) – Reads byteLength
number of bytes from buf
at the specified offset
and interprets the result as a little-endian, two's complement signed value
+supporting up to 48 bits of accuracy.
+ +```js +import { Buffer } from 'buffer' + +const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]) + +console.log(buf.readIntLE(0, 6).toString(16)) +// Prints: -546f87a9cbee +``` + +
+offset
– Number of bytes to skip before starting to read. Must satisfy 0 <= offset <= buf.length - byteLength
.number
byteLength
– Number of bytes to read. Must satisfy 0 < byteLength <= 6
.
+number
readIntLE(offset, byteLength) =>
readUInt16BE
(offset) – Reads an unsigned, big-endian 16-bit integer from buf
at the specifiedoffset
.
+ +This function is also available under the `readUint16BE` alias. + +```js +import { Buffer } from 'buffer' + +const buf = Buffer.from([0x12, 0x34, 0x56]) + +console.log(buf.readUInt16BE(0).toString(16)) +// Prints: 1234 +console.log(buf.readUInt16BE(1).toString(16)) +// Prints: 3456 +``` + +
+offset
number
readUInt16BE(offset) =>
readUInt16LE
(offset) – Reads an unsigned, little-endian 16-bit integer from buf
at the specifiedoffset
.
+ +This function is also available under the `readUint16LE` alias. + +```js +import { Buffer } from 'buffer' + +const buf = Buffer.from([0x12, 0x34, 0x56]) + +console.log(buf.readUInt16LE(0).toString(16)) +// Prints: 3412 +console.log(buf.readUInt16LE(1).toString(16)) +// Prints: 5634 +console.log(buf.readUInt16LE(2).toString(16)) +// Throws ERR_OUT_OF_RANGE. +``` + +
+offset
number
readUInt16LE(offset) =>
readUInt32BE
(offset) – Reads an unsigned, big-endian 32-bit integer from buf
at the specifiedoffset
.
+ +This function is also available under the `readUint32BE` alias. + +```js +import { Buffer } from 'buffer' + +const buf = Buffer.from([0x12, 0x34, 0x56, 0x78]) + +console.log(buf.readUInt32BE(0).toString(16)) +// Prints: 12345678 +``` + +
+offset
number
readUInt32BE(offset) =>
readUInt32LE
(offset) – Reads an unsigned, little-endian 32-bit integer from buf
at the specifiedoffset
.
+ +This function is also available under the `readUint32LE` alias. + +```js +import { Buffer } from 'buffer' + +const buf = Buffer.from([0x12, 0x34, 0x56, 0x78]) + +console.log(buf.readUInt32LE(0).toString(16)) +// Prints: 78563412 +console.log(buf.readUInt32LE(1).toString(16)) +// Throws ERR_OUT_OF_RANGE. +``` + +
+offset
number
readUInt32LE(offset) =>
readUInt8
(offset) – Reads an unsigned 8-bit integer from buf
at the specified offset
.
+ +This function is also available under the `readUint8` alias. + +```js +import { Buffer } from 'buffer' + +const buf = Buffer.from([1, -2]) + +console.log(buf.readUInt8(0)) +// Prints: 1 +console.log(buf.readUInt8(1)) +// Prints: 254 +console.log(buf.readUInt8(2)) +// Throws ERR_OUT_OF_RANGE. +``` + +
+offset
number
readUInt8(offset) =>
readUIntBE
(offset, byteLength) – Reads byteLength
number of bytes from buf
at the specified offset
and interprets the result as an unsigned big-endian integer supporting
+up to 48 bits of accuracy.
+ +This function is also available under the `readUintBE` alias. + +```js +import { Buffer } from 'buffer' + +const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]) + +console.log(buf.readUIntBE(0, 6).toString(16)) +// Prints: 1234567890ab +console.log(buf.readUIntBE(1, 6).toString(16)) +// Throws ERR_OUT_OF_RANGE. +``` + +
+offset
– Number of bytes to skip before starting to read. Must satisfy 0 <= offset <= buf.length - byteLength
.number
byteLength
– Number of bytes to read. Must satisfy 0 < byteLength <= 6
.
+number
readUIntBE(offset, byteLength) =>
readUIntLE
(offset, byteLength) – Reads byteLength
number of bytes from buf
at the specified offset
and interprets the result as an unsigned, little-endian integer supporting
+up to 48 bits of accuracy.
+ +This function is also available under the `readUintLE` alias. + +```js +import { Buffer } from 'buffer' + +const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]) + +console.log(buf.readUIntLE(0, 6).toString(16)) +// Prints: ab9078563412 +``` + +
+offset
– Number of bytes to skip before starting to read. Must satisfy 0 <= offset <= buf.length - byteLength
.number
byteLength
– Number of bytes to read. Must satisfy 0 < byteLength <= 6
.
+number
readUIntLE(offset, byteLength) =>
readUint16BE
(offset) number#
offset
readUint16BE(offset) =>
readUint16LE
(offset) number#
offset
readUint16LE(offset) =>
readUint32BE
(offset) number#
offset
readUint32BE(offset) =>
readUint32LE
(offset) number#
offset
readUint32LE(offset) =>
readUint8
(offset) number#
offset
readUint8(offset) =>
readUintBE
(offset, byteLength) readUintLE
(offset, byteLength) reverse
()
reverse() =>
slice
(start, end) – Returns a new Buffer
that references the same memory as the original, but
+offset and cropped by the start
and end
indices.
+ +This is the same behavior as `buf.subarray()`. + +This method is not compatible with the `Uint8Array.prototype.slice()`, +which is a superclass of `Buffer`. To copy the slice, use`Uint8Array.prototype.slice()`. + +```js +import { Buffer } from 'buffer' + +const buf = Buffer.from('buffer') + +const copiedBuf = Uint8Array.prototype.slice.call(buf) +copiedBuf[0]++ +console.log(copiedBuf.toString()) +// Prints: cuffer + +console.log(buf.toString()) +// Prints: buffer +``` + +
+start
number
end
number
slice(start, end) =>
subarray
(start, end) – Returns a new Buffer
that references the same memory as the original, but
+offset and cropped by the start
and end
indices.
+ +Specifying `end` greater than `buf.length` will return the same result as +that of `end` equal to `buf.length`. + +This method is inherited from [`TypedArray.prototype.subarray()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/subarray). + +Modifying the new `Buffer` slice will modify the memory in the original `Buffer`because the allocated memory of the two objects overlap. + +```js +import { Buffer } from 'buffer' + +// Create a `Buffer` with the ASCII alphabet, take a slice, and modify one byte +// from the original `Buffer`. + +const buf1 = Buffer.allocUnsafe(26) + +for (let i = 0; i < 26; i++) { + // 97 is the decimal ASCII value for 'a'. + buf1[i] = i + 97 +} + +const buf2 = buf1.subarray(0, 3) + +console.log(buf2.toString('ascii', 0, buf2.length)) +// Prints: abc + +buf1[0] = 33 + +console.log(buf2.toString('ascii', 0, buf2.length)) +// Prints: !bc +``` + +Specifying negative indexes causes the slice to be generated relative to the +end of `buf` rather than the beginning. + +```js +import { Buffer } from 'buffer' + +const buf = Buffer.from('buffer') + +console.log(buf.subarray(-6, -1).toString()) +// Prints: buffe +// (Equivalent to buf.subarray(0, 5).) + +console.log(buf.subarray(-6, -2).toString()) +// Prints: buff +// (Equivalent to buf.subarray(0, 4).) + +console.log(buf.subarray(-5, -2).toString()) +// Prints: uff +// (Equivalent to buf.subarray(1, 4).) +``` + +
+start
number
end
number
subarray(start, end) =>
swap16
() – Interprets buf
as an array of unsigned 16-bit integers and swaps the
+byte order in-place. Throws ERR_INVALID_BUFFER_SIZE
if buf.length
is not a multiple of 2.
+
+```js
+import { Buffer } from 'buffer'
+
+const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8])
+
+console.log(buf1)
+// Prints:
swap16() =>
swap32
() – Interprets buf
as an array of unsigned 32-bit integers and swaps the
+byte order in-place. Throws ERR_INVALID_BUFFER_SIZE
if buf.length
is not a multiple of 4.
+
+```js
+import { Buffer } from 'buffer'
+
+const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8])
+
+console.log(buf1)
+// Prints:
swap32() =>
swap64
() – Interprets buf
as an array of 64-bit numbers and swaps byte order in-place.
+Throws ERR_INVALID_BUFFER_SIZE
if buf.length
is not a multiple of 8.
+
+```js
+import { Buffer } from 'buffer'
+
+const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8])
+
+console.log(buf1)
+// Prints:
swap64() =>
toJSON
() – Returns a JSON representation of buf
. JSON.stringify()
implicitly calls
+this function when stringifying a Buffer
instance.
+
+`Buffer.from()` accepts objects in the format returned from this method.
+In particular, `Buffer.from(buf.toJSON())` works like `Buffer.from(buf)`.
+
+```js
+import { Buffer } from 'buffer';
+
+const buf = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5]);
+const json = JSON.stringify(buf);
+
+console.log(json);
+// Prints: {"type":"Buffer","data":[1,2,3,4,5]}
+
+const copy = JSON.parse(json, (key, value) => {
+ return value && value.type === 'Buffer' ?
+ Buffer.from(value) :
+ value;
+});
+
+console.log(copy);
+// Prints:
toJSON() =>
}
toString
(encoding, start, end) – Decodes buf
to a string according to the specified character encoding inencoding
. start
and end
may be passed to decode only a subset of buf
.
+ +If `encoding` is `'utf8'` and a byte sequence in the input is not valid UTF-8, +then each invalid byte is replaced with the replacement character `U+FFFD`. + +The maximum length of a string instance (in UTF-16 code units) is available +as {@link constants.MAX_STRING_LENGTH}. + +```js +import { Buffer } from 'buffer' + +const buf1 = Buffer.allocUnsafe(26) + +for (let i = 0; i < 26; i++) { + // 97 is the decimal ASCII value for 'a'. + buf1[i] = i + 97 +} + +console.log(buf1.toString('utf8')) +// Prints: abcdefghijklmnopqrstuvwxyz +console.log(buf1.toString('utf8', 0, 5)) +// Prints: abcde + +const buf2 = Buffer.from('tést') + +console.log(buf2.toString('hex')) +// Prints: 74c3a97374 +console.log(buf2.toString('utf8', 0, 3)) +// Prints: té +console.log(buf2.toString(undefined, 0, 3)) +// Prints: té +``` + +
+encoding
start
number
end
number
toString(encoding, start, end) =>
values
() – Creates and returns an iterator for buf
values (bytes). This function is
+called automatically when a Buffer
is used in a for..of
statement.
+ +```js +import { Buffer } from 'buffer' + +const buf = Buffer.from('buffer') + +for (const value of buf.values()) { + console.log(value) +} +// Prints: +// 98 +// 117 +// 102 +// 102 +// 101 +// 114 + +for (const value of buf) { + console.log(value) +} +// Prints: +// 98 +// 117 +// 102 +// 102 +// 101 +// 114 +``` + +
+values() =>
write
(string, encoding) – Writes string
to buf
at offset
according to the character encoding inencoding
. The length
parameter is the number of bytes to write. If buf
did
+not contain enough space to fit the entire string, only part of string
will be
+written. However, partially encoded characters will not be written.
+ +```js +import { Buffer } from 'buffer' + +const buf = Buffer.alloc(256) + +const len = buf.write('\u00bd + \u00bc = \u00be', 0) + +console.log(`${len} bytes: ${buf.toString('utf8', 0, len)}`) +// Prints: 12 bytes: ½ + ¼ = ¾ + +const buffer = Buffer.alloc(10) + +const length = buffer.write('abcd', 8) + +console.log(`${length} bytes: ${buffer.toString('utf8', 8, 10)}`) +// Prints: 2 bytes : ab +``` + +
+string
– String to write to buf
.string
encoding
write(string, encoding) =>
string
string
offset
number
encoding
write(string, offset, encoding) =>
string
string
offset
number
length
number
encoding
write(string, offset, length, encoding) =>
writeBigInt64BE
(value, offset) – Writes value
to buf
at the specified offset
as big-endian.
+
+`value` is interpreted and written as a two's complement signed integer.
+
+```js
+import { Buffer } from 'buffer'
+
+const buf = Buffer.allocUnsafe(8)
+
+buf.writeBigInt64BE(0x0102030405060708n, 0)
+
+console.log(buf)
+// Prints:
value
– Number to be written to buf
.bigint
offset
number
writeBigInt64BE(value, offset) =>
writeBigInt64LE
(value, offset) – Writes value
to buf
at the specified offset
as little-endian.
+
+`value` is interpreted and written as a two's complement signed integer.
+
+```js
+import { Buffer } from 'buffer'
+
+const buf = Buffer.allocUnsafe(8)
+
+buf.writeBigInt64LE(0x0102030405060708n, 0)
+
+console.log(buf)
+// Prints:
value
– Number to be written to buf
.bigint
offset
number
writeBigInt64LE(value, offset) =>
writeBigUInt64BE
(value, offset) – Writes value
to buf
at the specified offset
as big-endian.
+
+This function is also available under the `writeBigUint64BE` alias.
+
+```js
+import { Buffer } from 'buffer'
+
+const buf = Buffer.allocUnsafe(8)
+
+buf.writeBigUInt64BE(0xdecafafecacefaden, 0)
+
+console.log(buf)
+// Prints:
value
– Number to be written to buf
.bigint
offset
number
writeBigUInt64BE(value, offset) =>
writeBigUInt64LE
(value, offset) – Writes value
to buf
at the specified offset
as little-endian
+
+```js
+import { Buffer } from 'buffer'
+
+const buf = Buffer.allocUnsafe(8)
+
+buf.writeBigUInt64LE(0xdecafafecacefaden, 0)
+
+console.log(buf)
+// Prints:
value
– Number to be written to buf
.bigint
offset
number
writeBigUInt64LE(value, offset) =>
writeBigUint64BE
(value, offset) writeBigUint64LE
(value, offset) writeDoubleBE
(value, offset) – Writes value
to buf
at the specified offset
as big-endian. The value
must be a JavaScript number. Behavior is undefined when value
is anything
+other than a JavaScript number.
+
+```js
+import { Buffer } from 'buffer'
+
+const buf = Buffer.allocUnsafe(8)
+
+buf.writeDoubleBE(123.456, 0)
+
+console.log(buf)
+// Prints:
value
– Number to be written to buf
.number
offset
number
writeDoubleBE(value, offset) =>
writeDoubleLE
(value, offset) – Writes value
to buf
at the specified offset
as little-endian. The value
must be a JavaScript number. Behavior is undefined when value
is anything
+other than a JavaScript number.
+
+```js
+import { Buffer } from 'buffer'
+
+const buf = Buffer.allocUnsafe(8)
+
+buf.writeDoubleLE(123.456, 0)
+
+console.log(buf)
+// Prints:
value
– Number to be written to buf
.number
offset
number
writeDoubleLE(value, offset) =>
writeFloatBE
(value, offset) – Writes value
to buf
at the specified offset
as big-endian. Behavior is
+undefined when value
is anything other than a JavaScript number.
+
+```js
+import { Buffer } from 'buffer'
+
+const buf = Buffer.allocUnsafe(4)
+
+buf.writeFloatBE(0xcafebabe, 0)
+
+console.log(buf)
+// Prints:
value
– Number to be written to buf
.number
offset
number
writeFloatBE(value, offset) =>
writeFloatLE
(value, offset) – Writes value
to buf
at the specified offset
as little-endian. Behavior is
+undefined when value
is anything other than a JavaScript number.
+
+```js
+import { Buffer } from 'buffer'
+
+const buf = Buffer.allocUnsafe(4)
+
+buf.writeFloatLE(0xcafebabe, 0)
+
+console.log(buf)
+// Prints:
value
– Number to be written to buf
.number
offset
number
writeFloatLE(value, offset) =>
writeInt16BE
(value, offset) – Writes value
to buf
at the specified offset
as big-endian. The value
must be a valid signed 16-bit integer. Behavior is undefined when value
is
+anything other than a signed 16-bit integer.
+
+The `value` is interpreted and written as a two's complement signed integer.
+
+```js
+import { Buffer } from 'buffer'
+
+const buf = Buffer.allocUnsafe(2)
+
+buf.writeInt16BE(0x0102, 0)
+
+console.log(buf)
+// Prints:
value
– Number to be written to buf
.number
offset
number
writeInt16BE(value, offset) =>
writeInt16LE
(value, offset) – Writes value
to buf
at the specified offset
as little-endian. The value
must be a valid signed 16-bit integer. Behavior is undefined when value
is
+anything other than a signed 16-bit integer.
+
+The `value` is interpreted and written as a two's complement signed integer.
+
+```js
+import { Buffer } from 'buffer'
+
+const buf = Buffer.allocUnsafe(2)
+
+buf.writeInt16LE(0x0304, 0)
+
+console.log(buf)
+// Prints:
value
– Number to be written to buf
.number
offset
number
writeInt16LE(value, offset) =>
writeInt32BE
(value, offset) – Writes value
to buf
at the specified offset
as big-endian. The value
must be a valid signed 32-bit integer. Behavior is undefined when value
is
+anything other than a signed 32-bit integer.
+
+The `value` is interpreted and written as a two's complement signed integer.
+
+```js
+import { Buffer } from 'buffer'
+
+const buf = Buffer.allocUnsafe(4)
+
+buf.writeInt32BE(0x01020304, 0)
+
+console.log(buf)
+// Prints:
value
– Number to be written to buf
.number
offset
number
writeInt32BE(value, offset) =>
writeInt32LE
(value, offset) – Writes value
to buf
at the specified offset
as little-endian. The value
must be a valid signed 32-bit integer. Behavior is undefined when value
is
+anything other than a signed 32-bit integer.
+
+The `value` is interpreted and written as a two's complement signed integer.
+
+```js
+import { Buffer } from 'buffer'
+
+const buf = Buffer.allocUnsafe(4)
+
+buf.writeInt32LE(0x05060708, 0)
+
+console.log(buf)
+// Prints:
value
– Number to be written to buf
.number
offset
number
writeInt32LE(value, offset) =>
writeInt8
(value, offset) – Writes value
to buf
at the specified offset
. value
must be a valid
+signed 8-bit integer. Behavior is undefined when value
is anything other than
+a signed 8-bit integer.
+
+`value` is interpreted and written as a two's complement signed integer.
+
+```js
+import { Buffer } from 'buffer'
+
+const buf = Buffer.allocUnsafe(2)
+
+buf.writeInt8(2, 0)
+buf.writeInt8(-2, 1)
+
+console.log(buf)
+// Prints:
value
– Number to be written to buf
.number
offset
number
writeInt8(value, offset) =>
writeIntBE
(value, offset, byteLength) – Writes byteLength
bytes of value
to buf
at the specified offset
as big-endian. Supports up to 48 bits of accuracy. Behavior is undefined whenvalue
is anything other than a
+signed integer.
+
+```js
+import { Buffer } from 'buffer'
+
+const buf = Buffer.allocUnsafe(6)
+
+buf.writeIntBE(0x1234567890ab, 0, 6)
+
+console.log(buf)
+// Prints:
value
– Number to be written to buf
.number
offset
– Number of bytes to skip before starting to write. Must satisfy 0 <= offset <= buf.length - byteLength
.number
byteLength
– Number of bytes to write. Must satisfy 0 < byteLength <= 6
.number
writeIntBE(value, offset, byteLength) =>
writeIntLE
(value, offset, byteLength) – Writes byteLength
bytes of value
to buf
at the specified offset
as little-endian. Supports up to 48 bits of accuracy. Behavior is undefined
+when value
is anything other than a signed integer.
+
+```js
+import { Buffer } from 'buffer'
+
+const buf = Buffer.allocUnsafe(6)
+
+buf.writeIntLE(0x1234567890ab, 0, 6)
+
+console.log(buf)
+// Prints:
value
– Number to be written to buf
.number
offset
– Number of bytes to skip before starting to write. Must satisfy 0 <= offset <= buf.length - byteLength
.number
byteLength
– Number of bytes to write. Must satisfy 0 < byteLength <= 6
.number
writeIntLE(value, offset, byteLength) =>
writeUInt16BE
(value, offset) – Writes value
to buf
at the specified offset
as big-endian. The value
must be a valid unsigned 16-bit integer. Behavior is undefined when value
is anything other than an
+unsigned 16-bit integer.
+
+This function is also available under the `writeUint16BE` alias.
+
+```js
+import { Buffer } from 'buffer'
+
+const buf = Buffer.allocUnsafe(4)
+
+buf.writeUInt16BE(0xdead, 0)
+buf.writeUInt16BE(0xbeef, 2)
+
+console.log(buf)
+// Prints:
value
– Number to be written to buf
.number
offset
number
writeUInt16BE(value, offset) =>
writeUInt16LE
(value, offset) – Writes value
to buf
at the specified offset
as little-endian. The value
must be a valid unsigned 16-bit integer. Behavior is undefined when value
is
+anything other than an unsigned 16-bit integer.
+
+This function is also available under the `writeUint16LE` alias.
+
+```js
+import { Buffer } from 'buffer'
+
+const buf = Buffer.allocUnsafe(4)
+
+buf.writeUInt16LE(0xdead, 0)
+buf.writeUInt16LE(0xbeef, 2)
+
+console.log(buf)
+// Prints:
value
– Number to be written to buf
.number
offset
number
writeUInt16LE(value, offset) =>
writeUInt32BE
(value, offset) – Writes value
to buf
at the specified offset
as big-endian. The value
must be a valid unsigned 32-bit integer. Behavior is undefined when value
is anything other than an
+unsigned 32-bit integer.
+
+This function is also available under the `writeUint32BE` alias.
+
+```js
+import { Buffer } from 'buffer'
+
+const buf = Buffer.allocUnsafe(4)
+
+buf.writeUInt32BE(0xfeedface, 0)
+
+console.log(buf)
+// Prints:
value
– Number to be written to buf
.number
offset
number
writeUInt32BE(value, offset) =>
writeUInt32LE
(value, offset) – Writes value
to buf
at the specified offset
as little-endian. The value
must be a valid unsigned 32-bit integer. Behavior is undefined when value
is
+anything other than an unsigned 32-bit integer.
+
+This function is also available under the `writeUint32LE` alias.
+
+```js
+import { Buffer } from 'buffer'
+
+const buf = Buffer.allocUnsafe(4)
+
+buf.writeUInt32LE(0xfeedface, 0)
+
+console.log(buf)
+// Prints:
value
– Number to be written to buf
.number
offset
number
writeUInt32LE(value, offset) =>
writeUInt8
(value, offset) – Writes value
to buf
at the specified offset
. value
must be a
+valid unsigned 8-bit integer. Behavior is undefined when value
is anything
+other than an unsigned 8-bit integer.
+
+This function is also available under the `writeUint8` alias.
+
+```js
+import { Buffer } from 'buffer'
+
+const buf = Buffer.allocUnsafe(4)
+
+buf.writeUInt8(0x3, 0)
+buf.writeUInt8(0x4, 1)
+buf.writeUInt8(0x23, 2)
+buf.writeUInt8(0x42, 3)
+
+console.log(buf)
+// Prints:
value
– Number to be written to buf
.number
offset
number
writeUInt8(value, offset) =>
writeUIntBE
(value, offset, byteLength) – Writes byteLength
bytes of value
to buf
at the specified offset
as big-endian. Supports up to 48 bits of accuracy. Behavior is undefined
+when value
is anything other than an unsigned integer.
+
+This function is also available under the `writeUintBE` alias.
+
+```js
+import { Buffer } from 'buffer'
+
+const buf = Buffer.allocUnsafe(6)
+
+buf.writeUIntBE(0x1234567890ab, 0, 6)
+
+console.log(buf)
+// Prints:
value
– Number to be written to buf
.number
offset
– Number of bytes to skip before starting to write. Must satisfy 0 <= offset <= buf.length - byteLength
.number
byteLength
– Number of bytes to write. Must satisfy 0 < byteLength <= 6
.number
writeUIntBE(value, offset, byteLength) =>
writeUIntLE
(value, offset, byteLength) – Writes byteLength
bytes of value
to buf
at the specified offset
as little-endian. Supports up to 48 bits of accuracy. Behavior is undefined
+when value
is anything other than an unsigned integer.
+
+This function is also available under the `writeUintLE` alias.
+
+```js
+import { Buffer } from 'buffer'
+
+const buf = Buffer.allocUnsafe(6)
+
+buf.writeUIntLE(0x1234567890ab, 0, 6)
+
+console.log(buf)
+// Prints:
value
– Number to be written to buf
.number
offset
– Number of bytes to skip before starting to write. Must satisfy 0 <= offset <= buf.length - byteLength
.number
byteLength
– Number of bytes to write. Must satisfy 0 < byteLength <= 6
.number
writeUIntLE(value, offset, byteLength) =>
writeUint16BE
(value, offset) writeUint16LE
(value, offset) writeUint32BE
(value, offset) writeUint32LE
(value, offset) writeUintBE
(value, offset, byteLength) writeUintLE
(value, offset, byteLength) BufferConstructor
– Raw data is stored in instances of the Buffer class.
+A Buffer is similar to an array of integers but corresponds to a raw memory allocation outside the V8 heap. A Buffer cannot be resized.
+Valid string encodings: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'base64url'|'binary'(deprecated)|'hex' number
+
+```js
+import { Buffer } from 'buffer'
+
+const buf = Buffer.alloc(5)
+
+console.log(buf)
+// Prints: number alloc(size, fill, encoding) => #
constructor
(str, encoding) – Allocates a new buffer containing the given {str}.
#
new BufferConstructor
() – Allocates a new buffer containing the given {str}.#
new BufferConstructor
() – Allocates a new buffer of {size} octets.#
new BufferConstructor
() – Allocates a new buffer containing the given {array} of octets.#
new BufferConstructor
() – Produces a Buffer backed by the same allocated memory as
+the given {ArrayBuffer}/{SharedArrayBuffer}.#
new BufferConstructor
() – Allocates a new buffer containing the given {array} of octets.#
src/.fastpm/-/@types/node@17.0.45/buffer.d.ts#L529 poolSize
– This is the size (in bytes) of pre-allocated internal Buffer
instances used
+for pooling. This value may be modified.#
alloc
(size, fill, encoding) – Allocates a new Buffer
of size
bytes. If fill
is undefined
, theBuffer
will be zero-filled.
#
size
– The desired length of the new Buffer
.#
encoding
allocUnsafe
(size) – Allocates a new Buffer
of size
bytes. If size
is larger than {@link constants.MAX_LENGTH} or smaller than 0, ERR_INVALID_ARG_VALUE
is thrown.
+
+The underlying memory for `Buffer` instances created in this way is _not_
+_initialized_. The contents of the newly created `Buffer` are unknown and _may contain sensitive data_. Use `Buffer.alloc()` instead to initialize`Buffer` instances with zeroes.
+
+```js
+import { Buffer } from 'buffer'
+
+const buf = Buffer.allocUnsafe(10)
+
+console.log(buf)
+// Prints (contents may vary):
size
– The desired length of the new Buffer
.
+number
allocUnsafe(size) =>
allocUnsafeSlow
(size) – Allocates a new Buffer
of size
bytes. If size
is larger than {@link constants.MAX_LENGTH} or smaller than 0, ERR_INVALID_ARG_VALUE
is thrown. A zero-length Buffer
is created
+if size
is 0.
+ +The underlying memory for `Buffer` instances created in this way is _not_ +_initialized_. The contents of the newly created `Buffer` are unknown and_may contain sensitive data_. Use `buf.fill(0)` to initialize +such `Buffer` instances with zeroes. + +When using `Buffer.allocUnsafe()` to allocate new `Buffer` instances, +allocations under 4 KB are sliced from a single pre-allocated `Buffer`. This +allows applications to avoid the garbage collection overhead of creating many +individually allocated `Buffer` instances. This approach improves both +performance and memory usage by eliminating the need to track and clean up as +many individual `ArrayBuffer` objects. + +However, in the case where a developer may need to retain a small chunk of +memory from a pool for an indeterminate amount of time, it may be appropriate +to create an un-pooled `Buffer` instance using `Buffer.allocUnsafeSlow()` and +then copying out the relevant bits. + +```js +import { Buffer } from 'buffer' + +// Need to keep around a few small chunks of memory. +const store = [] + +socket.on('readable', () => { + let data + while (null !== (data = readable.read())) { + // Allocate for retained data. + const sb = Buffer.allocUnsafeSlow(10) + + // Copy the data into the new allocation. + data.copy(sb, 0, 0, 10) + + store.push(sb) + } +}) +``` + +A `TypeError` will be thrown if `size` is not a number. + +
+size
– The desired length of the new Buffer
.
+number
allocUnsafeSlow(size) =>
byteLength
(string, encoding) – Returns the byte length of a string when encoded using encoding
.
+This is not the same as String.prototype.length
, which does not account
+for the encoding that is used to convert the string into bytes.
+ +For `'base64'`, `'base64url'`, and `'hex'`, this function assumes valid input. +For strings that contain non-base64/hex-encoded data (e.g. whitespace), the +return value might be greater than the length of a `Buffer` created from the +string. + +```js +import { Buffer } from 'buffer' + +const str = '\u00bd + \u00bc = \u00be' + +console.log( + `${str}: ${str.length} characters, ` + + `${Buffer.byteLength(str, 'utf8')} bytes` +) +// Prints: ½ + ¼ = ¾: 9 characters, 12 bytes +``` + +When `string` is a +`Buffer`/[`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView)/[`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/- +Reference/Global_Objects/TypedArray)/[`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer)/[`SharedArrayBuffer`](https://develop- +er.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer), the byte length as reported by `.byteLength`is returned. + +
+string
– A value to calculate the length of.string | ArrayBuffer | SharedArrayBuffer | ArrayBufferView
encoding
byteLength(string, encoding) =>
compare
(buf1, buf2) – Compares buf1
to buf2
, typically for the purpose of sorting arrays ofBuffer
instances. This is equivalent to calling buf1.compare(buf2)
.
+
+```js
+import { Buffer } from 'buffer'
+
+const buf1 = Buffer.from('1234')
+const buf2 = Buffer.from('0123')
+const arr = [buf1, buf2]
+
+console.log(arr.sort(Buffer.compare))
+// Prints: [
buf1
Uint8Array
buf2
Uint8Array
compare(buf1, buf2) =>
0
| 1
| -1
concat
(list, totalLength) – Returns a new Buffer
which is the result of concatenating all the Buffer
instances in the list
together.
+
+If the list has no items, or if the `totalLength` is 0, then a new zero-length`Buffer` is returned.
+
+If `totalLength` is not provided, it is calculated from the `Buffer` instances
+in `list` by adding their lengths.
+
+If `totalLength` is provided, it is coerced to an unsigned integer. If the
+combined length of the `Buffer`s in `list` exceeds `totalLength`, the result is
+truncated to `totalLength`.
+
+```js
+import { Buffer } from 'buffer'
+
+// Create a single `Buffer` from a list of three `Buffer` instances.
+
+const buf1 = Buffer.alloc(10)
+const buf2 = Buffer.alloc(14)
+const buf3 = Buffer.alloc(18)
+const totalLength = buf1.length + buf2.length + buf3.length
+
+console.log(totalLength)
+// Prints: 42
+
+const bufA = Buffer.concat([buf1, buf2, buf3], totalLength)
+
+console.log(bufA)
+// Prints:
list
– List of Buffer
or {@link Uint8Array} instances to concatenate.readonly Uint8Array []
totalLength
– Total length of the Buffer
instances in list
when concatenated.
+number
concat(list, totalLength) =>
from
(arrayBuffer, byteOffset, length) – Allocates a new Buffer
using an array
of bytes in the range 0
– 255
.
+Array entries outside that range will be truncated to fit into it.
+ +```js +import { Buffer } from 'buffer' + +// Creates a new Buffer containing the UTF-8 bytes of the string 'buffer'. +const buf = Buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]) +``` + +A `TypeError` will be thrown if `array` is not an `Array` or another type +appropriate for `Buffer.from()` variants. + +`Buffer.from(array)` and `Buffer.from(string)` may also use the internal`Buffer` pool like `Buffer.allocUnsafe()` does. + +
+arrayBuffer
WithImplicitCoercion<ArrayBuffer | SharedArrayBuffer>
byteOffset
number
length
number
from(arrayBuffer, byteOffset, length) =>
data
– data to create a new Buffer
+Uint8Array | readonly number []
from(data) =>
data
WithImplicitCoercion<string | Uint8Array | readonly number []>
from(data) =>
str
WithImplicitCoercion<string> | {
encoding
from(str, encoding) =>
isBuffer
(obj) – Returns true
if obj
is a Buffer
, false
otherwise.
+ +```js +import { Buffer } from 'buffer' + +Buffer.isBuffer(Buffer.alloc(10)) // true +Buffer.isBuffer(Buffer.from('foo')) // true +Buffer.isBuffer('a string') // false +Buffer.isBuffer([]) // false +Buffer.isBuffer(new Uint8Array(1024)) // false +``` + +
+obj
any
isBuffer(obj) =>
isEncoding
(encoding) – Returns true
if encoding
is the name of a supported character encoding,
+or false
otherwise.
+ +```js +import { Buffer } from 'buffer' + +console.log(Buffer.isEncoding('utf8')) +// Prints: true + +console.log(Buffer.isEncoding('hex')) +// Prints: true + +console.log(Buffer.isEncoding('utf/8')) +// Prints: false + +console.log(Buffer.isEncoding('')) +// Prints: false +``` + +
+encoding
– A character encoding name to check.
+string
isEncoding(encoding) =>
of
(items) – Creates a new Buffer using the passed {data} number []#
items
of(items) =>
BuildFailure
BuildIncremental
Record<string, string | OutputFile []#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L217 mangleCache
– Only when "mangleCache" is presentfalse
>#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L209 outputFiles
– Only when "write: false"#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L202 rebuild
– Only when "incremental: true"
BuildInvalidate
BuildInvalidate() =>
dispose() => #
dispose
()
void
BuildOptions
string number number boolean string | string | boolean
+
+Example:
+
+```json
+{
+ "main.js": {
+ "file": "main.68fe3fad.js",
+ "css": "main.e6b63442.css",
+ "imports": [...],
+ "dynamicImports": [...]
+ }
+}
+```
+
+ boolean | string boolean boolean boolean | string | boolean string | boolean string |
+
+Default: 'modules' - Similar to `@babel/preset-env`'s targets.esmodules,
+transpile targeting browsers that natively support dynamic es module imports.
+https://caniuse.com/es6-module-dynamic-import
+
+Another special value is 'esnext' - which only performs minimal transpiling
+(for minification compat) and assumes native dynamic imports support.
+
+For custom targets, see https://esbuild.github.io/api/#target and
+https://esbuild.github.io/content-types/#javascript for more details.
+
+ boolean#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L142 assetsDir
– Directory relative from outDir
where the built js/css/image assets will
+be placed.#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L148 assetsInlineLimit
– Static asset files smaller than this number (in bytes) will be inlined as
+base64 strings. Default limit is 4096
(4kb). Set to 0
to disable.#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L252 chunkSizeWarningLimit
– Adjust chunk size warning limit (in kbs).#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L192 commonjsOptions
– Options to pass on to @rollup/plugin-commonjs
#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L155 cssCodeSplit
– Whether to code-split CSS. When enabled, CSS in async chunks will be
+inlined as strings in the chunk and inserted via dynamically created
+style tags when the chunk is loaded.#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L164 cssTarget
– An optional separate target for CSS minification.
+As esbuild only supports configuring targets to mainstream
+browsers, users may need this option when they are targeting
+a niche browser that comes with most modern JavaScript features
+but has poor CSS support, e.g. Android WeChat WebView, which
+doesn't support the #RGBA syntax.false
| string []#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L196 dynamicImportVarsOptions
– Options to pass on to @rollup/plugin-dynamic-import-vars
#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L206 emptyOutDir
– Empty outDir on write.null
| boolean#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L232 lib
– Build in library mode. The value should be the global name of the lib in
+UMD mode. This will produce esm + cjs + umd bundle formats with default
+configurations that are suitable for distributing libraries.false
| LibraryOptions#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L226 manifest
– Whether to emit a manifest.json under assets dir to map hash-less filenames
+to their hashed versions. Useful when you want to generate your own HTML
+instead of using the one generated by Vite.#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L178 minify
– Set to false
to disable minification, or specify the minifier to use.
+Available options are 'terser' or 'esbuild'."esbuild"
| "terser"
#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L136 outDir
– Directory relative from root
where build output will be placed. If the
+directory exists, it will be removed before the build.#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L130 polyfillModulePreload
– whether to inject module preload polyfill.
+Note: does not apply to library mode.#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L247 reportCompressedSize
– Set to false to disable reporting compressed chunk sizes.
+Can slightly improve build speed.#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L188 rollupOptions
– Will be merged with internal rollup options.
+https://rollupjs.org/guide/en/#big-list-of-options#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L172 sourcemap
– If true
, a separate sourcemap file will be created. If 'inline', the
+sourcemap will be appended to the resulting output file as data URI.
+'hidden' works like true
except that the corresponding sourcemap
+comments in the bundled files are suppressed."inline"
| "hidden"
#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L237 ssr
– Produce SSR oriented build. Note this requires specifying SSR entry via
+rollupOptions.input
.#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L242 ssrManifest
– Generate SSR manifest for determining style links and asset preload
+directives in production.#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L124 target
– Compatibility transform target. The transform is performed with esbuild
+and the lowest supported target is es2015/es6. Note this only handles
+syntax transformation and does not cover polyfills (except for dynamic
+import)false
| string []#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L183 terserOptions
– Options for terser
+https://terser.org/docs/api-reference#minify-options#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L257 watch
– Rollup watch options
+https://rollupjs.org/guide/en/#watchoptionsnull
| WatcherOptions#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L201 write
– Whether to write bundle to disk
BuildOptions
string boolean string boolean string boolean string [] {} Drop [] string string [] | Record<string, string> string [] string boolean boolean string [] boolean string string string boolean {} number Record<string, LogLevel> string [] Record<string, string | RegExp boolean boolean boolean boolean boolean boolean string [] {} string string string Plugin [] boolean string string [] RegExp string [] string boolean | boolean boolean Record<string, boolean> string | string [] boolean string boolean | WatchMode boolean#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L138 absWorkingDir
– Documentation: https://esbuild.github.io/api/#working-directory#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L110 allowOverwrite
– Documentation: https://esbuild.github.io/api/#allow-overwrite#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L122 assetNames
– Documentation: https://esbuild.github.io/api/#asset-names#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L84 bundle
– Documentation: https://esbuild.github.io/api/#bundle#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L48 charset
– Documentation: https://esbuild.github.io/api/#charset#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L120 chunkNames
– Documentation: https://esbuild.github.io/api/#chunk-names#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L73 color
– Documentation: https://esbuild.github.io/api/#color#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L106 conditions
– Documentation: https://esbuild.github.io/api/#conditions#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L66 define
– Documentation: https://esbuild.github.io/api/#define#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L38 drop
– Documentation: https://esbuild.github.io/api/#drop#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L118 entryNames
– Documentation: https://esbuild.github.io/api/#entry-names#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L132 entryPoints
– Documentation: https://esbuild.github.io/api/#entry-points#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L98 external
– Documentation: https://esbuild.github.io/api/#external#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L19 format
– Documentation: https://esbuild.github.io/api/#format#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L21 globalName
– Documentation: https://esbuild.github.io/api/#global-name#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L52 ignoreAnnotations
– Documentation: https://esbuild.github.io/api/#ignore-annotations#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L130 incremental
– Documentation: https://esbuild.github.io/api/#incremental#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L124 inject
– Documentation: https://esbuild.github.io/api/#inject#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L55 jsx
– Documentation: https://esbuild.github.io/api/#jsx"transform"
| "preserve"
| "automatic"
#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L63 jsxDev
– Documentation: https://esbuild.github.io/api/#jsx-development#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L57 jsxFactory
– Documentation: https://esbuild.github.io/api/#jsx-factory#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L59 jsxFragment
– Documentation: https://esbuild.github.io/api/#jsx-fragment#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L61 jsxImportSource
– Documentation: https://esbuild.github.io/api/#jsx-import-source#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L70 keepNames
– Documentation: https://esbuild.github.io/api/#keep-names#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L12 legalComments
– Documentation: https://esbuild.github.io/api/#legal-comments"external"
| "none"
| "inline"
| "eof"
| "linked"
#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L100 loader
– Documentation: https://esbuild.github.io/api/#loader#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L75 logLevel
– Documentation: https://esbuild.github.io/api/#log-level#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L77 logLimit
– Documentation: https://esbuild.github.io/api/#log-limit#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L79 logOverride
– Documentation: https://esbuild.github.io/api/#log-override#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L104 mainFields
– Documentation: https://esbuild.github.io/api/#main-fields#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L36 mangleCache
– Documentation: https://esbuild.github.io/api/#mangle-propsfalse
>#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L30 mangleProps
– Documentation: https://esbuild.github.io/api/#mangle-props#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L34 mangleQuoted
– Documentation: https://esbuild.github.io/api/#mangle-props#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L92 metafile
– Documentation: https://esbuild.github.io/api/#metafile#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L40 minify
– Documentation: https://esbuild.github.io/api/#minify#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L44 minifyIdentifiers
– Documentation: https://esbuild.github.io/api/#minify#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L46 minifySyntax
– Documentation: https://esbuild.github.io/api/#minify#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L42 minifyWhitespace
– Documentation: https://esbuild.github.io/api/#minify#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L140 nodePaths
– Documentation: https://esbuild.github.io/api/#node-paths#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L114 outExtension
– Documentation: https://esbuild.github.io/api/#out-extension#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L96 outbase
– Documentation: https://esbuild.github.io/api/#outbase#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L94 outdir
– Documentation: https://esbuild.github.io/api/#outdir#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L90 outfile
– Documentation: https://esbuild.github.io/api/#outfile#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L27 platform
– Documentation: https://esbuild.github.io/api/#platform#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L136 plugins
– Documentation: https://esbuild.github.io/plugins/#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L88 preserveSymlinks
– Documentation: https://esbuild.github.io/api/#preserve-symlinks#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L116 publicPath
– Documentation: https://esbuild.github.io/api/#public-path#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L68 pure
– Documentation: https://esbuild.github.io/api/#pure#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L32 reserveProps
– Documentation: https://esbuild.github.io/api/#mangle-props#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L102 resolveExtensions
– Documentation: https://esbuild.github.io/api/#resolve-extensions#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L14 sourceRoot
– Documentation: https://esbuild.github.io/api/#source-root#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L10 sourcemap
– Documentation: https://esbuild.github.io/api/#sourcemap"external"
| "inline"
| "linked"
| "both"
#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L16 sourcesContent
– Documentation: https://esbuild.github.io/api/#sources-content#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L86 splitting
– Documentation: https://esbuild.github.io/api/#splitting#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L134 stdin
– Documentation: https://esbuild.github.io/api/#stdin#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L25 supported
– Documentation: https://esbuild.github.io/api/#supported#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L23 target
– Documentation: https://esbuild.github.io/api/#target#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L50 treeShaking
– Documentation: https://esbuild.github.io/api/#tree-shaking#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L112 tsconfig
– Documentation: https://esbuild.github.io/api/#tsconfig#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L142 watch
– Documentation: https://esbuild.github.io/api/#watch#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L108 write
– Documentation: https://esbuild.github.io/api/#write
BuildResult
Record<string, string | OutputFile []#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L217 mangleCache
– Only when "mangleCache" is presentfalse
>#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L209 outputFiles
– Only when "write: false"#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L211 rebuild
– Only when "incremental: true"
Builder
CSSModulesOptions
globalModulePaths
RegExp []
hashPrefix
string
localsConvention
– default: nullnull
| "camelCase"
| "camelCaseOnly"
| "dashes"
| "dashesOnly"
scopeBehaviour
"global"
| "local"
getJSON
(cssFileName, json, outputFileName) CSSOptions
boolean#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L489 devSourcemap
– Enables css sourcemaps during dev#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L479 modules
– https://github.com/css-modules/postcss-modulesfalse
| CSSModulesOptions
preprocessorOptions
Record<string, any>
Certificate
ChokidarOptions
binaryInterval
number
cwd
string
depth
number
disableGlobbing
boolean
followSymlinks
boolean
ignoreInitial
boolean
ignorePermissionErrors
boolean
ignored
any
interval
number
persistent
boolean
useFsEvents
boolean
usePolling
boolean
CipherNameAndProtocol
string#
src/.fastpm/-/@types/node@17.0.45/tls.d.ts#L73 standardName
– IETF name for the cipher suite.
ClientRequestArgs
(options, oncreate) =>
defaultPort
string | number
family
number
headers
host
null
| string
hostname
null
| string
localAddress
string
lookup
maxHeaderSize
number
method
string
path
null
| string
port
null
| string | number
protocol
null
| string
setHost
boolean
signal
AbortSignal
socketPath
string
timeout
number
CloseEvent
CommentProps
#
src/.fastpm/-/postcss@8.4.14/lib/comment.d.ts#L25 raws
– Information used to generate byte-to-byte equal node string as it was in the origin input.
CommentRaws
string string string#
src/.fastpm/-/postcss@8.4.14/lib/comment.d.ts#L8 before
– The space symbols before the node.#
src/.fastpm/-/postcss@8.4.14/lib/comment.d.ts#L13 left
– The space symbols between /*
and the comment’s text.#
src/.fastpm/-/postcss@8.4.14/lib/comment.d.ts#L18 right
– The space symbols between the comment’s text.
CommonConnectionOptions
string [] | Uint8Array | Uint8Array []#
src/.fastpm/-/@types/node@17.0.45/tls.d.ts#L447 ALPNProtocols
– An array of strings or a Buffer naming possible ALPN protocols.
+(Protocols should be ordered by their priority.)#
src/.fastpm/-/@types/node@17.0.45/tls.d.ts#L457 SNICallback
# (servername, cb) – SNICallback(servername, cb) <Function> A function that will be
+called if the client supports SNI TLS extension. Two arguments
+will be passed when called: servername and cb. SNICallback should
+invoke cb(null, ctx), where ctx is a SecureContext instance.
+(tls.createSecureContext(...) can be used to get a proper
+SecureContext.) If SNICallback wasn't provided the default callback
+with high-level API will be used (see below).
(servername, cb) =>
enableTrace
– When enabled, TLS packet trace information is written to stderr
. This can be
+used to debug TLS connection problems.boolean
requestCert
– If true the server will request a certificate from clients that
+connect and attempt to verify that certificate. Defaults to
+false.boolean
secureContext
– An optional TLS context object from tls.createSecureContext()CommonOptions
boolean {} Drop [] string boolean boolean string string string boolean number Record<string, LogLevel> Record<string, string | RegExp boolean boolean boolean boolean boolean string [] RegExp string boolean | boolean Record<string, boolean> string | string [] boolean#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L48 charset
– Documentation: https://esbuild.github.io/api/#charset#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L73 color
– Documentation: https://esbuild.github.io/api/#color#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L66 define
– Documentation: https://esbuild.github.io/api/#define#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L38 drop
– Documentation: https://esbuild.github.io/api/#drop#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L19 format
– Documentation: https://esbuild.github.io/api/#format#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L21 globalName
– Documentation: https://esbuild.github.io/api/#global-name#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L52 ignoreAnnotations
– Documentation: https://esbuild.github.io/api/#ignore-annotations#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L55 jsx
– Documentation: https://esbuild.github.io/api/#jsx"transform"
| "preserve"
| "automatic"
#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L63 jsxDev
– Documentation: https://esbuild.github.io/api/#jsx-development#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L57 jsxFactory
– Documentation: https://esbuild.github.io/api/#jsx-factory#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L59 jsxFragment
– Documentation: https://esbuild.github.io/api/#jsx-fragment#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L61 jsxImportSource
– Documentation: https://esbuild.github.io/api/#jsx-import-source#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L70 keepNames
– Documentation: https://esbuild.github.io/api/#keep-names#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L12 legalComments
– Documentation: https://esbuild.github.io/api/#legal-comments"external"
| "none"
| "inline"
| "eof"
| "linked"
#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L75 logLevel
– Documentation: https://esbuild.github.io/api/#log-level#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L77 logLimit
– Documentation: https://esbuild.github.io/api/#log-limit#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L79 logOverride
– Documentation: https://esbuild.github.io/api/#log-override#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L36 mangleCache
– Documentation: https://esbuild.github.io/api/#mangle-propsfalse
>#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L30 mangleProps
– Documentation: https://esbuild.github.io/api/#mangle-props#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L34 mangleQuoted
– Documentation: https://esbuild.github.io/api/#mangle-props#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L40 minify
– Documentation: https://esbuild.github.io/api/#minify#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L44 minifyIdentifiers
– Documentation: https://esbuild.github.io/api/#minify#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L46 minifySyntax
– Documentation: https://esbuild.github.io/api/#minify#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L42 minifyWhitespace
– Documentation: https://esbuild.github.io/api/#minify#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L27 platform
– Documentation: https://esbuild.github.io/api/#platform#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L68 pure
– Documentation: https://esbuild.github.io/api/#pure#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L32 reserveProps
– Documentation: https://esbuild.github.io/api/#mangle-props#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L14 sourceRoot
– Documentation: https://esbuild.github.io/api/#source-root#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L10 sourcemap
– Documentation: https://esbuild.github.io/api/#sourcemap"external"
| "inline"
| "linked"
| "both"
#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L16 sourcesContent
– Documentation: https://esbuild.github.io/api/#sources-content#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L25 supported
– Documentation: https://esbuild.github.io/api/#supported#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L23 target
– Documentation: https://esbuild.github.io/api/#target#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L50 treeShaking
– Documentation: https://esbuild.github.io/api/#tree-shaking
CommonServerOptions
boolean | CorsOptions string | boolean boolean | ServerOptions string | boolean number Record<string, string | ProxyOptions>
+
+Example `vite.config.js`:
+
+```js
+module.exports = {
+ proxy: {
+ // string shorthand
+ '/foo': 'http://localhost:4567/foo',
+ // with options
+ '/api': {
+ target: 'http://jsonplaceholder.typicode.com',
+ changeOrigin: true,
+ rewrite: path => path.replace(/^\/api/, ''),
+ },
+ },
+}
+```
+
+ boolean#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L319 cors
– Configure CORS for the dev server.
+Uses https://github.com/expressjs/cors.
+Set to true
to allow all methods from any origin, or configure separately
+using an object.#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L323 headers
– Specify server response headers.#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L280 host
– Specify which IP addresses the server should listen on.
+Set to 0.0.0.0 to listen on all addresses, including LAN and public addresses.#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L285 https
– Enable TLS + HTTP/2.
+Note: this downgrades to TLS only when the proxy option is also used.#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L289 open
– Open browser window on startup#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L271 port
– Specify server port. Note if the port is already being used, Vite will
+automatically try the next available port so this may not be the actual
+port the server ends up listening on.#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L312 proxy
– Configure custom proxy rules for the dev server. Expects an object
+of { key: options }
pairs.
+Uses http-proxy
.
+Full options here.#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L275 strictPort
– If enabled, vite will exit if specified port is already in use
CompressOptions
ConfigEnv
ConnectOpts
#
src/.fastpm/-/@types/node@17.0.45/net.d.ts#L47 onread
– If specified, incoming data is stored in a single buffer and passed to the supplied callback when data arrives on the socket.
+Note: this will cause the streaming functionality to not provide any data, however events like 'error', 'end', and 'close' will
+still be emitted as normal and methods like pause() and resume() will also behave as expected.
ConnectedPayload
ContainerProps
CorsOptions
– https://github.com/expressjs/cors#configuration-options
(origin, cb) =>
preflightContinue
boolean
CustomEventMap
CustomPayload
CustomPluginOptions
DOMEventTarget
opts
{
}
addEventListener(eventName, listener, { once }) =>
DeclarationProps
boolean#
src/.fastpm/-/postcss@8.4.14/lib/declaration.d.ts#L36 important
– Whether the declaration has an !important
annotation.#
src/.fastpm/-/postcss@8.4.14/lib/declaration.d.ts#L38 raws
– Information used to generate byte-to-byte equal node string as it was in the origin input.
DeclarationRaws
string string string { #
src/.fastpm/-/postcss@8.4.14/lib/declaration.d.ts#L9 before
– The space symbols before the node. It also stores *
+and _
symbols before the declaration (IE hack).#
src/.fastpm/-/postcss@8.4.14/lib/declaration.d.ts#L14 between
– The symbols between the property and value for declarations.#
src/.fastpm/-/postcss@8.4.14/lib/declaration.d.ts#L19 important
– The content of the important statement, if it is not just !important
.#
src/.fastpm/-/postcss@8.4.14/lib/declaration.d.ts#L24 value
– Declaration value with comments.
DepOptimizationConfig
boolean | Omit<BuildOptions,
+
+Certain options are omitted since changing them would not be compatible
+with Vite's dep optimization.
+
+- `external` is also omitted, use Vite's `optimizeDeps.exclude` option
+- `plugins` are merged with Vite's dep plugin
+
+https://esbuild.github.io/api
+
+ string [] string []
+
+By default, Vite can optimize `.mjs`, `.js`, `.ts`, and `.mts` files. This option
+allows specifying additional extensions.
+
+ string [] string []#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L559 disabled
– Disables dependencies optimizations, true disables the optimizer during
+build and dev. Pass 'build' or 'dev' to only disable the optimizer in
+one of the modes. Deps optimization is enabled by default in dev only."build"
| "dev"
#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L541 esbuildOptions
– Options to pass to esbuild during the dep scanning and optimization"bundle"
| "entryPoints"
| "external"
| "write"
| "watch"
| "outdir"
| "outfile"
| "outbase"
| "outExtension"
| "metafile"
>#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L523 exclude
– Do not optimize these dependencies (must be resolvable import paths,
+cannot be globs).#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L551 extensions
– List of file extensions that can be optimized. A corresponding esbuild
+plugin must exist to handle the specific extension.#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L518 include
– Force optimize listed dependencies (must be resolvable import paths,
+cannot be globs).#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L529 needsInterop
– Force ESM interop when importing for these dependencies. Some legacy
+packages advertise themselves as ESM but use require
internally
DepOptimizationMetadata
string Record<string, OptimizedDepInfo> Record<string, OptimizedDepInfo> string Record<string, OptimizedDepInfo>#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L573 browserHash
– The browser hash is determined by the main hash plus additional dependencies
+discovered at runtime. This is used to invalidate browser requests to
+optimized deps.#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L581 chunks
– Metadata for non-entry optimized chunks and dynamic imports#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L589 depInfoList
– OptimizedDepInfo list#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L585 discovered
– Metadata for each newly discovered dependency after processing#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L567 hash
– The main hash is determined by user config and dependency lockfiles.
+This is checked on server startup to avoid unnecessary re-bundles.#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L577 optimized
– Metadata for each already optimized dependency
DepsOptimizer
#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L635 delayDepsOptimizerUntil
(id, done)
delayDepsOptimizerUntil(id, done) =>
ensureFirstRun
()
ensureFirstRun() =>
getOptimizedDepId
(depInfo) #
depInfo
getOptimizedDepId(depInfo) =>
isOptimizedDepFile
(id) string#
id
isOptimizedDepFile(id) =>
isOptimizedDepUrl
(url) string#
url
isOptimizedDepUrl(url) =>
registerMissingImport
(id, resolved) registerWorkersSource
(id) string#
id
registerWorkersSource(id) =>
resetRegisteredIds
()
resetRegisteredIds() =>
run
()
run() =>
DetailedPeerCertificate
Dict
DocumentProps
Record<string, any>
+
+Every parser saves its own properties.
+
+#
src/.fastpm/-/postcss@8.4.14/lib/document.d.ts#L15 raws
– Information to generate byte-to-byte equal node string as it was
+in the origin input.
DuplexOptions
AbortSignal#
src/.fastpm/-/@types/node@17.0.45/events.d.ts#L317 signal
– When provided the corresponding AbortController
can be used to cancel an asynchronous action.
construct(this, callback) =>
destroy
(this, error, callback) #
error
null
| Error
destroy(this, error, callback) =>
final
(this, callback)
final(this, callback) =>
write
(this, chunk, encoding, callback) write(this, chunk, encoding, callback) =>
writev
(this, chunks, callback) { #
chunks
callback
(error) #
error
null
| Error
callback(error) =>
writev(this, chunks, callback) =>
ESBuildOptions
boolean {} Drop [] string | RegExp | string [] | RegExp [] string boolean string | RegExp | string [] | RegExp [] boolean string string string boolean number Record<string, LogLevel> Record<string, string | RegExp boolean undefined boolean boolean boolean string [] RegExp string boolean | boolean Record<string, boolean> string | string [] boolean string | { { #
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L48 charset
– Documentation: https://esbuild.github.io/api/#charset#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L73 color
– Documentation: https://esbuild.github.io/api/#color#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L66 define
– Documentation: https://esbuild.github.io/api/#define#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L38 drop
– Documentation: https://esbuild.github.io/api/#drop#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L662 exclude
#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L19 format
– Documentation: https://esbuild.github.io/api/#format#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L21 globalName
– Documentation: https://esbuild.github.io/api/#global-name#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L52 ignoreAnnotations
– Documentation: https://esbuild.github.io/api/#ignore-annotations#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L661 include
#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L55 jsx
– Documentation: https://esbuild.github.io/api/#jsx"transform"
| "preserve"
| "automatic"
#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L63 jsxDev
– Documentation: https://esbuild.github.io/api/#jsx-development#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L57 jsxFactory
– Documentation: https://esbuild.github.io/api/#jsx-factory#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L59 jsxFragment
– Documentation: https://esbuild.github.io/api/#jsx-fragment#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L61 jsxImportSource
– Documentation: https://esbuild.github.io/api/#jsx-import-source#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L70 keepNames
– Documentation: https://esbuild.github.io/api/#keep-names#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L12 legalComments
– Documentation: https://esbuild.github.io/api/#legal-comments"external"
| "none"
| "inline"
| "eof"
| "linked"
#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L75 logLevel
– Documentation: https://esbuild.github.io/api/#log-level#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L77 logLimit
– Documentation: https://esbuild.github.io/api/#log-limit#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L79 logOverride
– Documentation: https://esbuild.github.io/api/#log-override#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L36 mangleCache
– Documentation: https://esbuild.github.io/api/#mangle-propsfalse
>#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L30 mangleProps
– Documentation: https://esbuild.github.io/api/#mangle-props#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L34 mangleQuoted
– Documentation: https://esbuild.github.io/api/#mangle-props#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L667 minify
– This option is not respected. Use build.minify
instead.#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L44 minifyIdentifiers
– Documentation: https://esbuild.github.io/api/#minify#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L46 minifySyntax
– Documentation: https://esbuild.github.io/api/#minify#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L42 minifyWhitespace
– Documentation: https://esbuild.github.io/api/#minify#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L27 platform
– Documentation: https://esbuild.github.io/api/#platform#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L68 pure
– Documentation: https://esbuild.github.io/api/#pure#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L32 reserveProps
– Documentation: https://esbuild.github.io/api/#mangle-props#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L14 sourceRoot
– Documentation: https://esbuild.github.io/api/#source-root#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L10 sourcemap
– Documentation: https://esbuild.github.io/api/#sourcemap"external"
| "inline"
| "linked"
| "both"
#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L16 sourcesContent
– Documentation: https://esbuild.github.io/api/#sources-content#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L25 supported
– Documentation: https://esbuild.github.io/api/#supported#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L23 target
– Documentation: https://esbuild.github.io/api/#target#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L50 treeShaking
– Documentation: https://esbuild.github.io/api/#tree-shaking#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L251 tsconfigRaw
#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L252 compilerOptions
#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L256 importsNotUsedAsValues
"error"
| "preserve"
| "remove"
EmittedAsset
EmittedChunk
EphemeralKeyInfo
string number string#
src/.fastpm/-/@types/node@17.0.45/tls.d.ts#L83 name
– The name property is available only when type is 'ECDH'.#
src/.fastpm/-/@types/node@17.0.45/tls.d.ts#L87 size
– The size of parameter of an ephemeral key exchange.#
src/.fastpm/-/@types/node@17.0.45/tls.d.ts#L79 type
– The supported types are 'DH' and 'ECDH'.
ErrnoException
ErrorEvent
ErrorPayload
type
"error"
Event
EventEmitter
addListener(eventName, listener) =>
emit
(eventName, args) – Synchronously calls each of the listeners registered for the event namedeventName
, in the order they were registered, passing the supplied arguments
+to each.
+ +Returns `true` if the event had listeners, `false` otherwise. + +```js +const EventEmitter = require('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 +``` + +
+eventName
string | symbol
args
any []
emit(eventName, args) =>
eventNames
() – Returns an array listing the events for which the emitter has registered
+listeners. The values in the array are strings or Symbol
s.
+ +```js +const EventEmitter = require('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) ] +``` + +
+eventNames() =>
getMaxListeners
() – Returns the current max listener value for the EventEmitter
which is either
+set by emitter.setMaxListeners(n)
or defaults to {@link defaultMaxListeners}.
getMaxListeners() =>
listenerCount
(eventName) – Returns the number of listeners listening to the event named eventName
. string | symbol#
eventName
– The name of the event being listened for
+
listenerCount(eventName) =>
listeners
(eventName) – Returns a copy of the array of listeners for the event named eventName
.
+ +```js +server.on('connection', stream => { + console.log('someone connected!') +}) +console.log(util.inspect(server.listeners('connection'))) +// Prints: [ [Function] ] +``` + +
+eventName
string | symbol
listeners(eventName) =>
off
(eventName, listener) – Alias for emitter.removeListener()
. string | symbol#
eventName
off(eventName, listener) =>
on
(eventName, listener) – 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.
+ +```js +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. + +```js +const myEE = new EventEmitter() +myEE.on('foo', () => console.log('a')) +myEE.prependListener('foo', () => console.log('b')) +myEE.emit('foo') +// Prints: +// b +// a +``` + +
+eventName
– The name of the event.string | symbol
listener
(args) any []#
args
listener(args) =>
on(eventName, listener) =>
once
(eventName, listener) – Adds a one-timelistener
function for the event named eventName
. The
+next time eventName
is triggered, this listener is removed and then invoked.
+ +```js +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. + +```js +const myEE = new EventEmitter() +myEE.once('foo', () => console.log('a')) +myEE.prependOnceListener('foo', () => console.log('b')) +myEE.emit('foo') +// Prints: +// b +// a +``` + +
+eventName
– The name of the event.string | symbol
listener
(args) any []#
args
listener(args) =>
once(eventName, listener) =>
prependListener
(eventName, listener) – 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.
+ +```js +server.prependListener('connection', stream => { + console.log('someone connected!') +}) +``` + +Returns a reference to the `EventEmitter`, so that calls can be chained. + +
+eventName
– The name of the event.string | symbol
listener
(args) any []#
args
listener(args) =>
prependListener(eventName, listener) =>
prependOnceListener
(eventName, listener) – Adds a one-timelistener
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.
+ +```js +server.prependOnceListener('connection', stream => { + console.log('Ah, we have our first user!') +}) +``` + +Returns a reference to the `EventEmitter`, so that calls can be chained. + +
+eventName
– The name of the event.string | symbol
listener
(args) any []#
args
listener(args) =>
prependOnceListener(eventName, listener) =>
rawListeners
(eventName) – Returns a copy of the array of listeners for the event named eventName
,
+including any wrappers (such as those created by .once()
).
+ +```js +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') +``` + +
+eventName
string | symbol
rawListeners(eventName) =>
removeAllListeners
(event) – 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. + +
+event
string | symbol
removeAllListeners(event) =>
removeListener
(eventName, listener) – Removes the specified listener
from the listener array for the event namedeventName
.
+ +```js +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. + +```js +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 indices 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: + +```js +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. + +
+eventName
string | symbol
listener
(args) any []#
args
listener(args) =>
removeListener(eventName, listener) =>
setMaxListeners
(n) – By default EventEmitter
s 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 toInfinity
(or 0
) to indicate an unlimited number of listeners.
+ +Returns a reference to the `EventEmitter`, so that calls can be chained. + +
+n
number
setMaxListeners(n) =>
EventEmitterOptions
boolean#
src/.fastpm/-/@types/node@17.0.45/events.d.ts#L42 captureRejections
– Enables automatic capturing of promise rejection.
EventListenerOptions
ExistingDecodedSourceMap
ExistingRawSourceMap
ExperimentalOptions
boolean boolean#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L698 hmrPartialAccept
– Enables support of HMR partial accept via import.meta.hot.acceptExports
.#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L685 importGlobRestoreExtension
– Append fake &lang.(ext)
when queries are specified, to preserve the file extension for following plugins to process.#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L691 renderBuiltUrl
– Allow finegrain control over assets and public files paths
FSWatcher
addListener(event, listener) =>
event
"change"
listener
(eventType, filename) string#
eventType
listener(eventType, filename) =>
addListener(event, listener) =>
event
"error"
listener
(error) Error#
error
listener(error) =>
addListener(event, listener) =>
event
"close"
listener
()
listener() =>
addListener(event, listener) =>
close
() – Stop watching for changes on the given fs.FSWatcher
. Once stopped, the fs.FSWatcher
object is no longer usable.
close() =>
emit
(eventName, args) – Synchronously calls each of the listeners registered for the event namedeventName
, in the order they were registered, passing the supplied arguments
+to each.
+ +Returns `true` if the event had listeners, `false` otherwise. + +```js +const EventEmitter = require('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 +``` + +
+eventName
string | symbol
args
any []
emit(eventName, args) =>
eventNames
() – Returns an array listing the events for which the emitter has registered
+listeners. The values in the array are strings or Symbol
s.
+ +```js +const EventEmitter = require('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) ] +``` + +
+eventNames() =>
getMaxListeners
() – Returns the current max listener value for the EventEmitter
which is either
+set by emitter.setMaxListeners(n)
or defaults to {@link defaultMaxListeners}.
getMaxListeners() =>
listenerCount
(eventName) – Returns the number of listeners listening to the event named eventName
. string | symbol#
eventName
– The name of the event being listened for
+
listenerCount(eventName) =>
listeners
(eventName) – Returns a copy of the array of listeners for the event named eventName
.
+ +```js +server.on('connection', stream => { + console.log('someone connected!') +}) +console.log(util.inspect(server.listeners('connection'))) +// Prints: [ [Function] ] +``` + +
+eventName
string | symbol
listeners(eventName) =>
off
(eventName, listener) – Alias for emitter.removeListener()
. string | symbol#
eventName
off(eventName, listener) =>
on
(event, listener) – 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.
+ +```js +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. + +```js +const myEE = new EventEmitter() +myEE.on('foo', () => console.log('a')) +myEE.prependListener('foo', () => console.log('b')) +myEE.emit('foo') +// Prints: +// b +// a +``` + +
+event
string
listener
(args) any []#
args
listener(args) =>
on(event, listener) =>
event
"change"
listener
(eventType, filename) string#
eventType
listener(eventType, filename) =>
on(event, listener) =>
event
"error"
listener
(error) Error#
error
listener(error) =>
on(event, listener) =>
event
"close"
listener
()
listener() =>
on(event, listener) =>
once
(event, listener) – Adds a one-timelistener
function for the event named eventName
. The
+next time eventName
is triggered, this listener is removed and then invoked.
+ +```js +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. + +```js +const myEE = new EventEmitter() +myEE.once('foo', () => console.log('a')) +myEE.prependOnceListener('foo', () => console.log('b')) +myEE.emit('foo') +// Prints: +// b +// a +``` + +
+event
string
listener
(args) any []#
args
listener(args) =>
once(event, listener) =>
event
"change"
listener
(eventType, filename) string#
eventType
listener(eventType, filename) =>
once(event, listener) =>
event
"error"
listener
(error) Error#
error
listener(error) =>
once(event, listener) =>
event
"close"
listener
()
listener() =>
once(event, listener) =>
prependListener
(event, listener) – 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.
+ +```js +server.prependListener('connection', stream => { + console.log('someone connected!') +}) +``` + +Returns a reference to the `EventEmitter`, so that calls can be chained. + +
+event
string
listener
(args) any []#
args
listener(args) =>
prependListener(event, listener) =>
event
"change"
listener
(eventType, filename) string#
eventType
listener(eventType, filename) =>
prependListener(event, listener) =>
event
"error"
listener
(error) Error#
error
listener(error) =>
prependListener(event, listener) =>
event
"close"
listener
()
listener() =>
prependListener(event, listener) =>
prependOnceListener
(event, listener) – Adds a one-timelistener
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.
+ +```js +server.prependOnceListener('connection', stream => { + console.log('Ah, we have our first user!') +}) +``` + +Returns a reference to the `EventEmitter`, so that calls can be chained. + +
+event
string
listener
(args) any []#
args
listener(args) =>
prependOnceListener(event, listener) =>
event
"change"
listener
(eventType, filename) string#
eventType
listener(eventType, filename) =>
prependOnceListener(event, listener) =>
event
"error"
listener
(error) Error#
error
listener(error) =>
prependOnceListener(event, listener) =>
event
"close"
listener
()
listener() =>
prependOnceListener(event, listener) =>
rawListeners
(eventName) – Returns a copy of the array of listeners for the event named eventName
,
+including any wrappers (such as those created by .once()
).
+ +```js +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') +``` + +
+eventName
string | symbol
rawListeners(eventName) =>
removeAllListeners
(event) – 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. + +
+event
string | symbol
removeAllListeners(event) =>
removeListener
(eventName, listener) – Removes the specified listener
from the listener array for the event namedeventName
.
+ +```js +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. + +```js +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 indices 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: + +```js +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. + +
+eventName
string | symbol
listener
(args) any []#
args
listener(args) =>
removeListener(eventName, listener) =>
setMaxListeners
(n) – By default EventEmitter
s 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 toInfinity
(or 0
) to indicate an unlimited number of listeners.
+ +Returns a reference to the `EventEmitter`, so that calls can be chained. + +
+n
number
setMaxListeners(n) =>
FilePosition
number number number number#
src/.fastpm/-/postcss@8.4.14/lib/input.d.ts#L23 column
– Column of inclusive start position in source file.#
src/.fastpm/-/postcss@8.4.14/lib/input.d.ts#L33 endColumn
– Column of exclusive end position in source file.#
src/.fastpm/-/postcss@8.4.14/lib/input.d.ts#L28 endLine
– Line of exclusive end position in source file.#
src/.fastpm/-/postcss@8.4.14/lib/input.d.ts#L18 line
– Line of inclusive start position in source file.
FileSystemServeOptions
string []
+
+Accepts absolute path or a path relative to project root.
+Will try to search up for workspace root by default.
+
+ string []
+
+This will have higher priority than `allow`.
+Glob patterns are supported.
+
+ boolean
+
+Set to `false` to disable the warning
+
+#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L724 allow
– Restrict accessing files outside the allowed directories.#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L733 deny
– Restrict accessing files that matches the patterns.#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L717 strict
– Strictly restrict file accessing outside of allowing paths.
FindPosition
FormatMessagesOptions
FormatOptions
ecma
ie8
boolean
indent_level
number
indent_start
number
inline_script
boolean
keep_quoted_props
boolean
max_line_len
number | false
preamble
string
preserve_annotations
boolean
quote_keys
boolean
quote_style
safari10
boolean
semicolons
boolean
shebang
boolean
shorthand
boolean
source_map
webkit
boolean
width
number
wrap_func_args
boolean
wrap_iife
boolean
FullReloadPayload
GeneratedCodeOptions
GetManualChunkApi
getModuleIds() => #
src/.fastpm/-/rollup@2.77.0/dist/rollup.d.ts#L522 getModuleIds
()
IterableIterator<string>
HmrContext
HmrOptions
HtmlTagDescriptor
Record<string, undefined | string | boolean>#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L851 attrs
#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L856 injectTo
– default: 'head-prepend'"head"
| "body"
| "head-prepend"
| "body-prepend"
IncomingHttpHeaders
IndexHtmlTransformContext
InformationEvent
InitializeOptions
Module
+
+You can use this as an alternative to "wasmURL" for environments where it's
+not possible to download the WebAssembly module.
+
+ string boolean#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L592 wasmModule
– The result of calling "new WebAssembly.Module(buffer)" where "buffer"
+is a typed array or ArrayBuffer containing the binary code of the
+"esbuild.wasm" file.#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L582 wasmURL
– The URL of the "esbuild.wasm" file. This must be provided when running
+esbuild in the browser.#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L599 worker
– By default esbuild runs the WebAssembly-based browser API in a web worker
+to avoid blocking the UI thread. This can be disabled by setting "worker"
+to false.
InlineConfig
string | RegExp | string | RegExp [] string string Record<string, any> string string | string []
+
+Features under this field could change in the future and might NOT follow semver.
+Please be careful and always pin Vite's version when using them.
+
+
+
+Features under this field only follow semver for patches, they could be removed in a
+future minor version. Please always pin Vite's version to a minor when using them.
+
+ string PluginOption [] string |
+
+Set to `false` or an empty string to disable copied static assets to build dist dir.
+
+ ResolveOptions & { #
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L2405 appType
– Whether your application is a Single Page Application (SPA),
+a Multi-Page Application (MPA), or Custom Application (SSR
+and frameworks with custom HTML handling)#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L2321 assetsInclude
– Specify additional picomatch patterns to be treated as static assets.#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L2265 base
– Base public path when served in development or production.#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L2284 cacheDir
– Directory to save cache files. Files in this directory are pre-bundled
+deps or some other cache files that generated by vite, which can improve
+the performance. You can use --force
flag or manually delete the directory
+to regenerate the cache files. The value can be either an absolute file
+system path or a path relative to <root>.
+Default to .vite
when no package.json
is detected.#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L2308 css
– CSS related options (preprocessors and CSS modules)#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L2294 define
– Define global variable replacements.
+Entries will be defined on window
during dev and replaced during build.#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L2375 envDir
– Environment files directory. Can be an absolute path, or a path relative from
+the location of the config file itself.#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L2380 envPrefix
– Env variables starts with envPrefix
will be exposed to your client source code via import.meta.env.#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L2317 esbuild
– Transform options to pass to esbuild.
+Or set to false
to disable esbuild.false
| ESBuildOptions#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L2349 experimental
– Experimental features
#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L2356 legacy
– Legacy options
#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L2361 logLevel
– Log level.
+Default: 'info'#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L2289 mode
– Explicitly set a mode to run in. This will override the default mode for
+each command, and can be overridden by the command line --mode option.#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L2337 optimizeDeps
– Dep optimization options#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L2298 plugins
– Array of vite plugins to use.#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L2333 preview
– Preview specific options, e.g. host, port, https...#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L2274 publicDir
– Directory to serve as plain static assets. Files in this directory are
+served and copied to build dist dir as-is without transform. The value
+can be either an absolute file system path or a path relative to <root>.false
#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L2302 resolve
– Configure resolver
root
– Project root directory. Can be an absolute path, or a path relative from
+the location of the config file itself.string
server
– Server specific options, e.g. host, port, https...ssr
– SSR specific optionsworker
– Worker bundle options{
PluginOption [] Omit<RollupOptions, #
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L2389 format
– Output format for worker bundle"es"
| "iife"
#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L2393 plugins
– Vite plugins that apply to worker bundle#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L2397 rollupOptions
– Rollup options to build worker bundle"plugins"
| "input"
| "onwarn"
| "preserveEntrySignatures"
>
InputOptions
() =>
cache
false
| RollupCache
context
string
experimentalCacheExpiry
number
external
inlineDynamicImports
boolean
input
makeAbsoluteExternalsRelative
boolean | "ifRelativeSource"
manualChunks
maxParallelFileOps
number
maxParallelFileReads
number
moduleContext
onwarn
perf
boolean
plugins
undefined | null
| false
| Plugin []
preserveEntrySignatures
preserveModules
boolean
preserveSymlinks
boolean
shimMissingExports
boolean
strictDeprecations
boolean
treeshake
boolean | TreeshakingPreset | TreeshakingOptions
watch
false
| WatcherOptions
InternalResolveOptions
boolean boolean getDepsOptimizer(ssr) => #
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L1207 asSrc
– src code mode also attempts the following:
+- resolving /xxx as URLs
+- resolving bare imports from optimized deps#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L1218 getDepsOptimizer
(ssr)
#
ssr
undefined | DepsOptimizer
shouldExternalize
(id) string#
id
shouldExternalize(id) =>
IpcSocketConnectOpts
#
src/.fastpm/-/@types/node@17.0.45/net.d.ts#L47 onread
– If specified, incoming data is stored in a single buffer and passed to the supplied callback when data arrives on the socket.
+Note: this will cause the streaming functionality to not provide any data, however events like 'error', 'end', and 'close' will
+still be emitted as normal and methods like pause() and resume() will also behave as expected.
JSONHydrator
object []#
data
JSONHydrator(data) =>
data
object
JSONHydrator(data) =>
JsonOptions
boolean boolean#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L1229 namedExports
– Generate a named export for every property of the JSON object#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L1235 stringify
– Generate performant output as JSON.parse("stringified").
+Enabling this will disable namedExports.
JsonWebKey
JwkKeyExportOptions
KeyExportOptions
KeyObject
LegacyOptions
boolean#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L1252 buildSsrCjsExternalHeuristics
– Revert vite build --ssr to the v2.9 strategy. Use CJS SSR build and v2.9 externalization heuristics
LibraryOptions
#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L1277 fileName
– The name of the package file output. The default file name is the name option
+of the project package.json. It can also be defined as a function taking the
+format as an argument.
formats
– Output bundle formatsname
– The name of the exposed global variable. Required when the formats
option includes
+umd
or iife
string
LineRange
ListenOptions
AbortSignal#
src/.fastpm/-/@types/node@17.0.45/events.d.ts#L317 signal
– When provided the corresponding AbortController
can be used to cancel an asynchronous action.
Location
LogErrorOptions
LogOptions
Logger
error
(msg, options) error(msg, options) =>
hasErrorLogged
(error) Error | RollupError#
error
hasErrorLogged(error) =>
info
(msg, options) info(msg, options) =>
warn
(msg, options) warn(msg, options) =>
warnOnce
(msg, options) warnOnce(msg, options) =>
LookupOneOptions
LookupOptions
MangleOptions
ManglePropertiesOptions
MappedPosition
Mapping
MappingItem
Message
Message
any#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L167 detail
– Optional user-specified data that is passed through unmodified. You can
+use this to stash the original error, for example.
MessageEvent
Metafile
MinifyOptions
MinimalPluginContext
ModuleInfo
readonly ResolvedId []#
src/.fastpm/-/rollup@2.77.0/dist/rollup.d.ts#L163 dynamicallyImportedIdResolutions
ModuleJSON
#
src/.fastpm/-/rollup@2.77.0/dist/rollup.d.ts#L110 originalSourcemap
null
| ExistingDecodedSourceMap
ModuleOptions
NodeErrorOptions
number number string string#
src/.fastpm/-/postcss@8.4.14/lib/node.d.ts#L91 endIndex
– An ending index inside a node's string that should be highlighted as
+source of error.#
src/.fastpm/-/postcss@8.4.14/lib/node.d.ts#L86 index
– An index inside a node's string that should be highlighted as source
+of error.#
src/.fastpm/-/postcss@8.4.14/lib/node.d.ts#L76 plugin
– Plugin name that created this error. PostCSS will set it automatically.#
src/.fastpm/-/postcss@8.4.14/lib/node.d.ts#L81 word
– A word inside a node's string, that should be highlighted as source
+of error.
NodeEventTarget
once(eventName, listener) =>
NodeProps
NormalizedGeneratedCodeOptions
NormalizedInputOptions
cache
undefined | false
| RollupCache
context
string
experimentalCacheExpiry
number
external
inlineDynamicImports
undefined | boolean
input
string [] | {}
makeAbsoluteExternalsRelative
boolean | "ifRelativeSource"
manualChunks
undefined | ManualChunksOption
maxParallelFileOps
number
maxParallelFileReads
number
onwarn
perf
boolean
plugins
Plugin []
preserveEntrySignatures
preserveModules
undefined | boolean
preserveSymlinks
boolean
shimMissingExports
boolean
strictDeprecations
boolean
treeshake
false
| NormalizedTreeshakingOptions
moduleContext
(id) string#
id
moduleContext(id) =>
NormalizedOutputOptions
chunkFileNames
compact
boolean
dir
undefined | string
dynamicImportFunction
undefined | string
entryFileNames
esModule
boolean
exports
"none"
| "default"
| "auto"
| "named"
extend
boolean
externalLiveBindings
boolean
file
undefined | string
format
freeze
boolean
generatedCode
globals
hoistTransitiveImports
boolean
indent
string | true
inlineDynamicImports
boolean
interop
manualChunks
minifyInternalExports
boolean
name
undefined | string
namespaceToStringTag
boolean
noConflict
boolean
paths
plugins
OutputPlugin []
preferConst
boolean
preserveModules
boolean
preserveModulesRoot
undefined | string
sourcemap
boolean | "inline"
| "hidden"
sourcemapBaseUrl
undefined | string
sourcemapExcludeSources
boolean
sourcemapFile
undefined | string
sourcemapPathTransform
undefined | SourcemapPathTransformOption
strict
boolean
systemNullSetters
boolean
validate
boolean
intro
()
intro() =>
outro
()
outro() =>
sanitizeFileName
(fileName) string#
fileName
sanitizeFileName(fileName) =>
NormalizedTreeshakingOptions
Note
OldPlugin
OnLoadArgs
OnLoadOptions
OnLoadResult
OnReadOpts
callback
(bytesWritten, buf) – This function is called for every chunk of incoming data.
+Two arguments are passed to it: the number of bytes written to buffer and a reference to buffer.
+Return false from this function to implicitly pause() the socket.OnResolveArgs
OnResolveOptions
OnResolveResult
OnStartResult
OptimizedDepInfo
Promise<ExportsData> Promise<void>#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L1409 exportsData
– ExportData cache, discovered deps will parse the src entry to get exports
+data used both to define if interop is needed and when pre-bundling#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L1404 processing
– During optimization, ids can still be resolved to their final location
+but the bundles may not yet be saved to disk
OutgoingHttpHeaders
OutputAsset
OutputBundle
OutputChunk
OutputFile
OutputOptions
chunkFileNames
compact
boolean
dir
string
dynamicImportFunction
string
entryFileNames
esModule
boolean
exports
"none"
| "default"
| "auto"
| "named"
extend
boolean
externalLiveBindings
boolean
file
string
format
freeze
boolean
generatedCode
globals
hoistTransitiveImports
boolean
indent
string | boolean
inlineDynamicImports
boolean
interop
intro
string | () => # ()
string | Promise<string>
manualChunks
minifyInternalExports
boolean
name
string
namespaceToStringTag
boolean
noConflict
boolean
outro
string | () => # ()
string | Promise<string>
paths
plugins
undefined | null
| false
| OutputPlugin []
preferConst
boolean
preserveModules
boolean
preserveModulesRoot
string
sanitizeFileName
boolean |
sourcemap
boolean | "inline"
| "hidden"
sourcemapBaseUrl
string
sourcemapExcludeSources
boolean
sourcemapFile
string
sourcemapPathTransform
strict
boolean
systemNullSetters
boolean
validate
boolean
OutputPlugin
augmentChunkHash(this, chunk) => #
src/.fastpm/-/rollup@2.77.0/dist/rollup.d.ts#L393 augmentChunkHash
(this, chunk)
string | void
generateBundle
(this, options, bundle, isWrite) outputOptions
(this, options) outputOptions(this, options) =>
null
| void | OutputOptionsrenderDynamicImport
(this, { customResolution, format, moduleId, targetModuleId }) renderDynamicImport(this, { customResolution, format, moduleId, targetModuleId }) =>
null
| void | {}
renderError
(this, err) renderError(this, err) =>
renderStart
(this, outputOptions, inputOptions) writeBundle
(this, options, bundle) writeBundle(this, options, bundle) =>
OutputPluginHooks
augmentChunkHash(this, chunk) => #
src/.fastpm/-/rollup@2.77.0/dist/rollup.d.ts#L393 augmentChunkHash
(this, chunk)
string | void
generateBundle
(this, options, bundle, isWrite) outputOptions
(this, options) outputOptions(this, options) =>
null
| void | OutputOptionsrenderDynamicImport
(this, { customResolution, format, moduleId, targetModuleId }) renderDynamicImport(this, { customResolution, format, moduleId, targetModuleId }) =>
null
| void | {}
renderError
(this, err) renderError(this, err) =>
renderStart
(this, outputOptions, inputOptions) writeBundle
(this, options, bundle) writeBundle(this, options, bundle) =>
OutputPluginValueHooks
PackageData
{ string | Record<string, string | string | Record<string, any> | string []#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L1428 data
#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L1435 browser
false
>#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L1436 exports
dir
string
nodeResolvedImports
Record<string, undefined | string>
webResolvedImports
Record<string, undefined | string>
getResolvedCache
(key, targetWeb) hasSideEffects
(id) string#
id
hasSideEffects(id) =>
"no-treeshake"
setResolvedCache
(key, entry, targetWeb) ParseOptions
ParsedUrlQuery
Parser
opts
Pick<ProcessOptions, "map"
| "from"
>
Parser(css, opts) =>
PartialMessage
PartialNote
PartialResolvedId
#
src/.fastpm/-/rollup@2.77.0/dist/rollup.d.ts#L94 moduleSideEffects
null
| boolean | "no-treeshake"
PeerCertificate
Plugin
augmentChunkHash(this, chunk) => #
src/.fastpm/-/rollup@2.77.0/dist/rollup.d.ts#L387 shouldTransformCachedModule
#
src/.fastpm/-/rollup@2.77.0/dist/rollup.d.ts#L393 augmentChunkHash
(this, chunk)
string | void
buildEnd
(this, err) buildEnd(this, err) =>
buildStart
(this, options) buildStart(this, options) =>
closeBundle
(this) #
this
closeBundle(this) =>
closeWatcher
(this) #
this
closeWatcher(this) =>
generateBundle
(this, options, bundle, isWrite) options
(this, options) options(this, options) =>
null
| void | InputOptions | Promise<null
| void | InputOptions>outputOptions
(this, options) outputOptions(this, options) =>
null
| void | OutputOptionsrenderDynamicImport
(this, { customResolution, format, moduleId, targetModuleId }) renderDynamicImport(this, { customResolution, format, moduleId, targetModuleId }) =>
null
| void | {}
renderError
(this, err) renderError(this, err) =>
renderStart
(this, outputOptions, inputOptions) writeBundle
(this, options, bundle) writeBundle(this, options, bundle) =>
Plugin
AtRuleProcessor | {}
+
+Will be called again on node or children changes.
+
+ AtRuleProcessor | {}
+
+Will be called again on node or children changes.
+
+
+
+Will be called again on node or children changes.
+
+
+
+Will be called again on node or children changes.
+
+ DeclarationProcessor | {}
+
+Will be called again on node or children changes.
+
+ DeclarationProcessor | {}
+
+Will be called again on node or children changes.
+
+
+
+Will be called again on children changes.
+
+
+
+Will be called again on children changes.
+
+
+
+This listener will not be called again.
+
+
+
+Will be called again on children changes.
+
+
+
+Will be called again on children changes.
+
+
+
+Will be called again on node or children changes.
+
+
+
+Will be called again on node or children changes.
+
+#
src/.fastpm/-/postcss@8.4.14/lib/postcss.d.ts#L159 AtRule
– Will be called on allAtRule
nodes.#
src/.fastpm/-/postcss@8.4.14/lib/postcss.d.ts#L166 AtRuleExit
– Will be called on all AtRule
nodes, when all children will be processed.#
src/.fastpm/-/postcss@8.4.14/lib/postcss.d.ts#L173 Comment
– Will be called on all Comment
nodes.
#
src/.fastpm/-/postcss@8.4.14/lib/postcss.d.ts#L181 CommentExit
– Will be called on all Comment
nodes after listeners
+for Comment
event.
#
src/.fastpm/-/postcss@8.4.14/lib/postcss.d.ts#L129 Declaration
– Will be called on all Declaration
nodes after listeners
+for Declaration
event.#
src/.fastpm/-/postcss@8.4.14/lib/postcss.d.ts#L136 DeclarationExit
– Will be called on all Declaration
nodes.#
src/.fastpm/-/postcss@8.4.14/lib/postcss.d.ts#L90 Document
– Will be called on Document
node.
#
src/.fastpm/-/postcss@8.4.14/lib/postcss.d.ts#L97 DocumentExit
– Will be called on Document
node, when all children will be processed.
#
src/.fastpm/-/postcss@8.4.14/lib/postcss.d.ts#L188 Exit
– Will be called when all other listeners processed the document.
#
src/.fastpm/-/postcss@8.4.14/lib/postcss.d.ts#L102 Once
– Will be called on Root
node once.#
src/.fastpm/-/postcss@8.4.14/lib/postcss.d.ts#L107 OnceExit
– Will be called on Root
node once, when all children will be processed.#
src/.fastpm/-/postcss@8.4.14/lib/postcss.d.ts#L114 Root
– Will be called on Root
node.
#
src/.fastpm/-/postcss@8.4.14/lib/postcss.d.ts#L121 RootExit
– Will be called on Root
node, when all children will be processed.
#
src/.fastpm/-/postcss@8.4.14/lib/postcss.d.ts#L145 Rule
– Will be called on all Rule
nodes.
#
src/.fastpm/-/postcss@8.4.14/lib/postcss.d.ts#L152 RuleExit
– Will be called on all Rule
nodes, when all children will be processed.
Plugin
setup(build) => #
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L282 setup
(build)
#
build
void | Promise<void>
PluginBuild
{
+
+- Works in node: yes
+- Works in browser: yes
+
+Documentation: https://esbuild.github.io/api/#analyze
+
+ (metafile, options) => #
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L299 esbuild
#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L307 analyzeMetafile
# (metafile, options) – Pretty-prints an analysis of the metafile JSON to a string. This is just for
+convenience to be able to match esbuild's pretty-printing exactly. If you want
+to customize it, you can just inspect the data in the metafile yourself.
#
options
Promise<string>
analyzeMetafileSync
build
{
+ +- Works in node: yes +- Works in browser: yes + +Documentation: https://esbuild.github.io/api/#build-api + +
+options
BuildOptions & {
}
(options) =>
}>
options
BuildOptions & {
}
(options) =>
}>
options
BuildOptions & {
}
(options) =>
options
BuildOptions & {
}
(options) =>
}>
options
(options) =>
buildSync
{
+ +- Works in node: yes +- Works in browser: no + +Documentation: https://esbuild.github.io/api/#build-api + +
+options
BuildOptions & {
}
(options) =>
}
options
(options) =>
formatMessages
# (messages, options) – Converts log messages to formatted message strings suitable for printing in
+the terminal. This allows you to reuse the built-in behavior of esbuild's
+log message formatter. This is a batch-oriented API for efficiency.
formatMessagesSync
initialize
+
+- Works in node: yes
+- Works in browser: yes ("options" is required)
+
+Documentation: https://esbuild.github.io/api/#running-in-the-browser
+
+ (options) => # (options) – This configures the browser-based version of esbuild. It is necessary to
+call this first and wait for the returned promise to be resolved before
+making other API calls when using esbuild in the browser.
#
options
Promise<void>
serve
+
+- Works in node: yes
+- Works in browser: no
+
+Documentation: https://esbuild.github.io/api/#serve
+
+ (serveOptions, buildOptions) => # (serveOptions, buildOptions) – This function is similar to "build" but it serves the resulting files over
+HTTP on a localhost address with the specified port.
#
serveOptions
#
buildOptions
Promise<ServeResult>
transform
+
+- Works in node: yes
+- Works in browser: yes
+
+Documentation: https://esbuild.github.io/api/#transform-api
+
+ string | Uint8Array (input, options) => # (input, options) – This function transforms a single JavaScript file. It can be used to minify
+JavaScript, convert TypeScript/JSX to JavaScript, or convert newer JavaScript
+to older JavaScript. It returns a promise that is either resolved with a
+"TransformResult" object or rejected with a "TransformFailure" object.
#
input
#
options
Promise<TransformResult>
transformSync
version
string
initialOptions
onEnd(callback) =>
onLoad
(options, callback) callback(args) => #
options
#
callback
(args)
#
args
undefined |
null
| OnLoadResult | Promise<undefined | null
| OnLoadResult>
onLoad(options, callback) =>
onResolve
(options, callback) callback(args) => #
options
#
callback
(args)
#
args
undefined |
null
| OnResolveResult | Promise<undefined | null
| OnResolveResult>
onResolve(options, callback) =>
onStart
(callback) callback() => #
callback
()
null
| void | OnStartResult | Promise<null
| void | OnStartResult>
onStart(callback) =>
resolve
(path, options) resolve(path, options) =>
PluginCache
get
(id) string#
id
get<T>(id) =>
has
(id) string#
id
has(id) =>
PluginContainer
close
()
close() =>
getModuleInfo
(id) string#
id
getModuleInfo(id) =>
null
| ModuleInfoload
(id, { ssr }) load(id, { ssr }) =>
resolveId
(id, importer, { custom, isEntry, skip, ssr }) resolveId(id, importer, { custom, isEntry, skip, ssr }) =>
null
| PartialResolvedId>transform
(code, id, { inMap, ssr }) transform(code, id, { inMap, ssr }) =>
null
| SourceDescription>PluginContext
string addWatchFile(id) => #
src/.fastpm/-/rollup@2.77.0/dist/rollup.d.ts#L186 addWatchFile
(id)
#
id
void
error
(err, pos) string | RollupError number | { #
err
#
pos
error(err, pos) =>
getAssetFileName
(assetReferenceId) string#
assetReferenceId
getAssetFileName(assetReferenceId) =>
getChunkFileName
(chunkReferenceId) string#
chunkReferenceId
getChunkFileName(chunkReferenceId) =>
getFileName
(fileReferenceId) string#
fileReferenceId
getFileName(fileReferenceId) =>
getModuleIds
()
getModuleIds() =>
getWatchFiles
()
getWatchFiles() =>
load
(options) { #
options
load(options) =>
parse
(input, options) resolve
(source, importer, { custom, isEntry, skipSelf }) resolve(source, importer, { custom, isEntry, skipSelf }) =>
null
| ResolvedId>resolveId
(source, importer) setAssetSource
(assetReferenceId, source) warn
(warning, pos) string | RollupWarning number | { #
warning
#
pos
warn(warning, pos) =>
PluginContextMeta
PluginCreator
#
opts
PluginCreator(opts) =>
PluginHooks
augmentChunkHash(this, chunk) => #
src/.fastpm/-/rollup@2.77.0/dist/rollup.d.ts#L387 shouldTransformCachedModule
#
src/.fastpm/-/rollup@2.77.0/dist/rollup.d.ts#L393 augmentChunkHash
(this, chunk)
string | void
buildEnd
(this, err) buildEnd(this, err) =>
buildStart
(this, options) buildStart(this, options) =>
closeBundle
(this) #
this
closeBundle(this) =>
closeWatcher
(this) #
this
closeWatcher(this) =>
generateBundle
(this, options, bundle, isWrite) options
(this, options) options(this, options) =>
null
| void | InputOptions | Promise<null
| void | InputOptions>outputOptions
(this, options) outputOptions(this, options) =>
null
| void | OutputOptionsrenderDynamicImport
(this, { customResolution, format, moduleId, targetModuleId }) renderDynamicImport(this, { customResolution, format, moduleId, targetModuleId }) =>
null
| void | {}
renderError
(this, err) renderError(this, err) =>
renderStart
(this, outputOptions, inputOptions) writeBundle
(this, options, bundle) writeBundle(this, options, bundle) =>
Plugin_2
– Vite plugins extends the Rollup plugin interface with a few extra
+vite-specific options. A valid vite plugin is also a valid Rollup plugin.
+On the contrary, a Rollup plugin may or may NOT be a valid vite universal
+plugin, since some Rollup features do not make sense in an unbundled
+dev server context. That said, as long as a rollup plugin doesn't have strong
+coupling between its bundle phase and output phase hooks then it should
+just work (that means, most of them).+ +By default, the plugins are run during both serve and build. When a plugin +is applied during serve, it will only run **non output plugin hooks** (see +rollup type definition of {@link rollup#PluginHooks}). You can think of the +dev server as only running `const bundle = rollup.rollup()` but never calling +`bundle.generate()`. + +A plugin that expects to have different behavior depending on serve/build can +export a factory function that receives the command being run via options. + +If a plugin should be applied only for server or build, a function format +config file can be used to conditional determine the plugins to use. + +
+ #
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L1479 apply
– Apply the plugin only for serve or build, or on certain conditions."build"
| "serve"
|
cacheKey
string
configurePreviewServer
– Configure the preview server. The hook receives the connect server and
+its underlying http server.+ +The hooks are called before other middlewares are applied. A hook can +return a post hook that will be called after other middlewares are +applied. Hooks can be async functions and will be called in series. + +
+configureServer
– Configure the vite server. The hook receives the {@link ViteDevServer}
+instance. This can also be used to store a reference to the server
+for use in other hooks.+ +The hooks will be called before internal middlewares are applied. A hook +can return a post hook that will be called after internal middlewares +are applied. Hook can be async functions and will be called in series. + +
+enforce
– Enforce plugin invocation tier similar to webpack loaders."pre"
| "post"
+ +Plugin invocation order: + +- alias resolution +- `enforce: 'pre'` plugins +- vite core plugins +- normal plugins +- vite build plugins +- `enforce: 'post'` plugins +- vite build post plugins + +
+intro
moduleParsed
name
string
outro
renderChunk
resolveAssetUrl
resolveDynamicImport
resolveFileUrl
resolveImportMeta
shouldTransformCachedModule
transformIndexHtml
– Transform index.html.
+The hook receives the following arguments:+ +- html: string +- ctx?: vite.ServerContext (only present during serve) +- bundle?: rollup.OutputBundle (only present during build) + +It can either return a transformed string, or a list of html tag +descriptors that will be injected into the
or . + +By default the transform is applied **after** vite's internal html +transform. If you need to apply the transform before vite, use an object: +`{ enforce: 'pre', transform: hook }` + + +watchChange
augmentChunkHash
(this, chunk) augmentChunkHash(this, chunk) =>
buildEnd
(this, err) buildEnd(this, err) =>
buildStart
(this, options) buildStart(this, options) =>
closeBundle
(this) #
this
closeBundle(this) =>
closeWatcher
(this) #
this
closeWatcher(this) =>
config
(config, env) – Modify vite config before it's resolved. The hook can either mutate the
+passed-in config directly, or return a partial config object that will be
+deeply merged into existing config.
+ +Note: User plugins are resolved before running this hook so injecting other +plugins inside the `config` hook will have no effect. + +
+config
env
config(config, env) =>
null
| void | UserConfig | Promise<null
| void | UserConfig>configResolved
(config) – Use this hook to read and store the final resolved vite config. Readonly<Omit<UserConfig, string assetsInclude(file) => #
config
"plugins"
| "assetsInclude"
| "optimizeDeps"
| "worker"
> & {#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L1681 assetsInclude
(file)
#
file
boolean
createResolver
(options) Partial<InternalResolveOptions>#
options
createResolver(options) =>
configResolved(config) =>
generateBundle
(this, options, bundle, isWrite) handleHotUpdate
(ctx) – Perform custom handling of HMR updates.
+The handler receives a context containing changed filename, timestamp, a
+list of modules affected by the file change, and the dev server instance.
+ +- The hook can return a filtered list of modules to narrow down the update. + e.g. for a Vue SFC, we can narrow down the part to update by comparing + the descriptors. + +- The hook can also return an empty array and then perform custom updates + by sending a custom hmr payload via server.ws.send(). + +- If the hook doesn't return a value, the hmr update will be performed as + normal. + +
+ctx
handleHotUpdate(ctx) =>
load
(this, id, { ssr }) load(this, id, { ssr }) =>
options
(this, options) options(this, options) =>
null
| void | InputOptions | Promise<null
| void | InputOptions>outputOptions
(this, options) outputOptions(this, options) =>
null
| void | OutputOptionsrenderDynamicImport
(this, { customResolution, format, moduleId, targetModuleId }) renderDynamicImport(this, { customResolution, format, moduleId, targetModuleId }) =>
null
| void | {}
renderError
(this, err) renderError(this, err) =>
renderStart
(this, outputOptions, inputOptions) resolveId
(this, source, importer, { custom, isEntry, ssr }) – extend hooks with ssr flagresolveId(this, source, importer, { custom, isEntry, ssr }) =>
transform
(this, code, id, { ssr }) transform(this, code, id, { ssr }) =>
writeBundle
(this, options, bundle) writeBundle(this, options, bundle) =>
Position
number number#
src/.fastpm/-/postcss@8.4.14/lib/node.d.ts#L33 column
– Source line in file. In contrast to offset
it starts from 1.#
src/.fastpm/-/postcss@8.4.14/lib/node.d.ts#L28 offset
– Source offset in file. It starts from 0.
Position
Postcss
– Create a new Processor
instance that will apply plugins
+as CSS processors.
+ +```js +let postcss = require('postcss') + +postcss(plugins).process(css, { from, to }).then(result => { + console.log(result.css) +}) +``` + +
+plugins
– PostCSS plugins.Postcss(plugins) =>
plugins
Postcss(plugins) =>
+
+```js
+const json = root.toJSON()
+// save to file, send by network, etc
+const root2 = postcss.fromJSON(json)
+```
+
+#
src/.fastpm/-/postcss@8.4.14/lib/postcss.d.ts#L393 fromJSON
– Rehydrate a JSON AST (from Node#toJSON
) back into the AST classes.
#
src/.fastpm/-/postcss@8.4.14/lib/postcss.d.ts#L382 parse
– Parses source css and returns a new Root
or Document
node,
+which contains the source CSS nodes.#
src/.fastpm/-/postcss@8.4.14/lib/postcss.d.ts#L369 stringify
– Default function to convert a node tree into a CSS string.
comment
(defaults) – Creates a new Comment
node. #
defaults
– Properties for the new node.
comment(defaults) =>
decl
(defaults) – Creates a new Declaration
node. #
defaults
– Properties for the new node.
decl(defaults) =>
document
(defaults) – Creates a new Document
node. #
defaults
– Properties for the new node.
document(defaults) =>
root
(defaults) – Creates a new Root
node.
root(defaults) =>
PreRenderedAsset
PreRenderedChunk
PreviewOptions
boolean | CorsOptions string | boolean boolean | ServerOptions string | boolean number Record<string, string | ProxyOptions>
+
+Example `vite.config.js`:
+
+```js
+module.exports = {
+ proxy: {
+ // string shorthand
+ '/foo': 'http://localhost:4567/foo',
+ // with options
+ '/api': {
+ target: 'http://jsonplaceholder.typicode.com',
+ changeOrigin: true,
+ rewrite: path => path.replace(/^\/api/, ''),
+ },
+ },
+}
+```
+
+ boolean#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L319 cors
– Configure CORS for the dev server.
+Uses https://github.com/expressjs/cors.
+Set to true
to allow all methods from any origin, or configure separately
+using an object.#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L323 headers
– Specify server response headers.#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L280 host
– Specify which IP addresses the server should listen on.
+Set to 0.0.0.0 to listen on all addresses, including LAN and public addresses.#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L285 https
– Enable TLS + HTTP/2.
+Note: this downgrades to TLS only when the proxy option is also used.#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L289 open
– Open browser window on startup#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L271 port
– Specify server port. Note if the port is already being used, Vite will
+automatically try the next available port so this may not be the actual
+port the server ends up listening on.#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L312 proxy
– Configure custom proxy rules for the dev server. Expects an object
+of { key: options }
pairs.
+Uses http-proxy
.
+Full options here.#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L275 strictPort
– If enabled, vite will exit if specified port is already in use
ProcessOptions
string boolean | SourceMapOptions string#
src/.fastpm/-/postcss@8.4.14/lib/postcss.d.ts#L318 from
– The path of the CSS source file. You should always set from
,
+because it is used in source map generation and syntax error messages.#
src/.fastpm/-/postcss@8.4.14/lib/postcss.d.ts#L344 map
– Source map options#
src/.fastpm/-/postcss@8.4.14/lib/postcss.d.ts#L329 parser
– Function to generate AST by string.#
src/.fastpm/-/postcss@8.4.14/lib/postcss.d.ts#L334 stringifier
– Class to generate string by AST.#
src/.fastpm/-/postcss@8.4.14/lib/postcss.d.ts#L339 syntax
– Object with parse and stringify.#
src/.fastpm/-/postcss@8.4.14/lib/postcss.d.ts#L324 to
– The path where you'll put the output CSS file. You should always set to
+to generate correct source maps.
Processors
AtRuleProcessor | {}
+
+Will be called again on node or children changes.
+
+ AtRuleProcessor | {}
+
+Will be called again on node or children changes.
+
+
+
+Will be called again on node or children changes.
+
+
+
+Will be called again on node or children changes.
+
+ DeclarationProcessor | {}
+
+Will be called again on node or children changes.
+
+ DeclarationProcessor | {}
+
+Will be called again on node or children changes.
+
+
+
+Will be called again on children changes.
+
+
+
+Will be called again on children changes.
+
+
+
+This listener will not be called again.
+
+
+
+Will be called again on children changes.
+
+
+
+Will be called again on children changes.
+
+
+
+Will be called again on node or children changes.
+
+
+
+Will be called again on node or children changes.
+
+#
src/.fastpm/-/postcss@8.4.14/lib/postcss.d.ts#L159 AtRule
– Will be called on allAtRule
nodes.#
src/.fastpm/-/postcss@8.4.14/lib/postcss.d.ts#L166 AtRuleExit
– Will be called on all AtRule
nodes, when all children will be processed.#
src/.fastpm/-/postcss@8.4.14/lib/postcss.d.ts#L173 Comment
– Will be called on all Comment
nodes.
#
src/.fastpm/-/postcss@8.4.14/lib/postcss.d.ts#L181 CommentExit
– Will be called on all Comment
nodes after listeners
+for Comment
event.
#
src/.fastpm/-/postcss@8.4.14/lib/postcss.d.ts#L129 Declaration
– Will be called on all Declaration
nodes after listeners
+for Declaration
event.#
src/.fastpm/-/postcss@8.4.14/lib/postcss.d.ts#L136 DeclarationExit
– Will be called on all Declaration
nodes.#
src/.fastpm/-/postcss@8.4.14/lib/postcss.d.ts#L90 Document
– Will be called on Document
node.
#
src/.fastpm/-/postcss@8.4.14/lib/postcss.d.ts#L97 DocumentExit
– Will be called on Document
node, when all children will be processed.
#
src/.fastpm/-/postcss@8.4.14/lib/postcss.d.ts#L188 Exit
– Will be called when all other listeners processed the document.
#
src/.fastpm/-/postcss@8.4.14/lib/postcss.d.ts#L102 Once
– Will be called on Root
node once.#
src/.fastpm/-/postcss@8.4.14/lib/postcss.d.ts#L107 OnceExit
– Will be called on Root
node once, when all children will be processed.#
src/.fastpm/-/postcss@8.4.14/lib/postcss.d.ts#L114 Root
– Will be called on Root
node.
#
src/.fastpm/-/postcss@8.4.14/lib/postcss.d.ts#L121 RootExit
– Will be called on Root
node, when all children will be processed.
#
src/.fastpm/-/postcss@8.4.14/lib/postcss.d.ts#L145 Rule
– Will be called on all Rule
nodes.
#
src/.fastpm/-/postcss@8.4.14/lib/postcss.d.ts#L152 RuleExit
– Will be called on all Rule
nodes, when all children will be processed.
ProxyOptions
any string boolean boolean boolean {} string boolean string boolean boolean string number boolean any number boolean bypass(req, res, options) => #
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L1033 agent
– Object to be passed to http(s).request.#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L1055 auth
– Basic authentication i.e. 'user:password' to compute an Authorization header.#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L1059 autoRewrite
– Rewrites the location host/ port on (301 / 302 / 307 / 308) redirects based on requested host/ port.Default: false.#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L1051 changeOrigin
– Changes the origin of the host header to the target URL.#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L1073 followRedirects
– Specify whether you want to follow redirects. Default: false#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L1031 forward
– URL string to be parsed with the url module.#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L1067 headers
– object with extra headers to be added to target requests.#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L1057 hostRewrite
– Rewrites the location hostname on (301 / 302 / 307 / 308) redirects, Default: null.#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L1047 ignorePath
– Specify whether you want to ignore the proxy path of the incoming request.#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L1049 localAddress
– Local interface string to bind for outgoing connections.#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L1045 prependPath
– Specify whether you want to prepend the target's path to the proxy path.#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L1053 preserveHeaderKeyCase
– specify whether you want to keep letter case of response header key#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L1061 protocolRewrite
– Rewrites the location protocol on (301 / 302 / 307 / 308) redirects to 'http' or 'https'.Default: null.#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L1069 proxyTimeout
– Timeout (in milliseconds) when proxy receives no response from target. Default: 120000 (2 minutes)#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L1075 selfHandleResponse
– If set to true, none of the webOutgoing passes are called and it's your responsibility to appropriately return the response by listening and acting on the proxyRes event#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L1035 ssl
– Object to be passed to https.createServer().#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L1029 target
– URL string to be parsed with the url module.#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L1071 timeout
– Timeout (in milliseconds) for incoming requests#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L1043 toProxy
– Explicitly specify if we are proxying to another proxy.#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L1631 bypass
(req, res, options) – webpack-dev-server style bypass function
undefined |
null
| string | false
| void
configure
(proxy, options) – configure the proxy server (e.g. listen to events) #
options
configure(proxy, options) =>
rewrite
(path) – rewrite path string#
path
rewrite(path) =>
ProxyTargetDetailed
PrunePayload
PxfObject
string | Buffer#
src/.fastpm/-/@types/node@17.0.45/tls.d.ts#L103 buf
– PFX or PKCS12 encoded private key and certificate chain.
Range
RangePosition
– A position that is part of a range. number number#
src/.fastpm/-/postcss@8.4.14/lib/css-syntax-error.d.ts#L15 column
– The column number in the input.#
src/.fastpm/-/postcss@8.4.14/lib/css-syntax-error.d.ts#L10 line
– The line number in the input.
RawSourceMap
ReadOnlyDict
ReadWriteStream
addListener
(eventName, listener) – Alias for emitter.on(eventName, listener)
. string | symbol#
eventName
addListener(eventName, listener) =>
emit
(eventName, args) – Synchronously calls each of the listeners registered for the event namedeventName
, in the order they were registered, passing the supplied arguments
+to each.
+ +Returns `true` if the event had listeners, `false` otherwise. + +```js +const EventEmitter = require('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 +``` + +
+eventName
string | symbol
args
any []
emit(eventName, args) =>
end
(cb) cb() => #
cb
()
void
end(cb) =>
data
string | Uint8Array
cb
()
cb() =>
end(data, cb) =>
str
string
encoding
cb
()
cb() =>
end(str, encoding, cb) =>
eventNames
() – Returns an array listing the events for which the emitter has registered
+listeners. The values in the array are strings or Symbol
s.
+ +```js +const EventEmitter = require('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) ] +``` + +
+eventNames() =>
getMaxListeners
() – Returns the current max listener value for the EventEmitter
which is either
+set by emitter.setMaxListeners(n)
or defaults to {@link defaultMaxListeners}.
getMaxListeners() =>
isPaused
()
isPaused() =>
listenerCount
(eventName) – Returns the number of listeners listening to the event named eventName
. string | symbol#
eventName
– The name of the event being listened for
+
listenerCount(eventName) =>
listeners
(eventName) – Returns a copy of the array of listeners for the event named eventName
.
+ +```js +server.on('connection', stream => { + console.log('someone connected!') +}) +console.log(util.inspect(server.listeners('connection'))) +// Prints: [ [Function] ] +``` + +
+eventName
string | symbol
listeners(eventName) =>
off
(eventName, listener) – Alias for emitter.removeListener()
. string | symbol#
eventName
off(eventName, listener) =>
on
(eventName, listener) – 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.
+ +```js +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. + +```js +const myEE = new EventEmitter() +myEE.on('foo', () => console.log('a')) +myEE.prependListener('foo', () => console.log('b')) +myEE.emit('foo') +// Prints: +// b +// a +``` + +
+eventName
– The name of the event.string | symbol
listener
(args) any []#
args
listener(args) =>
on(eventName, listener) =>
once
(eventName, listener) – Adds a one-timelistener
function for the event named eventName
. The
+next time eventName
is triggered, this listener is removed and then invoked.
+ +```js +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. + +```js +const myEE = new EventEmitter() +myEE.once('foo', () => console.log('a')) +myEE.prependOnceListener('foo', () => console.log('b')) +myEE.emit('foo') +// Prints: +// b +// a +``` + +
+eventName
– The name of the event.string | symbol
listener
(args) any []#
args
listener(args) =>
once(eventName, listener) =>
pause
()
pause() =>
pipe
(destination, { end }) { #
options
pipe<T extends WritableStream<T>>(destination, { end }) =>
prependListener
(eventName, listener) – 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.
+ +```js +server.prependListener('connection', stream => { + console.log('someone connected!') +}) +``` + +Returns a reference to the `EventEmitter`, so that calls can be chained. + +
+eventName
– The name of the event.string | symbol
listener
(args) any []#
args
listener(args) =>
prependListener(eventName, listener) =>
prependOnceListener
(eventName, listener) – Adds a one-timelistener
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.
+ +```js +server.prependOnceListener('connection', stream => { + console.log('Ah, we have our first user!') +}) +``` + +Returns a reference to the `EventEmitter`, so that calls can be chained. + +
+eventName
– The name of the event.string | symbol
listener
(args) any []#
args
listener(args) =>
prependOnceListener(eventName, listener) =>
rawListeners
(eventName) – Returns a copy of the array of listeners for the event named eventName
,
+including any wrappers (such as those created by .once()
).
+ +```js +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') +``` + +
+eventName
string | symbol
rawListeners(eventName) =>
read
(size) number#
size
read(size) =>
removeAllListeners
(event) – 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. + +
+event
string | symbol
removeAllListeners(event) =>
removeListener
(eventName, listener) – Removes the specified listener
from the listener array for the event namedeventName
.
+ +```js +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. + +```js +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 indices 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: + +```js +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. + +
+eventName
string | symbol
listener
(args) any []#
args
listener(args) =>
removeListener(eventName, listener) =>
resume
()
resume() =>
setEncoding
(encoding) #
encoding
setEncoding(encoding) =>
setMaxListeners
(n) – By default EventEmitter
s 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 toInfinity
(or 0
) to indicate an unlimited number of listeners.
+ +Returns a reference to the `EventEmitter`, so that calls can be chained. + +
+n
number
setMaxListeners(n) =>
unpipe
(destination) #
destination
unpipe(destination) =>
wrap
(oldStream) #
oldStream
wrap(oldStream) =>
write(buffer, cb) =>
str
string
encoding
cb
(err) #
err
null
| Error
cb(err) =>
write(str, encoding, cb) =>
ReadableOptions
AbortSignal#
src/.fastpm/-/@types/node@17.0.45/events.d.ts#L317 signal
– When provided the corresponding AbortController
can be used to cancel an asynchronous action.
construct(this, callback) =>
destroy
(this, error, callback) #
error
null
| Error
destroy(this, error, callback) =>
ReadableStream
addListener
(eventName, listener) – Alias for emitter.on(eventName, listener)
. string | symbol#
eventName
addListener(eventName, listener) =>
emit
(eventName, args) – Synchronously calls each of the listeners registered for the event namedeventName
, in the order they were registered, passing the supplied arguments
+to each.
+ +Returns `true` if the event had listeners, `false` otherwise. + +```js +const EventEmitter = require('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 +``` + +
+eventName
string | symbol
args
any []
emit(eventName, args) =>
eventNames
() – Returns an array listing the events for which the emitter has registered
+listeners. The values in the array are strings or Symbol
s.
+ +```js +const EventEmitter = require('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) ] +``` + +
+eventNames() =>
getMaxListeners
() – Returns the current max listener value for the EventEmitter
which is either
+set by emitter.setMaxListeners(n)
or defaults to {@link defaultMaxListeners}.
getMaxListeners() =>
isPaused
()
isPaused() =>
listenerCount
(eventName) – Returns the number of listeners listening to the event named eventName
. string | symbol#
eventName
– The name of the event being listened for
+
listenerCount(eventName) =>
listeners
(eventName) – Returns a copy of the array of listeners for the event named eventName
.
+ +```js +server.on('connection', stream => { + console.log('someone connected!') +}) +console.log(util.inspect(server.listeners('connection'))) +// Prints: [ [Function] ] +``` + +
+eventName
string | symbol
listeners(eventName) =>
off
(eventName, listener) – Alias for emitter.removeListener()
. string | symbol#
eventName
off(eventName, listener) =>
on
(eventName, listener) – 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.
+ +```js +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. + +```js +const myEE = new EventEmitter() +myEE.on('foo', () => console.log('a')) +myEE.prependListener('foo', () => console.log('b')) +myEE.emit('foo') +// Prints: +// b +// a +``` + +
+eventName
– The name of the event.string | symbol
listener
(args) any []#
args
listener(args) =>
on(eventName, listener) =>
once
(eventName, listener) – Adds a one-timelistener
function for the event named eventName
. The
+next time eventName
is triggered, this listener is removed and then invoked.
+ +```js +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. + +```js +const myEE = new EventEmitter() +myEE.once('foo', () => console.log('a')) +myEE.prependOnceListener('foo', () => console.log('b')) +myEE.emit('foo') +// Prints: +// b +// a +``` + +
+eventName
– The name of the event.string | symbol
listener
(args) any []#
args
listener(args) =>
once(eventName, listener) =>
pause
()
pause() =>
pipe
(destination, { end }) { #
options
pipe<T extends WritableStream<T>>(destination, { end }) =>
prependListener
(eventName, listener) – 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.
+ +```js +server.prependListener('connection', stream => { + console.log('someone connected!') +}) +``` + +Returns a reference to the `EventEmitter`, so that calls can be chained. + +
+eventName
– The name of the event.string | symbol
listener
(args) any []#
args
listener(args) =>
prependListener(eventName, listener) =>
prependOnceListener
(eventName, listener) – Adds a one-timelistener
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.
+ +```js +server.prependOnceListener('connection', stream => { + console.log('Ah, we have our first user!') +}) +``` + +Returns a reference to the `EventEmitter`, so that calls can be chained. + +
+eventName
– The name of the event.string | symbol
listener
(args) any []#
args
listener(args) =>
prependOnceListener(eventName, listener) =>
rawListeners
(eventName) – Returns a copy of the array of listeners for the event named eventName
,
+including any wrappers (such as those created by .once()
).
+ +```js +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') +``` + +
+eventName
string | symbol
rawListeners(eventName) =>
read
(size) number#
size
read(size) =>
removeAllListeners
(event) – 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. + +
+event
string | symbol
removeAllListeners(event) =>
removeListener
(eventName, listener) – Removes the specified listener
from the listener array for the event namedeventName
.
+ +```js +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. + +```js +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 indices 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: + +```js +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. + +
+eventName
string | symbol
listener
(args) any []#
args
listener(args) =>
removeListener(eventName, listener) =>
resume
()
resume() =>
setEncoding
(encoding) #
encoding
setEncoding(encoding) =>
setMaxListeners
(n) – By default EventEmitter
s 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 toInfinity
(or 0
) to indicate an unlimited number of listeners.
+ +Returns a reference to the `EventEmitter`, so that calls can be chained. + +
+n
number
setMaxListeners(n) =>
unpipe
(destination) #
destination
unpipe(destination) =>
wrap
(oldStream) #
oldStream
wrap(oldStream) =>
RenderedChunk
RenderedModule
ResolveOptions
ResolveOptions
ResolveResult
ResolveWorkerOptions
ResolvedId
ResolvedIdMap
ResolvedPreviewOptions
boolean | CorsOptions string | boolean boolean | ServerOptions string | boolean number Record<string, string | ProxyOptions>
+
+Example `vite.config.js`:
+
+```js
+module.exports = {
+ proxy: {
+ // string shorthand
+ '/foo': 'http://localhost:4567/foo',
+ // with options
+ '/api': {
+ target: 'http://jsonplaceholder.typicode.com',
+ changeOrigin: true,
+ rewrite: path => path.replace(/^\/api/, ''),
+ },
+ },
+}
+```
+
+ boolean#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L319 cors
– Configure CORS for the dev server.
+Uses https://github.com/expressjs/cors.
+Set to true
to allow all methods from any origin, or configure separately
+using an object.#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L323 headers
– Specify server response headers.#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L280 host
– Specify which IP addresses the server should listen on.
+Set to 0.0.0.0 to listen on all addresses, including LAN and public addresses.#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L285 https
– Enable TLS + HTTP/2.
+Note: this downgrades to TLS only when the proxy option is also used.#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L289 open
– Open browser window on startup#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L271 port
– Specify server port. Note if the port is already being used, Vite will
+automatically try the next available port so this may not be the actual
+port the server ends up listening on.#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L312 proxy
– Configure custom proxy rules for the dev server. Expects an object
+of { key: options }
pairs.
+Uses http-proxy
.
+Full options here.#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L275 strictPort
– If enabled, vite will exit if specified port is already in use
ResolvedSSROptions
string | #
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L1706 format
– Define the format for the ssr build. Since Vite v3 the SSR build generates ESM by default.
+'cjs'
can be selected to generate a CJS build, but it isn't recommended. This option is
+left marked as experimental to give users more time to update to ESM. CJS builds requires
+complex externalization heuristics that aren't present in the ESM format.#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L2026 noExternal
true
| RegExp | string | RegExp []#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L1707 optimizeDeps
– Control over which dependencies are optimized during SSR and esbuild options
+During build:
+no external CJS dependencies are optimized by default
+During dev:
+explicit no external CJS dependencies are optimized by default#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L1705 target
– Define the target for the ssr build. The browser field in package.json
+is ignored for node but used if webworker is the target
+Default: 'node'
ResolvedServerOptions
string boolean | CorsOptions boolean Required<FileSystemServeOptions> boolean | HmrOptions string | boolean boolean | ServerOptions boolean string | boolean string number boolean Record<string, string | ProxyOptions>
+
+Example `vite.config.js`:
+
+```js
+module.exports = {
+ proxy: {
+ // string shorthand
+ '/foo': 'http://localhost:4567/foo',
+ // with options
+ '/api': {
+ target: 'http://jsonplaceholder.typicode.com',
+ changeOrigin: true,
+ rewrite: path => path.replace(/^\/api/, ''),
+ },
+ },
+}
+```
+
+ boolean#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L1982 base
– Prepend this folder to http requests, for use when proxying vite as a subfolder
+Should start and end with the /
character#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L319 cors
– Configure CORS for the dev server.
+Uses https://github.com/expressjs/cors.
+Set to true
to allow all methods from any origin, or configure separately
+using an object.#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L2004 force
– Force dep pre-optimization regardless of whether deps have changed.#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L1695 fs
– Options for files served via '/@fs/'.#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L323 headers
– Specify server response headers.#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L1968 hmr
– Configure HMR-specific options (port, host, path & protocol)#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L280 host
– Specify which IP addresses the server should listen on.
+Set to 0.0.0.0 to listen on all addresses, including LAN and public addresses.#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L285 https
– Enable TLS + HTTP/2.
+Note: this downgrades to TLS only when the proxy option is also used.#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L1696 middlewareMode
– Create Vite dev server to be used as a middleware in an existing server#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L289 open
– Open browser window on startup#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L1992 origin
– Origin for the generated asset URLs.#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L271 port
– Specify server port. Note if the port is already being used, Vite will
+automatically try the next available port so this may not be the actual
+port the server ends up listening on.#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L1997 preTransformRequests
– Pre-transform known direct imports#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L312 proxy
– Configure custom proxy rules for the dev server. Expects an object
+of { key: options }
pairs.
+Uses http-proxy
.
+Full options here.#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L275 strictPort
– If enabled, vite will exit if specified port is already in use#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L1973 watch
– chokidar watch options
+https://github.com/paulmillr/chokidar#api
ResolvedServerUrls
ResolverObject
(this, options) => #
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L1735 buildStart
# (this, options)
void | Promise<void>
resolveId
ResultOptions
string boolean | SourceMapOptions string string#
src/.fastpm/-/postcss@8.4.14/lib/postcss.d.ts#L318 from
– The path of the CSS source file. You should always set from
,
+because it is used in source map generation and syntax error messages.#
src/.fastpm/-/postcss@8.4.14/lib/postcss.d.ts#L344 map
– Source map options#
src/.fastpm/-/postcss@8.4.14/lib/result.d.ts#L32 node
– The CSS node that was the source of the warning.#
src/.fastpm/-/postcss@8.4.14/lib/postcss.d.ts#L329 parser
– Function to generate AST by string.#
src/.fastpm/-/postcss@8.4.14/lib/result.d.ts#L38 plugin
– Name of plugin that created this warning. Result#warn
will fill it
+automatically with Plugin#postcssPlugin
value.#
src/.fastpm/-/postcss@8.4.14/lib/postcss.d.ts#L334 stringifier
– Class to generate string by AST.#
src/.fastpm/-/postcss@8.4.14/lib/postcss.d.ts#L339 syntax
– Object with parse and stringify.#
src/.fastpm/-/postcss@8.4.14/lib/postcss.d.ts#L324 to
– The path where you'll put the output CSS file. You should always set to
+to generate correct source maps.
RollupCache
RollupCommonJSOptions
– https://github.com/rollup/plugins/blob/master/packages/commonjs/types/index.d.ts+ +This source code is licensed under the MIT license found in the +LICENSE file at +https://github.com/rollup/plugins/blob/master/LICENSE + +
+ string | readonly string []
+
+Note: In extreme cases, this feature may result in some paths being
+rendered as absolute in the final bundle. The plugin tries to avoid
+exposing paths from the local machine, but if you are `dynamicRequirePaths`
+with paths that are far away from your project's folder, that may require
+replacing strings like `"/Users/John/Desktop/foo-project/"` -\> `"/"`.
+
+ boolean | readonly string [] | #
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L1925 dynamicRequireTargets
– Some modules contain dynamic require
calls, or require modules that
+contain circular dependencies, which are not handled well by static
+imports. Including those modules as dynamicRequireTargets
will simulate a
+CommonJS (NodeJS-like) environment for them with support for dynamic and
+circular dependencies.#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L1855 esmExternals
– Controls how to render imports from external dependencies. By default,
+this plugin assumes that all external dependencies are CommonJS. This
+means they are rendered as default imports to be compatible with e.g.
+NodeJS where ES modules can only import a default export from a CommonJS
+dependency.
+ +If you set `esmExternals` to `true`, this plugins assumes that all +external dependencies are ES modules and respect the +`requireReturnsDefault` option. If that option is not set, they will be +rendered as namespace imports. + +You can also supply an array of ids to be treated as ES modules, or a +function that will be passed each external id to determine if it is an ES +module. + +
+exclude
– A picomatch pattern, or array of patterns, which specifies the files in
+the build the plugin should ignore. By default, all files with
+extensions other than those in extensions
or ".cjs"
are ignored, but you
+can exclude additional files. See also the include
option.string | RegExp | readonly string | RegExp []
extensions
– For extensionless imports, search for extensions other than .js in the
+order specified. Note that you need to make sure that non-JavaScript files
+are transpiled by another plugin first.readonly string []
ignore
– Sometimes you have to leave require statements unconverted. Pass an array
+containing the IDs or a id => boolean
function.readonly string [] |
ignoreDynamicRequires
– Some require
calls cannot be resolved statically to be translated to
+imports.
+When this option is set to false
, the generated code will either
+directly throw an error when such a call is encountered or, when
+dynamicRequireTargets
is used, when such a call cannot be resolved with a
+configured dynamic require target.
+Setting this option to true
will instead leave the require
call in the
+code or use it as a fallback for dynamicRequireTargets
.boolean
ignoreGlobal
– If true then uses of global
won't be dealt with by this pluginboolean
ignoreTryCatch
– In most cases, where require
calls are inside a try-catch
clause,
+they should be left unconverted as it requires an optional dependency
+that may or may not be installed beside the rolled up package.
+Due to the conversion of require
to a static import
- the call is hoisted
+to the top of the file, outside of the try-catch
clause.boolean | readonly string [] | "remove"
|
+ +- `true`: All `require` calls inside a `try` will be left unconverted. +- `false`: All `require` calls inside a `try` will be converted as if the `try-catch` clause is not there. +- `remove`: Remove all `require` calls from inside any `try` block. +- `string[]`: Pass an array containing the IDs to left unconverted. +- `((id: string) => boolean|'remove')`: Pass a function that control individual IDs. + +
+include
– A picomatch pattern, or array of patterns, which specifies the files in
+the build the plugin should operate on. By default, all files with
+extension ".cjs"
or those in extensions
are included, but you can narrow
+this list by only including specific files. These files will be analyzed
+and transpiled if either the analysis does not find ES module specific
+statements or transformMixedEsModules
is true
.string | RegExp | readonly string | RegExp []
requireReturnsDefault
– Controls what is returned when requiring an ES module from a CommonJS file.
+When using the esmExternals
option, this will also apply to external
+modules. By default, this plugin will render those imports as namespace
+imports i.e.boolean | "auto"
| "preferred"
| "namespace"
|
+ +```js +// input +const foo = require('foo') + +// output +import * as foo from 'foo' +``` + +However there are some situations where this may not be desired. +For these situations, you can change Rollup's behaviour either globally or +per module. To change it globally, set the `requireReturnsDefault` option +to one of the following values: + +- `false`: This is the default, requiring an ES module returns its + namespace. This is the only option that will also add a marker + `__esModule: true` to the namespace to support interop patterns in + CommonJS modules that are transpiled ES modules. +- `"namespace"`: Like `false`, requiring an ES module returns its + namespace, but the plugin does not add the `__esModule` marker and thus + creates more efficient code. For external dependencies when using + `esmExternals: true`, no additional interop code is generated. +- `"auto"`: This is complementary to how `output.exports: "auto"` works in + Rollup: If a module has a default export and no named exports, requiring + that module returns the default export. In all other cases, the namespace + is returned. For external dependencies when using `esmExternals: true`, a + corresponding interop helper is added. +- `"preferred"`: If a module has a default export, requiring that module + always returns the default export, no matter whether additional named + exports exist. This is similar to how previous versions of this plugin + worked. Again for external dependencies when using `esmExternals: true`, + an interop helper is added. +- `true`: This will always try to return the default export on require + without checking if it actually exists. This can throw at build time if + there is no default export. This is how external dependencies are handled + when `esmExternals` is not used. The advantage over the other options is + that, like `false`, this does not add an interop helper for external + dependencies, keeping the code lean. + +To change this for individual modules, you can supply a function for +`requireReturnsDefault` instead. This function will then be called once for +each required ES module or external dependency with the corresponding id +and allows you to return different values for different modules. + +
+sourceMap
– If false, skips source map generation for CommonJS modules. This will improve performance.boolean
transformMixedEsModules
– Instructs the plugin whether to enable mixed module transformations. This
+is useful in scenarios with modules that contain a mix of ES import
+statements and CommonJS require
expressions. Set to true
if require
+calls should be transformed to imports in mixed modules, or false
if the
+require
expressions should survive the transformation. The latter can be
+important if the code contains environment detection, or you are coding
+for an environment with special treatment for require
calls such as
+ElectronJS. See also the ignore
option.boolean
RollupDynamicImportVarsOptions
string | RegExp | string | RegExp [] string | RegExp | string | RegExp [] boolean#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L1938 exclude
– Files to exclude in this plugin (default none).#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L1933 include
– Files to include in this plugin (default all).#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L1943 warnOnError
– By default, the plugin quits the build process when it encounters an error. If you set this option to true, it will throw a warning instead and leave the code untouched.
RollupError
message
string
name
string
parserError
Error
plugin
string
pluginCode
string
pos
number
stack
string
url
string
watchFiles
string []
RollupLogProps
message
string
name
string
plugin
string
pluginCode
string
pos
number
url
string
RollupOptions
() =>
cache
false
| RollupCache
context
string
experimentalCacheExpiry
number
external
inlineDynamicImports
boolean
input
makeAbsoluteExternalsRelative
boolean | "ifRelativeSource"
manualChunks
maxParallelFileOps
number
maxParallelFileReads
number
moduleContext
onwarn
output
perf
boolean
plugins
undefined | null
| false
| Plugin []
preserveEntrySignatures
preserveModules
boolean
preserveSymlinks
boolean
shimMissingExports
boolean
strictDeprecations
boolean
treeshake
boolean | TreeshakingPreset | TreeshakingOptions
watch
false
| WatcherOptions
RollupWarning
message
string
missing
string
modules
string []
name
string
names
string []
plugin
string
pluginCode
string
pos
number
reexporter
string
source
string
sources
string []
url
string
RootProps
#
src/.fastpm/-/postcss@8.4.14/lib/root.d.ts#L39 raws
– Information used to generate byte-to-byte equal node string
+as it was in the origin input.
RootRaws
string string
+
+**Experimental:** some aspects of this node could change within minor
+or patch version releases.
+
+ string
+
+**Experimental:** some aspects of this node could change within minor
+or patch version releases.
+
+ boolean#
src/.fastpm/-/postcss@8.4.14/lib/root.d.ts#L10 after
– The space symbols after the last child to the end of file.#
src/.fastpm/-/postcss@8.4.14/lib/root.d.ts#L26 codeAfter
– Non-CSS code after Root
, when Root
is inside Document
.#
src/.fastpm/-/postcss@8.4.14/lib/root.d.ts#L18 codeBefore
– Non-CSS code before Root
, when Root
is inside Document
.#
src/.fastpm/-/postcss@8.4.14/lib/root.d.ts#L31 semicolon
– Is the last child has an (optional) semicolon.
RuleProps
string string []#
src/.fastpm/-/postcss@8.4.14/lib/rule.d.ts#L45 raws
– Information used to generate byte-to-byte equal node string as it was in the origin input.#
src/.fastpm/-/postcss@8.4.14/lib/rule.d.ts#L41 selector
– Selector or selectors of the rule.#
src/.fastpm/-/postcss@8.4.14/lib/rule.d.ts#L43 selectors
– Selectors of the rule represented as an array of strings.
RuleRaws
string string string string { #
src/.fastpm/-/postcss@8.4.14/lib/rule.d.ts#L13 after
– The space symbols after the last child of the node to the end of the node.#
src/.fastpm/-/postcss@8.4.14/lib/rule.d.ts#L8 before
– The space symbols before the node. It also stores *
+and _
symbols before the declaration (IE hack).#
src/.fastpm/-/postcss@8.4.14/lib/rule.d.ts#L18 between
– The symbols between the selector and {
for rules.#
src/.fastpm/-/postcss@8.4.14/lib/rule.d.ts#L28 ownSemicolon
– Contains true
if there is semicolon after rule.#
src/.fastpm/-/postcss@8.4.14/lib/rule.d.ts#L33 selector
– The rule’s selector with comments.
semicolon
– Contains true
if the last child has an (optional) semicolon.boolean
SSROptions
string | #
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L2041 format
– Define the format for the ssr build. Since Vite v3 the SSR build generates ESM by default.
+'cjs'
can be selected to generate a CJS build, but it isn't recommended. This option is
+left marked as experimental to give users more time to update to ESM. CJS builds requires
+complex externalization heuristics that aren't present in the ESM format.#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L2026 noExternal
true
| RegExp | string | RegExp []#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L2050 optimizeDeps
– Control over which dependencies are optimized during SSR and esbuild options
+During build:
+no external CJS dependencies are optimized by default
+During dev:
+explicit no external CJS dependencies are optimized by default#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L2033 target
– Define the target for the ssr build. The browser field in package.json
+is ignored for node but used if webworker is the target
+Default: 'node'
SecureContext
SecureContextOptions
string string string | Buffer string boolean string string string number string string number string#
src/.fastpm/-/@types/node@17.0.45/tls.d.ts#L656 ca
– Optionally override the trusted CA certificates. Default is to trust
+the well-known CAs curated by Mozilla. Mozilla's CAs are completely
+replaced when CAs are explicitly specified using this option.#
src/.fastpm/-/@types/node@17.0.45/tls.d.ts#L668 cert
– Cert chains in PEM format. One cert chain should be provided per
+private key. Each cert chain should consist of the PEM formatted
+certificate for a provided private key, followed by the PEM
+formatted intermediate certificates (if any), in order, and not
+including the root CA (the root CA must be pre-known to the peer,
+see ca). When providing multiple cert chains, they do not have to
+be in the same order as their private keys in key. If the
+intermediate certificates are not provided, the peer will not be
+able to validate the certificate, and the handshake will fail.#
src/.fastpm/-/@types/node@17.0.45/tls.d.ts#L682 ciphers
– Cipher suite specification, replacing the default. For more
+information, see modifying the default cipher suite. Permitted
+ciphers can be obtained via tls.getCiphers(). Cipher names must be
+uppercased in order for OpenSSL to accept them.#
src/.fastpm/-/@types/node@17.0.45/tls.d.ts#L686 clientCertEngine
– Name of an OpenSSL engine which can provide the client certificate.#
src/.fastpm/-/@types/node@17.0.45/tls.d.ts#L690 crl
– PEM formatted CRLs (Certificate Revocation Lists).#
src/.fastpm/-/@types/node@17.0.45/tls.d.ts#L699 dhparam
– Diffie Hellman parameters, required for Perfect Forward Secrecy. Use
+openssl dhparam to create the parameters. The key length must be
+greater than or equal to 1024 bits or else an error will be thrown.
+Although 1024 bits is permissible, use 2048 bits or larger for
+stronger security. If omitted or invalid, the parameters are
+silently discarded and DHE ciphers will not be available.#
src/.fastpm/-/@types/node@17.0.45/tls.d.ts#L709 ecdhCurve
– A string describing a named curve or a colon separated list of curve
+NIDs or names, for example P-521:P-384:P-256, to use for ECDH key
+agreement. Set to auto to select the curve automatically. Use
+crypto.getCurves() to obtain a list of available curve names. On
+recent releases, openssl ecparam -list_curves will also display the
+name and description of each available elliptic curve. Default:
+tls.DEFAULT_ECDH_CURVE.#
src/.fastpm/-/@types/node@17.0.45/tls.d.ts#L715 honorCipherOrder
– Attempt to use the server's cipher suite preferences instead of the
+client's. When true, causes SSL_OP_CIPHER_SERVER_PREFERENCE to be
+set in secureOptions#
src/.fastpm/-/@types/node@17.0.45/tls.d.ts#L726 key
– Private keys in PEM format. PEM allows the option of private keys
+being encrypted. Encrypted keys will be decrypted with
+options.passphrase. Multiple keys using different algorithms can be
+provided either as an array of unencrypted key strings or buffers,
+or an array of objects in the form {pem: <string|buffer>[,
+passphrase: <string>]}. The object form can only occur in an array.
+object.passphrase is optional. Encrypted keys will be decrypted with
+object.passphrase if provided, or options.passphrase if it is not.#
src/.fastpm/-/@types/node@17.0.45/tls.d.ts#L746 maxVersion
– Optionally set the maximum TLS version to allow. One
+of 'TLSv1.3'
, 'TLSv1.2'
, 'TLSv1.1'
, or 'TLSv1'
. Cannot be specified along with the
+secureProtocol
option, use one or the other.
+Default: 'TLSv1.3'
, unless changed using CLI options. Using
+--tls-max-v1.2
sets the default to 'TLSv1.2'
. Using --tls-max-v1.3
sets the default to
+'TLSv1.3'
. If multiple of the options are provided, the highest maximum is used.#
src/.fastpm/-/@types/node@17.0.45/tls.d.ts#L757 minVersion
– Optionally set the minimum TLS version to allow. One
+of 'TLSv1.3'
, 'TLSv1.2'
, 'TLSv1.1'
, or 'TLSv1'
. Cannot be specified along with the
+secureProtocol
option, use one or the other. It is not recommended to use
+less than TLSv1.2, but it may be required for interoperability.
+Default: 'TLSv1.2'
, unless changed using CLI options. Using
+--tls-v1.0
sets the default to 'TLSv1'
. Using --tls-v1.1
sets the default to
+'TLSv1.1'
. Using --tls-min-v1.3
sets the default to
+'TLSv1.3'. If multiple of the options are provided, the lowest minimum is used.#
src/.fastpm/-/@types/node@17.0.45/tls.d.ts#L761 passphrase
– Shared passphrase used for a single private key and/or a PFX.#
src/.fastpm/-/@types/node@17.0.45/tls.d.ts#L772 pfx
– PFX or PKCS12 encoded private key and certificate chain. pfx is an
+alternative to providing key and cert individually. PFX is usually
+encrypted, if it is, passphrase will be used to decrypt it. Multiple
+PFX can be provided either as an array of unencrypted PFX buffers,
+or an array of objects in the form {buf: <string|buffer>[,
+passphrase: <string>]}. The object form can only occur in an array.
+object.passphrase is optional. Encrypted PFX will be decrypted with
+object.passphrase if provided, or options.passphrase if it is not.#
src/.fastpm/-/@types/node@17.0.45/tls.d.ts#L731 privateKeyEngine
– Name of an OpenSSL engine to get private key from. Should be used
+together with privateKeyIdentifier.#
src/.fastpm/-/@types/node@17.0.45/tls.d.ts#L737 privateKeyIdentifier
– Identifier of a private key managed by an OpenSSL engine. Should be
+used together with privateKeyEngine. Should not be set together with
+key, because both options define a private key in different ways.#
src/.fastpm/-/@types/node@17.0.45/tls.d.ts#L778 secureOptions
– Optionally affect the OpenSSL protocol behavior, which is not
+usually necessary. This should be used carefully if at all! Value is
+a numeric bitmask of the SSL_OP_* options from OpenSSL Options#
src/.fastpm/-/@types/node@17.0.45/tls.d.ts#L790 secureProtocol
– Legacy mechanism to select the TLS protocol version to use, it does
+not support independent control of the minimum and maximum version,
+and does not support limiting the protocol to TLSv1.3. Use
+minVersion and maxVersion instead. The possible values are listed as
+SSL_METHODS, use the function names as strings. For example, use
+'TLSv1_1_method' to force TLS version 1.1, or 'TLS_method' to allow
+any TLS protocol version up to TLSv1.3. It is not recommended to use
+TLS versions less than 1.2, but it may be required for
+interoperability. Default: none, see minVersion.#
src/.fastpm/-/@types/node@17.0.45/tls.d.ts#L795 sessionIdContext
– Opaque identifier used by servers to ensure session state is not
+shared between applications. Unused by clients.#
src/.fastpm/-/@types/node@17.0.45/tls.d.ts#L806 sessionTimeout
– The number of seconds after which a TLS session created by the
+server will no longer be resumable. See Session Resumption for more
+information. Default: 300.#
src/.fastpm/-/@types/node@17.0.45/tls.d.ts#L675 sigalgs
– Colon-separated list of supported signature algorithms. The list
+can contain digest algorithms (SHA256, MD5 etc.), public key
+algorithms (RSA-PSS, ECDSA etc.), combination of both (e.g
+'RSA+SHA384') or TLS v1.3 scheme names (e.g. rsa_pss_pss_sha512).#
src/.fastpm/-/@types/node@17.0.45/tls.d.ts#L800 ticketKeys
– 48-bytes of cryptographically strong pseudo-random data.
+See Session Resumption for more information.
SerializablePluginCache
ServeOnRequestArgs
number#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L239 timeInMS
– The time to generate the response, not to send it
ServeOptions
– Documentation: https://esbuild.github.io/api/#serve-arguments
ServeResult
– Documentation: https://esbuild.github.io/api/#serve-return-values
Server
Server(req, res, next) =>
addListener(eventName, listener) =>
emit
(eventName, args) – Synchronously calls each of the listeners registered for the event namedeventName
, in the order they were registered, passing the supplied arguments
+to each.
+ +Returns `true` if the event had listeners, `false` otherwise. + +```js +const EventEmitter = require('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 +``` + +
+eventName
string | symbol
args
any []
emit(eventName, args) =>
eventNames
() – Returns an array listing the events for which the emitter has registered
+listeners. The values in the array are strings or Symbol
s.
+ +```js +const EventEmitter = require('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) ] +``` + +
+eventNames() =>
getMaxListeners
() – Returns the current max listener value for the EventEmitter
which is either
+set by emitter.setMaxListeners(n)
or defaults to {@link defaultMaxListeners}.
getMaxListeners() =>
handle
(req, res, next) – Handle server requests, punting them down
+the middleware stack.handle(req, res, next) =>
listen
(port, hostname, backlog, callback) – Listen for connections.
+ +This method takes the same arguments +as node's `http.Server#listen()`. + +HTTP and HTTPS: + +If you run your application both as HTTP +and HTTPS you may wrap them individually, +since your Connect "server" is really just +a JavaScript `Function`. + + var connect = require('connect') + , http = require('http') + , https = require('https'); + + var app = connect(); + + http.createServer(app).listen(80); + https.createServer(options, app).listen(443); + +
+port
number
hostname
string
backlog
number
callback
Function
listen(port, hostname, backlog, callback) =>
port
number
hostname
string
callback
Function
listen(port, hostname, callback) =>
path
string
callback
Function
listen(path, callback) =>
handle
any
listeningListener
Function
listen(handle, listeningListener) =>
listenerCount
(eventName) – Returns the number of listeners listening to the event named eventName
. string | symbol#
eventName
– The name of the event being listened for
+
listenerCount(eventName) =>
listeners
(eventName) – Returns a copy of the array of listeners for the event named eventName
.
+ +```js +server.on('connection', stream => { + console.log('someone connected!') +}) +console.log(util.inspect(server.listeners('connection'))) +// Prints: [ [Function] ] +``` + +
+eventName
string | symbol
listeners(eventName) =>
off
(eventName, listener) – Alias for emitter.removeListener()
. string | symbol#
eventName
off(eventName, listener) =>
on
(eventName, listener) – 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.
+ +```js +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. + +```js +const myEE = new EventEmitter() +myEE.on('foo', () => console.log('a')) +myEE.prependListener('foo', () => console.log('b')) +myEE.emit('foo') +// Prints: +// b +// a +``` + +
+eventName
– The name of the event.string | symbol
listener
(args) any []#
args
listener(args) =>
on(eventName, listener) =>
once
(eventName, listener) – Adds a one-timelistener
function for the event named eventName
. The
+next time eventName
is triggered, this listener is removed and then invoked.
+ +```js +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. + +```js +const myEE = new EventEmitter() +myEE.once('foo', () => console.log('a')) +myEE.prependOnceListener('foo', () => console.log('b')) +myEE.emit('foo') +// Prints: +// b +// a +``` + +
+eventName
– The name of the event.string | symbol
listener
(args) any []#
args
listener(args) =>
once(eventName, listener) =>
prependListener
(eventName, listener) – 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.
+ +```js +server.prependListener('connection', stream => { + console.log('someone connected!') +}) +``` + +Returns a reference to the `EventEmitter`, so that calls can be chained. + +
+eventName
– The name of the event.string | symbol
listener
(args) any []#
args
listener(args) =>
prependListener(eventName, listener) =>
prependOnceListener
(eventName, listener) – Adds a one-timelistener
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.
+ +```js +server.prependOnceListener('connection', stream => { + console.log('Ah, we have our first user!') +}) +``` + +Returns a reference to the `EventEmitter`, so that calls can be chained. + +
+eventName
– The name of the event.string | symbol
listener
(args) any []#
args
listener(args) =>
prependOnceListener(eventName, listener) =>
rawListeners
(eventName) – Returns a copy of the array of listeners for the event named eventName
,
+including any wrappers (such as those created by .once()
).
+ +```js +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') +``` + +
+eventName
string | symbol
rawListeners(eventName) =>
removeAllListeners
(event) – 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. + +
+event
string | symbol
removeAllListeners(event) =>
removeListener
(eventName, listener) – Removes the specified listener
from the listener array for the event namedeventName
.
+ +```js +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. + +```js +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 indices 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: + +```js +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. + +
+eventName
string | symbol
listener
(args) any []#
args
listener(args) =>
removeListener(eventName, listener) =>
setMaxListeners
(n) – By default EventEmitter
s 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 toInfinity
(or 0
) to indicate an unlimited number of listeners.
+ +Returns a reference to the `EventEmitter`, so that calls can be chained. + +
+n
number
setMaxListeners(n) =>
use
(fn) – Utilize the given middleware handle
to the given route
,
+defaulting to /. This "route" is the mount-point for the
+middleware, when given a value other than / the middleware
+is only effective when that segment is present in the request's
+pathname.
+ +For example if we were to mount a function at _/admin_, it would +be invoked on _/admin_, and _/admin/settings_, however it would +not be invoked for _/_, or _/posts_. + +
+fn
use(fn) =>
fn
use(fn) =>
route
string
fn
use(route, fn) =>
route
string
fn
use(route, fn) =>
ServerOptions
string boolean | CorsOptions boolean boolean | HmrOptions string | boolean boolean | ServerOptions boolean | string | boolean string number boolean Record<string, string | ProxyOptions>
+
+Example `vite.config.js`:
+
+```js
+module.exports = {
+ proxy: {
+ // string shorthand
+ '/foo': 'http://localhost:4567/foo',
+ // with options
+ '/api': {
+ target: 'http://jsonplaceholder.typicode.com',
+ changeOrigin: true,
+ rewrite: path => path.replace(/^\/api/, ''),
+ },
+ },
+}
+```
+
+ boolean#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L1982 base
– Prepend this folder to http requests, for use when proxying vite as a subfolder
+Should start and end with the /
character#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L319 cors
– Configure CORS for the dev server.
+Uses https://github.com/expressjs/cors.
+Set to true
to allow all methods from any origin, or configure separately
+using an object.#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L2004 force
– Force dep pre-optimization regardless of whether deps have changed.#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L1986 fs
– Options for files served via '/@fs/'.#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L323 headers
– Specify server response headers.#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L1968 hmr
– Configure HMR-specific options (port, host, path & protocol)#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L280 host
– Specify which IP addresses the server should listen on.
+Set to 0.0.0.0 to listen on all addresses, including LAN and public addresses.#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L285 https
– Enable TLS + HTTP/2.
+Note: this downgrades to TLS only when the proxy option is also used.#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L1977 middlewareMode
– Create Vite dev server to be used as a middleware in an existing server"ssr"
| "html"
#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L289 open
– Open browser window on startup#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L1992 origin
– Origin for the generated asset URLs.#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L271 port
– Specify server port. Note if the port is already being used, Vite will
+automatically try the next available port so this may not be the actual
+port the server ends up listening on.#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L1997 preTransformRequests
– Pre-transform known direct imports#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L312 proxy
– Configure custom proxy rules for the dev server. Expects an object
+of { key: options }
pairs.
+Uses http-proxy
.
+Full options here.#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L275 strictPort
– If enabled, vite will exit if specified port is already in use#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L1973 watch
– chokidar watch options
+https://github.com/paulmillr/chokidar#api
ServerOptions
boolean number#
src/.fastpm/-/@types/node@17.0.45/http.d.ts#L157 insecureHTTPParser
– Use an insecure HTTP parser that accepts invalid HTTP headers when true.
+Using the insecure parser should be avoided.
+See --insecure-http-parser for more information.#
src/.fastpm/-/@types/node@17.0.45/http.d.ts#L150 maxHeaderSize
– Optionally overrides the value of
+--max-http-header-size
for requests received by this server, i.e.
+the maximum length of request headers in bytes.
ServerOptions
any string boolean boolean boolean {} string boolean string boolean boolean string number boolean any number boolean#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L1033 agent
– Object to be passed to http(s).request.#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L1055 auth
– Basic authentication i.e. 'user:password' to compute an Authorization header.#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L1059 autoRewrite
– Rewrites the location host/ port on (301 / 302 / 307 / 308) redirects based on requested host/ port.Default: false.#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L1051 changeOrigin
– Changes the origin of the host header to the target URL.#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L1073 followRedirects
– Specify whether you want to follow redirects. Default: false#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L1031 forward
– URL string to be parsed with the url module.#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L1067 headers
– object with extra headers to be added to target requests.#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L1057 hostRewrite
– Rewrites the location hostname on (301 / 302 / 307 / 308) redirects, Default: null.#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L1047 ignorePath
– Specify whether you want to ignore the proxy path of the incoming request.#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L1049 localAddress
– Local interface string to bind for outgoing connections.#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L1045 prependPath
– Specify whether you want to prepend the target's path to the proxy path.#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L1053 preserveHeaderKeyCase
– specify whether you want to keep letter case of response header key#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L1061 protocolRewrite
– Rewrites the location protocol on (301 / 302 / 307 / 308) redirects to 'http' or 'https'.Default: null.#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L1069 proxyTimeout
– Timeout (in milliseconds) when proxy receives no response from target. Default: 120000 (2 minutes)#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L1075 selfHandleResponse
– If set to true, none of the webOutgoing passes are called and it's your responsibility to appropriately return the response by listening and acting on the proxyRes event#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L1035 ssl
– Object to be passed to https.createServer().#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L1029 target
– URL string to be parsed with the url module.#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L1071 timeout
– Timeout (in milliseconds) for incoming requests#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L1043 toProxy
– Explicitly specify if we are proxying to another proxy.
ServerOptions
boolean | PerMessageDeflateOptions#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L3013 perMessageDeflate
#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L3002 verifyClient
#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L3006 handleProtocols
(protocols, request)
ServerOpts
boolean boolean#
src/.fastpm/-/@types/node@17.0.45/net.d.ts#L391 allowHalfOpen
– Indicates whether half-opened TCP connections are allowed.#
src/.fastpm/-/@types/node@17.0.45/net.d.ts#L396 pauseOnConnect
– Indicates whether the socket should be paused on incoming connections.
ServerStackItem
SocketConstructorOpts
Source
#
src/.fastpm/-/postcss@8.4.14/lib/node.d.ts#L65 end
– The inclusive ending position of the node's source.#
src/.fastpm/-/postcss@8.4.14/lib/node.d.ts#L61 start
– The inclusive starting position of the node’s source.
SourceDescription
#
src/.fastpm/-/rollup@2.77.0/dist/rollup.d.ts#L94 moduleSideEffects
null
| boolean | "no-treeshake"
SourceFindPosition
SourceMap
toString() => #
toString
()
string
toUrl
()
toUrl() =>
SourceMapOptions
boolean string | boolean | #
src/.fastpm/-/postcss@8.4.14/lib/postcss.d.ts#L310 absolute
– Use absolute path in generated source map.#
src/.fastpm/-/postcss@8.4.14/lib/postcss.d.ts#L300 annotation
– Indicates that PostCSS should add annotation comments to the CSS.
+By default, PostCSS will always add a comment with a path
+to the source map. PostCSS will not add annotations to CSS files
+that do not contain any comments.
+ +By default, PostCSS presumes that you want to save the source map as +`opts.to + '.map'` and will use this path in the annotation comment. +A different path can be set by providing a string value for annotation. + +If you have set `inline: true`, annotation cannot be disabled. + +
+from
– Override from
in map’s sources.string
inline
– Indicates that the source map should be embedded in the output CSS
+as a Base64-encoded comment. By default, it is true
.
+But if all previous maps are external, not inline, PostCSS will not embed
+the map even if you do not set this option.boolean
+ +If you have an inline source map, the result.map property will be empty, +as the source map will be contained within the text of `result.css`. + +
+prev
– Source map content from a previous processing step (e.g., Sass).string | boolean | object |
+ +PostCSS will try to read the previous source map +automatically (based on comments within the source CSS), but you can use +this option to identify it manually. + +If desired, you can omit the previous map with prev: `false`. + +
+sourcesContent
– Indicates that PostCSS should set the origin content (e.g., Sass source)
+of the source map. By default, it is true. But if all previous maps do not
+contain sources content, PostCSS will also leave it out even if you
+do not set this option.boolean
SourceMapOptions
string | object#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L2219 content
– Source map object, 'inline' or source map file content
StartOfSourceMap
StaticEventEmitterOptions
StatsBase
isBlockDevice() => #
isBlockDevice
()
boolean
isCharacterDevice
()
isCharacterDevice() =>
isDirectory
()
isDirectory() =>
isFIFO
()
isFIFO() =>
isFile
()
isFile() =>
isSocket
()
isSocket() =>
isSymbolicLink
()
isSymbolicLink() =>
StdinOptions
StreamOptions
AbortSignal#
src/.fastpm/-/@types/node@17.0.45/events.d.ts#L317 signal
– When provided the corresponding AbortController
can be used to cancel an asynchronous action.
construct(this, callback) =>
destroy
(this, error, callback) #
error
null
| Error
destroy(this, error, callback) =>
Stringifier
Stringifier(node, builder) =>
Syntax
#
src/.fastpm/-/postcss@8.4.14/lib/postcss.d.ts#L249 parse
– Function to generate AST by string.#
src/.fastpm/-/postcss@8.4.14/lib/postcss.d.ts#L254 stringify
– Class to generate string by AST.
TLSSocketOptions
string [] | Uint8Array | Uint8Array []#
src/.fastpm/-/@types/node@17.0.45/tls.d.ts#L447 ALPNProtocols
– An array of strings or a Buffer naming possible ALPN protocols.
+(Protocols should be ordered by their priority.)#
src/.fastpm/-/@types/node@17.0.45/tls.d.ts#L457 SNICallback
# (servername, cb) – SNICallback(servername, cb) <Function> A function that will be
+called if the client supports SNI TLS extension. Two arguments
+will be passed when called: servername and cb. SNICallback should
+invoke cb(null, ctx), where ctx is a SecureContext instance.
+(tls.createSecureContext(...) can be used to get a proper
+SecureContext.) If SNICallback wasn't provided the default callback
+with high-level API will be used (see below).
(servername, cb) =>
ca
– Optionally override the trusted CA certificates. Default is to trust
+the well-known CAs curated by Mozilla. Mozilla's CAs are completely
+replaced when CAs are explicitly specified using this option.cert
– Cert chains in PEM format. One cert chain should be provided per
+private key. Each cert chain should consist of the PEM formatted
+certificate for a provided private key, followed by the PEM
+formatted intermediate certificates (if any), in order, and not
+including the root CA (the root CA must be pre-known to the peer,
+see ca). When providing multiple cert chains, they do not have to
+be in the same order as their private keys in key. If the
+intermediate certificates are not provided, the peer will not be
+able to validate the certificate, and the handshake will fail.ciphers
– Cipher suite specification, replacing the default. For more
+information, see modifying the default cipher suite. Permitted
+ciphers can be obtained via tls.getCiphers(). Cipher names must be
+uppercased in order for OpenSSL to accept them.string
clientCertEngine
– Name of an OpenSSL engine which can provide the client certificate.string
crl
– PEM formatted CRLs (Certificate Revocation Lists).dhparam
– Diffie Hellman parameters, required for Perfect Forward Secrecy. Use
+openssl dhparam to create the parameters. The key length must be
+greater than or equal to 1024 bits or else an error will be thrown.
+Although 1024 bits is permissible, use 2048 bits or larger for
+stronger security. If omitted or invalid, the parameters are
+silently discarded and DHE ciphers will not be available.string | Buffer
ecdhCurve
– A string describing a named curve or a colon separated list of curve
+NIDs or names, for example P-521:P-384:P-256, to use for ECDH key
+agreement. Set to auto to select the curve automatically. Use
+crypto.getCurves() to obtain a list of available curve names. On
+recent releases, openssl ecparam -list_curves will also display the
+name and description of each available elliptic curve. Default:
+tls.DEFAULT_ECDH_CURVE.string
enableTrace
– When enabled, TLS packet trace information is written to stderr
. This can be
+used to debug TLS connection problems.boolean
honorCipherOrder
– Attempt to use the server's cipher suite preferences instead of the
+client's. When true, causes SSL_OP_CIPHER_SERVER_PREFERENCE to be
+set in secureOptionsboolean
isServer
– If true the TLS socket will be instantiated in server-mode.
+Defaults to false.boolean
key
– Private keys in PEM format. PEM allows the option of private keys
+being encrypted. Encrypted keys will be decrypted with
+options.passphrase. Multiple keys using different algorithms can be
+provided either as an array of unencrypted key strings or buffers,
+or an array of objects in the form {pem: <string|buffer>[,
+passphrase: <string>]}. The object form can only occur in an array.
+object.passphrase is optional. Encrypted keys will be decrypted with
+object.passphrase if provided, or options.passphrase if it is not.maxVersion
– Optionally set the maximum TLS version to allow. One
+of 'TLSv1.3'
, 'TLSv1.2'
, 'TLSv1.1'
, or 'TLSv1'
. Cannot be specified along with the
+secureProtocol
option, use one or the other.
+Default: 'TLSv1.3'
, unless changed using CLI options. Using
+--tls-max-v1.2
sets the default to 'TLSv1.2'
. Using --tls-max-v1.3
sets the default to
+'TLSv1.3'
. If multiple of the options are provided, the highest maximum is used.minVersion
– Optionally set the minimum TLS version to allow. One
+of 'TLSv1.3'
, 'TLSv1.2'
, 'TLSv1.1'
, or 'TLSv1'
. Cannot be specified along with the
+secureProtocol
option, use one or the other. It is not recommended to use
+less than TLSv1.2, but it may be required for interoperability.
+Default: 'TLSv1.2'
, unless changed using CLI options. Using
+--tls-v1.0
sets the default to 'TLSv1'
. Using --tls-v1.1
sets the default to
+'TLSv1.1'
. Using --tls-min-v1.3
sets the default to
+'TLSv1.3'. If multiple of the options are provided, the lowest minimum is used.passphrase
– Shared passphrase used for a single private key and/or a PFX.string
pfx
– PFX or PKCS12 encoded private key and certificate chain. pfx is an
+alternative to providing key and cert individually. PFX is usually
+encrypted, if it is, passphrase will be used to decrypt it. Multiple
+PFX can be provided either as an array of unencrypted PFX buffers,
+or an array of objects in the form {buf: <string|buffer>[,
+passphrase: <string>]}. The object form can only occur in an array.
+object.passphrase is optional. Encrypted PFX will be decrypted with
+object.passphrase if provided, or options.passphrase if it is not.privateKeyEngine
– Name of an OpenSSL engine to get private key from. Should be used
+together with privateKeyIdentifier.string
privateKeyIdentifier
– Identifier of a private key managed by an OpenSSL engine. Should be
+used together with privateKeyEngine. Should not be set together with
+key, because both options define a private key in different ways.string
requestCert
– If true the server will request a certificate from clients that
+connect and attempt to verify that certificate. Defaults to
+false.boolean
requestOCSP
– If true, specifies that the OCSP status request extension will be
+added to the client hello and an 'OCSPResponse' event will be
+emitted on the socket before establishing a secure communicationboolean
secureContext
– An optional TLS context object from tls.createSecureContext()secureOptions
– Optionally affect the OpenSSL protocol behavior, which is not
+usually necessary. This should be used carefully if at all! Value is
+a numeric bitmask of the SSL_OP_* options from OpenSSL Optionsnumber
secureProtocol
– Legacy mechanism to select the TLS protocol version to use, it does
+not support independent control of the minimum and maximum version,
+and does not support limiting the protocol to TLSv1.3. Use
+minVersion and maxVersion instead. The possible values are listed as
+SSL_METHODS, use the function names as strings. For example, use
+'TLSv1_1_method' to force TLS version 1.1, or 'TLS_method' to allow
+any TLS protocol version up to TLSv1.3. It is not recommended to use
+TLS versions less than 1.2, but it may be required for
+interoperability. Default: none, see minVersion.string
server
– An optional net.Server instance.session
– An optional Buffer instance containing a TLS session.sessionIdContext
– Opaque identifier used by servers to ensure session state is not
+shared between applications. Unused by clients.string
sessionTimeout
– The number of seconds after which a TLS session created by the
+server will no longer be resumable. See Session Resumption for more
+information. Default: 300.number
sigalgs
– Colon-separated list of supported signature algorithms. The list
+can contain digest algorithms (SHA256, MD5 etc.), public key
+algorithms (RSA-PSS, ECDSA etc.), combination of both (e.g
+'RSA+SHA384') or TLS v1.3 scheme names (e.g. rsa_pss_pss_sha512).string
ticketKeys
– 48-bytes of cryptographically strong pseudo-random data.
+See Session Resumption for more information.TcpSocketConnectOpts
#
src/.fastpm/-/@types/node@17.0.45/net.d.ts#L47 onread
– If specified, incoming data is stored in a single buffer and passed to the supplied callback when data arrives on the socket.
+Note: this will cause the streaming functionality to not provide any data, however events like 'error', 'end', and 'close' will
+still be emitted as normal and methods like pause() and resume() will also behave as expected.
TlsOptions
string [] | Uint8Array | Uint8Array []#
src/.fastpm/-/@types/node@17.0.45/tls.d.ts#L447 ALPNProtocols
– An array of strings or a Buffer naming possible ALPN protocols.
+(Protocols should be ordered by their priority.)#
src/.fastpm/-/@types/node@17.0.45/tls.d.ts#L457 SNICallback
– SNICallback(servername, cb) <Function> A function that will be
+called if the client supports SNI TLS extension. Two arguments
+will be passed when called: servername and cb. SNICallback should
+invoke cb(null, ctx), where ctx is a SecureContext instance.
+(tls.createSecureContext(...) can be used to get a proper
+SecureContext.) If SNICallback wasn't provided the default callback
+with high-level API will be used (see below).# (servername, cb) – SNICallback(servername, cb) <Function> A function that will be
+called if the client supports SNI TLS extension. Two arguments
+will be passed when called: servername and cb. SNICallback should
+invoke cb(null, ctx), where ctx is a SecureContext instance.
+(tls.createSecureContext(...) can be used to get a proper
+SecureContext.) If SNICallback wasn't provided the default callback
+with high-level API will be used (see below).
(servername, cb) =>
allowHalfOpen
– Indicates whether half-opened TCP connections are allowed.boolean
ca
– Optionally override the trusted CA certificates. Default is to trust
+the well-known CAs curated by Mozilla. Mozilla's CAs are completely
+replaced when CAs are explicitly specified using this option.cert
– Cert chains in PEM format. One cert chain should be provided per
+private key. Each cert chain should consist of the PEM formatted
+certificate for a provided private key, followed by the PEM
+formatted intermediate certificates (if any), in order, and not
+including the root CA (the root CA must be pre-known to the peer,
+see ca). When providing multiple cert chains, they do not have to
+be in the same order as their private keys in key. If the
+intermediate certificates are not provided, the peer will not be
+able to validate the certificate, and the handshake will fail.ciphers
– Cipher suite specification, replacing the default. For more
+information, see modifying the default cipher suite. Permitted
+ciphers can be obtained via tls.getCiphers(). Cipher names must be
+uppercased in order for OpenSSL to accept them.string
clientCertEngine
– Name of an OpenSSL engine which can provide the client certificate.string
crl
– PEM formatted CRLs (Certificate Revocation Lists).dhparam
– Diffie Hellman parameters, required for Perfect Forward Secrecy. Use
+openssl dhparam to create the parameters. The key length must be
+greater than or equal to 1024 bits or else an error will be thrown.
+Although 1024 bits is permissible, use 2048 bits or larger for
+stronger security. If omitted or invalid, the parameters are
+silently discarded and DHE ciphers will not be available.string | Buffer
ecdhCurve
– A string describing a named curve or a colon separated list of curve
+NIDs or names, for example P-521:P-384:P-256, to use for ECDH key
+agreement. Set to auto to select the curve automatically. Use
+crypto.getCurves() to obtain a list of available curve names. On
+recent releases, openssl ecparam -list_curves will also display the
+name and description of each available elliptic curve. Default:
+tls.DEFAULT_ECDH_CURVE.string
enableTrace
– When enabled, TLS packet trace information is written to stderr
. This can be
+used to debug TLS connection problems.boolean
handshakeTimeout
– Abort the connection if the SSL/TLS handshake does not finish in the
+specified number of milliseconds. A 'tlsClientError' is emitted on
+the tls.Server object whenever a handshake times out. Default:
+120000 (120 seconds).number
honorCipherOrder
– Attempt to use the server's cipher suite preferences instead of the
+client's. When true, causes SSL_OP_CIPHER_SERVER_PREFERENCE to be
+set in secureOptionsboolean
key
– Private keys in PEM format. PEM allows the option of private keys
+being encrypted. Encrypted keys will be decrypted with
+options.passphrase. Multiple keys using different algorithms can be
+provided either as an array of unencrypted key strings or buffers,
+or an array of objects in the form {pem: <string|buffer>[,
+passphrase: <string>]}. The object form can only occur in an array.
+object.passphrase is optional. Encrypted keys will be decrypted with
+object.passphrase if provided, or options.passphrase if it is not.maxVersion
– Optionally set the maximum TLS version to allow. One
+of 'TLSv1.3'
, 'TLSv1.2'
, 'TLSv1.1'
, or 'TLSv1'
. Cannot be specified along with the
+secureProtocol
option, use one or the other.
+Default: 'TLSv1.3'
, unless changed using CLI options. Using
+--tls-max-v1.2
sets the default to 'TLSv1.2'
. Using --tls-max-v1.3
sets the default to
+'TLSv1.3'
. If multiple of the options are provided, the highest maximum is used.minVersion
– Optionally set the minimum TLS version to allow. One
+of 'TLSv1.3'
, 'TLSv1.2'
, 'TLSv1.1'
, or 'TLSv1'
. Cannot be specified along with the
+secureProtocol
option, use one or the other. It is not recommended to use
+less than TLSv1.2, but it may be required for interoperability.
+Default: 'TLSv1.2'
, unless changed using CLI options. Using
+--tls-v1.0
sets the default to 'TLSv1'
. Using --tls-v1.1
sets the default to
+'TLSv1.1'
. Using --tls-min-v1.3
sets the default to
+'TLSv1.3'. If multiple of the options are provided, the lowest minimum is used.passphrase
– Shared passphrase used for a single private key and/or a PFX.string
pauseOnConnect
– Indicates whether the socket should be paused on incoming connections.boolean
pfx
– PFX or PKCS12 encoded private key and certificate chain. pfx is an
+alternative to providing key and cert individually. PFX is usually
+encrypted, if it is, passphrase will be used to decrypt it. Multiple
+PFX can be provided either as an array of unencrypted PFX buffers,
+or an array of objects in the form {buf: <string|buffer>[,
+passphrase: <string>]}. The object form can only occur in an array.
+object.passphrase is optional. Encrypted PFX will be decrypted with
+object.passphrase if provided, or options.passphrase if it is not.privateKeyEngine
– Name of an OpenSSL engine to get private key from. Should be used
+together with privateKeyIdentifier.string
privateKeyIdentifier
– Identifier of a private key managed by an OpenSSL engine. Should be
+used together with privateKeyEngine. Should not be set together with
+key, because both options define a private key in different ways.string
pskIdentityHint
– hint to send to a client to help
+with selecting the identity during TLS-PSK negotiation. Will be ignored
+in TLS 1.3. Upon failing to set pskIdentityHint tlsClientError
will be
+emitted with ERR_TLS_PSK_SET_IDENTIY_HINT_FAILED
code.string
requestCert
– If true the server will request a certificate from clients that
+connect and attempt to verify that certificate. Defaults to
+false.boolean
secureContext
– An optional TLS context object from tls.createSecureContext()secureOptions
– Optionally affect the OpenSSL protocol behavior, which is not
+usually necessary. This should be used carefully if at all! Value is
+a numeric bitmask of the SSL_OP_* options from OpenSSL Optionsnumber
secureProtocol
– Legacy mechanism to select the TLS protocol version to use, it does
+not support independent control of the minimum and maximum version,
+and does not support limiting the protocol to TLSv1.3. Use
+minVersion and maxVersion instead. The possible values are listed as
+SSL_METHODS, use the function names as strings. For example, use
+'TLSv1_1_method' to force TLS version 1.1, or 'TLS_method' to allow
+any TLS protocol version up to TLSv1.3. It is not recommended to use
+TLS versions less than 1.2, but it may be required for
+interoperability. Default: none, see minVersion.string
sessionIdContext
– Opaque identifier used by servers to ensure session state is not
+shared between applications. Unused by clients.string
sessionTimeout
– The number of seconds after which a TLS session created by the
+server will no longer be resumable. See Session Resumption for more
+information. Default: 300.number
sigalgs
– Colon-separated list of supported signature algorithms. The list
+can contain digest algorithms (SHA256, MD5 etc.), public key
+algorithms (RSA-PSS, ECDSA etc.), combination of both (e.g
+'RSA+SHA384') or TLS v1.3 scheme names (e.g. rsa_pss_pss_sha512).string
ticketKeys
– 48-bytes of cryptographically strong pseudo-random data.pskCallback
(socket, identity) string#
identity
– identity parameter sent from the client.
pskCallback(socket, identity) =>
null
| DataView | TypedArrayTransformCallback
TransformCallback(root, result) =>
TransformModuleJSON
#
src/.fastpm/-/rollup@2.77.0/dist/rollup.d.ts#L110 originalSourcemap
null
| ExistingDecodedSourceMap
TransformOptions
TransformOptions
boolean {} Drop [] string boolean boolean string string string boolean number Record<string, LogLevel> Record<string, string | RegExp boolean boolean boolean boolean boolean string [] RegExp string boolean | boolean Record<string, boolean> string | string [] boolean string | { { #
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L48 charset
– Documentation: https://esbuild.github.io/api/#charset#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L73 color
– Documentation: https://esbuild.github.io/api/#color#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L66 define
– Documentation: https://esbuild.github.io/api/#define#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L38 drop
– Documentation: https://esbuild.github.io/api/#drop#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L19 format
– Documentation: https://esbuild.github.io/api/#format#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L21 globalName
– Documentation: https://esbuild.github.io/api/#global-name#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L52 ignoreAnnotations
– Documentation: https://esbuild.github.io/api/#ignore-annotations#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L55 jsx
– Documentation: https://esbuild.github.io/api/#jsx"transform"
| "preserve"
| "automatic"
#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L63 jsxDev
– Documentation: https://esbuild.github.io/api/#jsx-development#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L57 jsxFactory
– Documentation: https://esbuild.github.io/api/#jsx-factory#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L59 jsxFragment
– Documentation: https://esbuild.github.io/api/#jsx-fragment#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L61 jsxImportSource
– Documentation: https://esbuild.github.io/api/#jsx-import-source#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L70 keepNames
– Documentation: https://esbuild.github.io/api/#keep-names#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L12 legalComments
– Documentation: https://esbuild.github.io/api/#legal-comments"external"
| "none"
| "inline"
| "eof"
| "linked"
#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L75 logLevel
– Documentation: https://esbuild.github.io/api/#log-level#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L77 logLimit
– Documentation: https://esbuild.github.io/api/#log-limit#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L79 logOverride
– Documentation: https://esbuild.github.io/api/#log-override#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L36 mangleCache
– Documentation: https://esbuild.github.io/api/#mangle-propsfalse
>#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L30 mangleProps
– Documentation: https://esbuild.github.io/api/#mangle-props#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L34 mangleQuoted
– Documentation: https://esbuild.github.io/api/#mangle-props#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L40 minify
– Documentation: https://esbuild.github.io/api/#minify#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L44 minifyIdentifiers
– Documentation: https://esbuild.github.io/api/#minify#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L46 minifySyntax
– Documentation: https://esbuild.github.io/api/#minify#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L42 minifyWhitespace
– Documentation: https://esbuild.github.io/api/#minify#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L27 platform
– Documentation: https://esbuild.github.io/api/#platform#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L68 pure
– Documentation: https://esbuild.github.io/api/#pure#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L32 reserveProps
– Documentation: https://esbuild.github.io/api/#mangle-props#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L14 sourceRoot
– Documentation: https://esbuild.github.io/api/#source-root#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L10 sourcemap
– Documentation: https://esbuild.github.io/api/#sourcemap"external"
| "inline"
| "linked"
| "both"
#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L16 sourcesContent
– Documentation: https://esbuild.github.io/api/#sources-content#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L25 supported
– Documentation: https://esbuild.github.io/api/#supported#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L23 target
– Documentation: https://esbuild.github.io/api/#target#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L50 treeShaking
– Documentation: https://esbuild.github.io/api/#tree-shaking#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L251 tsconfigRaw
#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L252 compilerOptions
#
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L256 importsNotUsedAsValues
"error"
| "preserve"
| "remove"
TransformPluginContext
string addWatchFile(id) => #
src/.fastpm/-/rollup@2.77.0/dist/rollup.d.ts#L186 addWatchFile
(id)
#
id
void
error
(err, pos) string | RollupError number | { #
err
#
pos
error(err, pos) =>
getAssetFileName
(assetReferenceId) string#
assetReferenceId
getAssetFileName(assetReferenceId) =>
getChunkFileName
(chunkReferenceId) string#
chunkReferenceId
getChunkFileName(chunkReferenceId) =>
getCombinedSourcemap
()
getCombinedSourcemap() =>
getFileName
(fileReferenceId) string#
fileReferenceId
getFileName(fileReferenceId) =>
getModuleIds
()
getModuleIds() =>
getWatchFiles
()
getWatchFiles() =>
load
(options) { #
options
load(options) =>
parse
(input, options) resolve
(source, importer, { custom, isEntry, skipSelf }) resolve(source, importer, { custom, isEntry, skipSelf }) =>
null
| ResolvedId>resolveId
(source, importer) setAssetSource
(assetReferenceId, source) warn
(warning, pos) string | RollupWarning number | { #
warning
#
pos
warn(warning, pos) =>
TransformResult
TransformResult
Record<string, string | #
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L272 mangleCache
– Only when "mangleCache" is presentfalse
>
Transformer
Transformer(root, result) =>
TreeshakingOptions
Update
UpdatePayload
Url
UserConfig
string | RegExp | string | RegExp [] string string Record<string, any> string string | string []
+
+Features under this field could change in the future and might NOT follow semver.
+Please be careful and always pin Vite's version when using them.
+
+
+
+Features under this field only follow semver for patches, they could be removed in a
+future minor version. Please always pin Vite's version to a minor when using them.
+
+ string PluginOption [] string |
+
+Set to `false` or an empty string to disable copied static assets to build dist dir.
+
+ ResolveOptions & { #
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L2405 appType
– Whether your application is a Single Page Application (SPA),
+a Multi-Page Application (MPA), or Custom Application (SSR
+and frameworks with custom HTML handling)#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L2321 assetsInclude
– Specify additional picomatch patterns to be treated as static assets.#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L2265 base
– Base public path when served in development or production.#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L2284 cacheDir
– Directory to save cache files. Files in this directory are pre-bundled
+deps or some other cache files that generated by vite, which can improve
+the performance. You can use --force
flag or manually delete the directory
+to regenerate the cache files. The value can be either an absolute file
+system path or a path relative to <root>.
+Default to .vite
when no package.json
is detected.#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L2308 css
– CSS related options (preprocessors and CSS modules)#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L2294 define
– Define global variable replacements.
+Entries will be defined on window
during dev and replaced during build.#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L2375 envDir
– Environment files directory. Can be an absolute path, or a path relative from
+the location of the config file itself.#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L2380 envPrefix
– Env variables starts with envPrefix
will be exposed to your client source code via import.meta.env.#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L2317 esbuild
– Transform options to pass to esbuild.
+Or set to false
to disable esbuild.false
| ESBuildOptions#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L2349 experimental
– Experimental features
#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L2356 legacy
– Legacy options
#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L2361 logLevel
– Log level.
+Default: 'info'#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L2289 mode
– Explicitly set a mode to run in. This will override the default mode for
+each command, and can be overridden by the command line --mode option.#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L2337 optimizeDeps
– Dep optimization options#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L2298 plugins
– Array of vite plugins to use.#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L2333 preview
– Preview specific options, e.g. host, port, https...#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L2274 publicDir
– Directory to serve as plain static assets. Files in this directory are
+served and copied to build dist dir as-is without transform. The value
+can be either an absolute file system path or a path relative to <root>.false
#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L2302 resolve
– Configure resolver
root
– Project root directory. Can be an absolute path, or a path relative from
+the location of the config file itself.string
server
– Server specific options, e.g. host, port, https...ssr
– SSR specific optionsworker
– Worker bundle options{
PluginOption [] Omit<RollupOptions, #
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L2389 format
– Output format for worker bundle"es"
| "iife"
#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L2393 plugins
– Vite plugins that apply to worker bundle#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L2397 rollupOptions
– Rollup options to build worker bundle"plugins"
| "input"
| "onwarn"
| "preserveEntrySignatures"
>
ValueOptions
string#
src/.fastpm/-/postcss@8.4.14/lib/container.d.ts#L16 fast
– String that’s used to narrow down values and speed up the regexp search.
ViteDevServer
Readonly<Omit<UserConfig, string assetsInclude(file) => #
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L2418 config
– The resolved vite config object"plugins"
| "assetsInclude"
| "optimizeDeps"
| "worker"
> & {#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L1681 assetsInclude
(file)
#
file
boolean
createResolver
(options) Partial<InternalResolveOptions>#
options
createResolver(options) =>
httpServer
– native Node http server instance
+will be null in middleware modenull
| Server
middlewares
– A connect app instance.
+- Can be used to attach custom middlewares to the dev server.
+- Can also be used as the handler function of a custom http server
+or as a middleware in any connect-style Node.js frameworks+ +https://github.com/senchalabs/connect#use-middleware + +
+moduleGraph
– Module graph that tracks the import relationships, url to file mapping
+and hmr state.pluginContainer
– Rollup plugin container that can run plugin hooks on a given fileresolvedUrls
– The resolved urls Vite prints on the CLI. null in middleware mode or
+before server.listen
is called.null
| ResolvedServerUrls
watcher
– chokidar watcher instance
+https://github.com/paulmillr/chokidar#apiws
– web socket server with send(payload)
methodclose
() – Stop the server.
close() =>
listen
(port, isRestart) – Start the server.printUrls
() – Print server urls
printUrls() =>
restart
(forceOptimize) – Restart the server. boolean#
forceOptimize
– force the optimizer to re-bundle, same as --force cli flag
+
restart(forceOptimize) =>
ssrFixStacktrace
(e) – Mutates the given SSR error by rewriting the stacktrace Error#
e
ssrFixStacktrace(e) =>
ssrLoadModule
(url, { fixStacktrace }) – Load a given URL as an instantiated module for SSR.ssrLoadModule(url, { fixStacktrace }) =>
ssrRewriteStacktrace
(stack) – Returns a fixed version of the given stack string#
stack
ssrRewriteStacktrace(stack) =>
ssrTransform
(code, inMap, url) – Transform module code into SSR format.transformIndexHtml
(url, html, originalUrl) – Apply vite built-in HTML transforms and any plugin HTML transforms.transformRequest
(url, options) – Programmatically resolve, load and transform a URL and get the result
+without going through the http request pipeline.transformRequest(url, options) =>
null
| TransformResult>WarningOptions
number number string string#
src/.fastpm/-/postcss@8.4.14/lib/warning.d.ts#L33 end
– End position, exclusive, in CSS node string that caused the warning.#
src/.fastpm/-/postcss@8.4.14/lib/warning.d.ts#L23 endIndex
– End index, exclusive, in CSS node string that caused the warning.#
src/.fastpm/-/postcss@8.4.14/lib/warning.d.ts#L18 index
– Start index, inclusive, in CSS node string that caused the warning.#
src/.fastpm/-/postcss@8.4.14/lib/warning.d.ts#L39 plugin
– Name of the plugin that created this warning. Result#warn
fills
+this property automatically.#
src/.fastpm/-/postcss@8.4.14/lib/warning.d.ts#L28 start
– Start position, inclusive, in CSS node string that caused the warning.#
src/.fastpm/-/postcss@8.4.14/lib/warning.d.ts#L13 word
– Word in CSS source that caused the warning.
WatchMode
onRebuild(error, result) => #
src/.fastpm/-/esbuild@0.14.53/lib/main.d.ts#L146 onRebuild
(error, result)
#
error
null
| BuildFailure#
result
null
| BuildResultvoid
WatchOptions
boolean number | boolean boolean | AwaitWriteFinishOptions number string number boolean boolean boolean boolean number boolean boolean boolean#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L2574 alwaysStat
– If relying upon the fs.Stats
object that
+may get passed with add
, addDir
, and change
events, set this to true
to ensure it is
+provided even in cases where it wasn't already available from the underlying watch events.#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L2606 atomic
– true
if useFsEvents
and usePolling
are false
). Automatically filters out artifacts
+that occur when using editors that use "atomic writes" instead of writing directly to the
+source file. If a file is re-added within 100 ms of being deleted, Chokidar emits a change
+event rather than unlink
then add
. If the default of 100 ms does not work well for you,
+you can override it by setting atomic
to a custom value, in milliseconds.#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L2611 awaitWriteFinish
– can be set to an object in order to adjust timing params:#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L2590 binaryInterval
– Interval of file system polling for binary files. ([see list of binary extensions](https://gi
+thub.com/sindresorhus/binary-extensions/blob/master/binary-extensions.json))#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L2543 cwd
– The base directory from which watch paths
are to be derived. Paths emitted with events will
+be relative to this.#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L2579 depth
– If set, limits how many levels of subdirectories will be traversed.#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L2551 disableGlobbing
– If set to true then the strings passed to .watch() and .add() are treated as literal path
+names, even if they look like globs.#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L2537 followSymlinks
– When false
, only the symlinks themselves will be watched for changes instead of following
+the link references and bubbling events through the link's path.#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L2531 ignoreInitial
– If set to false
then add
/addDir
events are also emitted for matching paths while
+instantiating the watching as chokidar discovers these file paths (before the ready
event).#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L2597 ignorePermissionErrors
– Indicates whether to watch files that don't have read permissions if possible. If watching
+fails due to EPERM
or EACCES
with this set to true
, the errors will be suppressed
+silently.#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L2525 ignored
– (anymatch-compatible definition) Defines files/paths to
+be ignored. The whole relative or absolute path is tested, not just filename. If a function
+with two arguments is provided, it gets called twice per path - once with a single argument
+(the path), second time with two arguments (the path and the
+fs.Stats
object of that path).#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L2584 interval
– Interval of file system polling.#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L2516 persistent
– Indicates whether the process should continue to run as long as files are being watched. If
+set to false
when using fsevents
to watch, no more events will be emitted after ready
,
+even if the process continues to run.#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L2567 useFsEvents
– Whether to use the fsevents
watching interface if available. When set to true
explicitly
+and fsevents
is available this supercedes the usePolling
setting. When set to false
on
+OS X, usePolling: true
becomes the default.#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L2560 usePolling
– Whether to use fs.watchFile (backed by polling), or fs.watch. If polling leads to high CPU
+utilization, consider setting this to false
. It is typically necessary to set this to
+true
to successfully watch files over a network, and it may be necessary to successfully
+watch files in other non-standard situations. Setting to true
explicitly on OS X overrides
+the useFsEvents
default.
WatcherOptions
WebSocket
boolean#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L2643 CLOSING
– The connection is in the process of closing.2
#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L2639 CONNECTING
– The connection is not yet open.0
#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L2641 OPEN
– The connection is open and ready to communicate.1
#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L2624 binaryType
"nodebuffer"
| "arraybuffer"
| "fragments"
#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L2628 isPaused
– Indicates whether the websocket is paused
onerror
onmessage
onopen
null
|
protocol
string
readyState
– The current state of the connection0
| 1
| 2
| 3
url
string
addEventListener
(method, cb, options) options
addEventListener(method, cb, options) =>
method
"close"
cb
(event) #
event
cb(event) =>
options
addEventListener(method, cb, options) =>
method
"error"
cb
(event) #
event
cb(event) =>
options
addEventListener(method, cb, options) =>
method
"open"
options
addEventListener(method, cb, options) =>
addListener
(event, listener) #
event
"close"
addListener(event, listener) =>
event
"error"
listener
(err) Error#
err
listener(err) =>
addListener(event, listener) =>
event
"upgrade"
listener
(request) #
request
listener(request) =>
addListener(event, listener) =>
event
"message"
addListener(event, listener) =>
event
"open"
listener
()
listener() =>
addListener(event, listener) =>
event
"ping"
| "pong"
addListener(event, listener) =>
event
"unexpected-response"
listener
(request, response) listener(request, response) =>
addListener(event, listener) =>
event
string | symbol
listener
(args) any []#
args
listener(args) =>
addListener(event, listener) =>
close
(code, data) number#
code
close(code, data) =>
emit
(eventName, args) – Synchronously calls each of the listeners registered for the event namedeventName
, in the order they were registered, passing the supplied arguments
+to each.
+ +Returns `true` if the event had listeners, `false` otherwise. + +```js +const EventEmitter = require('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 +``` + +
+eventName
string | symbol
args
any []
emit(eventName, args) =>
eventNames
() – Returns an array listing the events for which the emitter has registered
+listeners. The values in the array are strings or Symbol
s.
+ +```js +const EventEmitter = require('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) ] +``` + +
+eventNames() =>
getMaxListeners
() – Returns the current max listener value for the EventEmitter
which is either
+set by emitter.setMaxListeners(n)
or defaults to {@link defaultMaxListeners}.
getMaxListeners() =>
listenerCount
(eventName) – Returns the number of listeners listening to the event named eventName
. string | symbol#
eventName
– The name of the event being listened for
+
listenerCount(eventName) =>
listeners
(eventName) – Returns a copy of the array of listeners for the event named eventName
.
+ +```js +server.on('connection', stream => { + console.log('someone connected!') +}) +console.log(util.inspect(server.listeners('connection'))) +// Prints: [ [Function] ] +``` + +
+eventName
string | symbol
listeners(eventName) =>
off
(event, listener) #
event
"close"
off(event, listener) =>
event
"error"
listener
(this, err) listener(this, err) =>
off(event, listener) =>
event
"upgrade"
listener
(this, request) listener(this, request) =>
off(event, listener) =>
event
"message"
listener
(this, data, isBinary) listener(this, data, isBinary) =>
off(event, listener) =>
event
"open"
listener
(this) #
this
listener(this) =>
off(event, listener) =>
event
"ping"
| "pong"
listener
(this, data) #
this
listener(this, data) =>
off(event, listener) =>
event
"unexpected-response"
listener
(this, request, response) listener(this, request, response) =>
off(event, listener) =>
event
string | symbol
listener
(this, args) listener(this, args) =>
off(event, listener) =>
on
(event, listener) #
event
"close"
on(event, listener) =>
event
"error"
listener
(this, err) listener(this, err) =>
on(event, listener) =>
event
"upgrade"
listener
(this, request) listener(this, request) =>
on(event, listener) =>
event
"message"
listener
(this, data, isBinary) listener(this, data, isBinary) =>
on(event, listener) =>
event
"open"
listener
(this) #
this
listener(this) =>
on(event, listener) =>
event
"ping"
| "pong"
listener
(this, data) #
this
listener(this, data) =>
on(event, listener) =>
event
"unexpected-response"
listener
(this, request, response) listener(this, request, response) =>
on(event, listener) =>
event
string | symbol
listener
(this, args) listener(this, args) =>
on(event, listener) =>
once
(event, listener) #
event
"close"
once(event, listener) =>
event
"error"
listener
(this, err) listener(this, err) =>
once(event, listener) =>
event
"upgrade"
listener
(this, request) listener(this, request) =>
once(event, listener) =>
event
"message"
listener
(this, data, isBinary) listener(this, data, isBinary) =>
once(event, listener) =>
event
"open"
listener
(this) #
this
listener(this) =>
once(event, listener) =>
event
"ping"
| "pong"
listener
(this, data) #
this
listener(this, data) =>
once(event, listener) =>
event
"unexpected-response"
listener
(this, request, response) listener(this, request, response) =>
once(event, listener) =>
event
string | symbol
listener
(this, args) listener(this, args) =>
once(event, listener) =>
pause
() – Pause the websocket causing it to stop emitting events. Some events can still be
+emitted after this is called, until all buffered data is consumed. This method
+is a noop if the ready state is CONNECTING
or CLOSED
.
pause() =>
ping
(data, mask, cb) ping(data, mask, cb) =>
pong
(data, mask, cb) pong(data, mask, cb) =>
prependListener
(eventName, listener) – 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.
+ +```js +server.prependListener('connection', stream => { + console.log('someone connected!') +}) +``` + +Returns a reference to the `EventEmitter`, so that calls can be chained. + +
+eventName
– The name of the event.string | symbol
listener
(args) any []#
args
listener(args) =>
prependListener(eventName, listener) =>
prependOnceListener
(eventName, listener) – Adds a one-timelistener
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.
+ +```js +server.prependOnceListener('connection', stream => { + console.log('Ah, we have our first user!') +}) +``` + +Returns a reference to the `EventEmitter`, so that calls can be chained. + +
+eventName
– The name of the event.string | symbol
listener
(args) any []#
args
listener(args) =>
prependOnceListener(eventName, listener) =>
rawListeners
(eventName) – Returns a copy of the array of listeners for the event named eventName
,
+including any wrappers (such as those created by .once()
).
+ +```js +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') +``` + +
+eventName
string | symbol
rawListeners(eventName) =>
removeAllListeners
(event) – 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. + +
+event
string | symbol
removeAllListeners(event) =>
removeEventListener
(method, cb) removeEventListener(method, cb) =>
method
"close"
cb
(event) #
event
cb(event) =>
removeEventListener(method, cb) =>
method
"error"
cb
(event) #
event
cb(event) =>
removeEventListener(method, cb) =>
method
"open"
removeEventListener(method, cb) =>
removeListener
(event, listener) #
event
"close"
removeListener(event, listener) =>
event
"error"
listener
(err) Error#
err
listener(err) =>
removeListener(event, listener) =>
event
"upgrade"
listener
(request) #
request
listener(request) =>
removeListener(event, listener) =>
event
"message"
removeListener(event, listener) =>
event
"open"
listener
()
listener() =>
removeListener(event, listener) =>
event
"ping"
| "pong"
removeListener(event, listener) =>
event
"unexpected-response"
listener
(request, response) listener(request, response) =>
removeListener(event, listener) =>
event
string | symbol
listener
(args) any []#
args
listener(args) =>
removeListener(event, listener) =>
resume
() – Make a paused socket resume emitting events. This method is a noop if the ready
+state is CONNECTING
or CLOSED
.
resume() =>
send
(data, cb) any#
data
send(data, cb) =>
data
any
options
{
}
cb
(err) Error#
err
cb(err) =>
send(data, { binary, compress, fin, mask }, cb) =>
setMaxListeners
(n) – By default EventEmitter
s 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 toInfinity
(or 0
) to indicate an unlimited number of listeners.
+ +Returns a reference to the `EventEmitter`, so that calls can be chained. + +
+n
number
setMaxListeners(n) =>
terminate
()
terminate() =>
WebSocketAlias
boolean#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L2643 CLOSING
– The connection is in the process of closing.2
#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L2639 CONNECTING
– The connection is not yet open.0
#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L2641 OPEN
– The connection is open and ready to communicate.1
#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L2624 binaryType
"nodebuffer"
| "arraybuffer"
| "fragments"
#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L2628 isPaused
– Indicates whether the websocket is paused
onerror
onmessage
onopen
null
|
protocol
string
readyState
– The current state of the connection0
| 1
| 2
| 3
url
string
addEventListener
(method, cb, options) options
addEventListener(method, cb, options) =>
method
"close"
cb
(event) #
event
cb(event) =>
options
addEventListener(method, cb, options) =>
method
"error"
cb
(event) #
event
cb(event) =>
options
addEventListener(method, cb, options) =>
method
"open"
options
addEventListener(method, cb, options) =>
addListener
(event, listener) – Alias for emitter.on(eventName, listener)
. #
event
"close"
addListener(event, listener) =>
event
"error"
listener
(err) Error#
err
listener(err) =>
addListener(event, listener) =>
event
"upgrade"
listener
(request) #
request
listener(request) =>
addListener(event, listener) =>
event
"message"
addListener(event, listener) =>
event
"open"
listener
()
listener() =>
addListener(event, listener) =>
event
"ping"
| "pong"
addListener(event, listener) =>
event
"unexpected-response"
listener
(request, response) listener(request, response) =>
addListener(event, listener) =>
event
string | symbol
listener
(args) any []#
args
listener(args) =>
addListener(event, listener) =>
close
(code, data) number#
code
close(code, data) =>
emit
(eventName, args) – Synchronously calls each of the listeners registered for the event namedeventName
, in the order they were registered, passing the supplied arguments
+to each.
+ +Returns `true` if the event had listeners, `false` otherwise. + +```js +const EventEmitter = require('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 +``` + +
+eventName
string | symbol
args
any []
emit(eventName, args) =>
eventNames
() – Returns an array listing the events for which the emitter has registered
+listeners. The values in the array are strings or Symbol
s.
+ +```js +const EventEmitter = require('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) ] +``` + +
+eventNames() =>
getMaxListeners
() – Returns the current max listener value for the EventEmitter
which is either
+set by emitter.setMaxListeners(n)
or defaults to {@link defaultMaxListeners}.
getMaxListeners() =>
listenerCount
(eventName) – Returns the number of listeners listening to the event named eventName
. string | symbol#
eventName
– The name of the event being listened for
+
listenerCount(eventName) =>
listeners
(eventName) – Returns a copy of the array of listeners for the event named eventName
.
+ +```js +server.on('connection', stream => { + console.log('someone connected!') +}) +console.log(util.inspect(server.listeners('connection'))) +// Prints: [ [Function] ] +``` + +
+eventName
string | symbol
listeners(eventName) =>
off
(event, listener) – Alias for emitter.removeListener()
. #
event
"close"
off(event, listener) =>
event
"error"
listener
(this, err) listener(this, err) =>
off(event, listener) =>
event
"upgrade"
listener
(this, request) listener(this, request) =>
off(event, listener) =>
event
"message"
listener
(this, data, isBinary) listener(this, data, isBinary) =>
off(event, listener) =>
event
"open"
listener
(this) #
this
listener(this) =>
off(event, listener) =>
event
"ping"
| "pong"
listener
(this, data) #
this
listener(this, data) =>
off(event, listener) =>
event
"unexpected-response"
listener
(this, request, response) listener(this, request, response) =>
off(event, listener) =>
event
string | symbol
listener
(this, args) listener(this, args) =>
off(event, listener) =>
on
(event, listener) – 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.
+ +```js +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. + +```js +const myEE = new EventEmitter() +myEE.on('foo', () => console.log('a')) +myEE.prependListener('foo', () => console.log('b')) +myEE.emit('foo') +// Prints: +// b +// a +``` + +
+event
"close"
listener
(this, code, reason) listener(this, code, reason) =>
on(event, listener) =>
event
"error"
listener
(this, err) listener(this, err) =>
on(event, listener) =>
event
"upgrade"
listener
(this, request) listener(this, request) =>
on(event, listener) =>
event
"message"
listener
(this, data, isBinary) listener(this, data, isBinary) =>
on(event, listener) =>
event
"open"
listener
(this) #
this
listener(this) =>
on(event, listener) =>
event
"ping"
| "pong"
listener
(this, data) #
this
listener(this, data) =>
on(event, listener) =>
event
"unexpected-response"
listener
(this, request, response) listener(this, request, response) =>
on(event, listener) =>
event
string | symbol
listener
(this, args) listener(this, args) =>
on(event, listener) =>
once
(event, listener) – Adds a one-timelistener
function for the event named eventName
. The
+next time eventName
is triggered, this listener is removed and then invoked.
+ +```js +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. + +```js +const myEE = new EventEmitter() +myEE.once('foo', () => console.log('a')) +myEE.prependOnceListener('foo', () => console.log('b')) +myEE.emit('foo') +// Prints: +// b +// a +``` + +
+event
"close"
listener
(this, code, reason) listener(this, code, reason) =>
once(event, listener) =>
event
"error"
listener
(this, err) listener(this, err) =>
once(event, listener) =>
event
"upgrade"
listener
(this, request) listener(this, request) =>
once(event, listener) =>
event
"message"
listener
(this, data, isBinary) listener(this, data, isBinary) =>
once(event, listener) =>
event
"open"
listener
(this) #
this
listener(this) =>
once(event, listener) =>
event
"ping"
| "pong"
listener
(this, data) #
this
listener(this, data) =>
once(event, listener) =>
event
"unexpected-response"
listener
(this, request, response) listener(this, request, response) =>
once(event, listener) =>
event
string | symbol
listener
(this, args) listener(this, args) =>
once(event, listener) =>
pause
() – Pause the websocket causing it to stop emitting events. Some events can still be
+emitted after this is called, until all buffered data is consumed. This method
+is a noop if the ready state is CONNECTING
or CLOSED
.
pause() =>
ping
(data, mask, cb) ping(data, mask, cb) =>
pong
(data, mask, cb) pong(data, mask, cb) =>
prependListener
(eventName, listener) – 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.
+ +```js +server.prependListener('connection', stream => { + console.log('someone connected!') +}) +``` + +Returns a reference to the `EventEmitter`, so that calls can be chained. + +
+eventName
– The name of the event.string | symbol
listener
(args) any []#
args
listener(args) =>
prependListener(eventName, listener) =>
prependOnceListener
(eventName, listener) – Adds a one-timelistener
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.
+ +```js +server.prependOnceListener('connection', stream => { + console.log('Ah, we have our first user!') +}) +``` + +Returns a reference to the `EventEmitter`, so that calls can be chained. + +
+eventName
– The name of the event.string | symbol
listener
(args) any []#
args
listener(args) =>
prependOnceListener(eventName, listener) =>
rawListeners
(eventName) – Returns a copy of the array of listeners for the event named eventName
,
+including any wrappers (such as those created by .once()
).
+ +```js +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') +``` + +
+eventName
string | symbol
rawListeners(eventName) =>
removeAllListeners
(event) – 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. + +
+event
string | symbol
removeAllListeners(event) =>
removeEventListener
(method, cb) removeEventListener(method, cb) =>
method
"close"
cb
(event) #
event
cb(event) =>
removeEventListener(method, cb) =>
method
"error"
cb
(event) #
event
cb(event) =>
removeEventListener(method, cb) =>
method
"open"
removeEventListener(method, cb) =>
removeListener
(event, listener) – Removes the specified listener
from the listener array for the event namedeventName
.
+ +```js +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. + +```js +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 indices 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: + +```js +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. + +
+event
"close"
removeListener(event, listener) =>
event
"error"
listener
(err) Error#
err
listener(err) =>
removeListener(event, listener) =>
event
"upgrade"
listener
(request) #
request
listener(request) =>
removeListener(event, listener) =>
event
"message"
removeListener(event, listener) =>
event
"open"
listener
()
listener() =>
removeListener(event, listener) =>
event
"ping"
| "pong"
removeListener(event, listener) =>
event
"unexpected-response"
listener
(request, response) listener(request, response) =>
removeListener(event, listener) =>
event
string | symbol
listener
(args) any []#
args
listener(args) =>
removeListener(event, listener) =>
resume
() – Make a paused socket resume emitting events. This method is a noop if the ready
+state is CONNECTING
or CLOSED
.
resume() =>
send
(data, cb) any#
data
send(data, cb) =>
data
any
options
{
}
cb
(err) Error#
err
cb(err) =>
send(data, { binary, compress, fin, mask }, cb) =>
setMaxListeners
(n) – By default EventEmitter
s 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 toInfinity
(or 0
) to indicate an unlimited number of listeners.
+ +Returns a reference to the `EventEmitter`, so that calls can be chained. + +
+n
number
setMaxListeners(n) =>
terminate
()
terminate() =>
WebSocketClient
#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L3147 socket
– The raw WebSocket instance
event
string
payload
any
send(event, payload) =>
WebSocketServer
Set<WebSocketClient>#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L3156 clients
– Get all connected clients.
(event, cb) =>
event
"error"
(event, cb) =>
event
"headers"
cb
(this, headers, request) cb(this, headers, request) =>
(event, cb) =>
event
"close"
| "listening"
(event, cb) =>
event
string | symbol
(event, listener) =>
on
– Handle custom event emitted by import.meta.hot.send
{
#
event
"connection"
(event, cb) =>
event
"error"
(event, cb) =>
event
"headers"
cb
(this, headers, request) cb(this, headers, request) =>
(event, cb) =>
event
"close"
| "listening"
(event, cb) =>
event
string | symbol
(event, listener) =>
#
listener
<T>(event, listener) =>
close
() – Disconnect all clients and terminate the server.
close() =>
send
(payload) – Boardcast events to all clients #
payload
send(payload) =>
event
payload
send<T>(event, payload) =>
WritableOptions
AbortSignal#
src/.fastpm/-/@types/node@17.0.45/events.d.ts#L317 signal
– When provided the corresponding AbortController
can be used to cancel an asynchronous action.
construct(this, callback) =>
destroy
(this, error, callback) #
error
null
| Error
destroy(this, error, callback) =>
final
(this, callback)
final(this, callback) =>
write
(this, chunk, encoding, callback) write(this, chunk, encoding, callback) =>
writev
(this, chunks, callback) { #
chunks
callback
(error) #
error
null
| Error
callback(error) =>
writev(this, chunks, callback) =>
WritableStream
addListener(eventName, listener) =>
emit
(eventName, args) – Synchronously calls each of the listeners registered for the event namedeventName
, in the order they were registered, passing the supplied arguments
+to each.
+ +Returns `true` if the event had listeners, `false` otherwise. + +```js +const EventEmitter = require('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 +``` + +
+eventName
string | symbol
args
any []
emit(eventName, args) =>
end
(cb) cb() => #
cb
()
void
end(cb) =>
data
string | Uint8Array
cb
()
cb() =>
end(data, cb) =>
str
string
encoding
cb
()
cb() =>
end(str, encoding, cb) =>
eventNames
() – Returns an array listing the events for which the emitter has registered
+listeners. The values in the array are strings or Symbol
s.
+ +```js +const EventEmitter = require('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) ] +``` + +
+eventNames() =>
getMaxListeners
() – Returns the current max listener value for the EventEmitter
which is either
+set by emitter.setMaxListeners(n)
or defaults to {@link defaultMaxListeners}.
getMaxListeners() =>
listenerCount
(eventName) – Returns the number of listeners listening to the event named eventName
. string | symbol#
eventName
– The name of the event being listened for
+
listenerCount(eventName) =>
listeners
(eventName) – Returns a copy of the array of listeners for the event named eventName
.
+ +```js +server.on('connection', stream => { + console.log('someone connected!') +}) +console.log(util.inspect(server.listeners('connection'))) +// Prints: [ [Function] ] +``` + +
+eventName
string | symbol
listeners(eventName) =>
off
(eventName, listener) – Alias for emitter.removeListener()
. string | symbol#
eventName
off(eventName, listener) =>
on
(eventName, listener) – 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.
+ +```js +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. + +```js +const myEE = new EventEmitter() +myEE.on('foo', () => console.log('a')) +myEE.prependListener('foo', () => console.log('b')) +myEE.emit('foo') +// Prints: +// b +// a +``` + +
+eventName
– The name of the event.string | symbol
listener
(args) any []#
args
listener(args) =>
on(eventName, listener) =>
once
(eventName, listener) – Adds a one-timelistener
function for the event named eventName
. The
+next time eventName
is triggered, this listener is removed and then invoked.
+ +```js +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. + +```js +const myEE = new EventEmitter() +myEE.once('foo', () => console.log('a')) +myEE.prependOnceListener('foo', () => console.log('b')) +myEE.emit('foo') +// Prints: +// b +// a +``` + +
+eventName
– The name of the event.string | symbol
listener
(args) any []#
args
listener(args) =>
once(eventName, listener) =>
prependListener
(eventName, listener) – 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.
+ +```js +server.prependListener('connection', stream => { + console.log('someone connected!') +}) +``` + +Returns a reference to the `EventEmitter`, so that calls can be chained. + +
+eventName
– The name of the event.string | symbol
listener
(args) any []#
args
listener(args) =>
prependListener(eventName, listener) =>
prependOnceListener
(eventName, listener) – Adds a one-timelistener
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.
+ +```js +server.prependOnceListener('connection', stream => { + console.log('Ah, we have our first user!') +}) +``` + +Returns a reference to the `EventEmitter`, so that calls can be chained. + +
+eventName
– The name of the event.string | symbol
listener
(args) any []#
args
listener(args) =>
prependOnceListener(eventName, listener) =>
rawListeners
(eventName) – Returns a copy of the array of listeners for the event named eventName
,
+including any wrappers (such as those created by .once()
).
+ +```js +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') +``` + +
+eventName
string | symbol
rawListeners(eventName) =>
removeAllListeners
(event) – 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. + +
+event
string | symbol
removeAllListeners(event) =>
removeListener
(eventName, listener) – Removes the specified listener
from the listener array for the event namedeventName
.
+ +```js +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. + +```js +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 indices 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: + +```js +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. + +
+eventName
string | symbol
listener
(args) any []#
args
listener(args) =>
removeListener(eventName, listener) =>
setMaxListeners
(n) – By default EventEmitter
s 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 toInfinity
(or 0
) to indicate an unlimited number of listeners.
+ +Returns a reference to the `EventEmitter`, so that calls can be chained. + +
+n
number
setMaxListeners(n) =>
write(buffer, cb) =>
str
string
encoding
cb
(err) #
err
null
| Error
cb(err) =>
write(str, encoding, cb) =>
X509CheckOptions
ZlibOptions
AcceptedPlugin
Plugin | PluginCreator<any> | OldPlugin<any> | TransformCallback | {
} | Processor
AddonHook
string | AddonHookFunction
AddonHookFunction
AliasOptions
– Specifies an Object
, or an Array
of Object
,
+which defines aliases used to replace values in import
or require
statements.
+With either format, the order of the entries is important,
+in that the first defined rules are applied first.readonly Alias [] | {}
+ +This is passed to \@rollup/plugin-alias as the "entries" field +https://github.com/rollup/plugins/tree/master/packages/alias#entries + +
+AmdOptions
{
} | {
} | {
} & {
}
AnyNode
AnymatchFn
AnymatchPattern
string | RegExp | AnymatchFn
AppType
– spa: include SPA fallback middleware and configure sirv with single: true
in preview"spa"
| "mpa"
| "custom"
+ +mpa: only include non-SPA HTML middlewares + +custom: don't include HTML middlewares + +
+ArrayBufferView
TypedArray | DataView
AtRuleProcessor
BinaryLike
string | NodeJS.ArrayBufferView
BufferEncoding
"ascii"
| "utf8"
| "utf-8"
| "utf16le"
| "ucs2"
| "ucs-2"
| "base64"
| "base64url"
| "latin1"
| "binary"
| "hex"
ChangeEvent
"create"
| "update"
| "delete"
Charset
"ascii"
| "utf8"
ChildNode
AtRule | Rule | Declaration | Comment
ChildProps
CommentProcessor
CorsOrigin
boolean | string | RegExp | string | RegExp []
DeclarationProcessor
DecodedSourceMapOrMissing
{
} | ExistingDecodedSourceMap
DepOptimizationOptions
string | string []
+
+If neither of these fit your needs, you can specify custom entries using
+this option - the value should be a fast-glob pattern or array of patterns
+(https://github.com/mrmlnc/fast-glob#basic-syntax) that are relative from
+vite project root. This will overwrite default entries inference.
+
+ boolean#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L603 entries
– By default, Vite will crawl your index.html
to detect dependencies that
+need to be pre-bundled. If build.rollupOptions.input
is specified, Vite
+will crawl those entry points instead.#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L608 force
– Force dep pre-optimization regardless of whether deps have changed.
DocumentProcessor
Drop
"console"
| "debugger"
ECMA
5
| 2015
| 2016
| 2017
| 2018
| 2019
| 2020
EmitAsset
EmitChunk
EmitFile
EmittedFile
ErrorCallback
(err, req, res, target) => # (err, req, res, target)
void
ErrorHandleFunction
(err, req, res, next) => # (err, req, res, next)
void
ExportsData
{
}
ExternalOption
string | RegExp [] | string | RegExp |
Format
"iife"
| "cjs"
| "esm"
GeneratedCodePreset
"es5"
| "es2015"
GetInterop
GetManualChunk
(id, api) => # (id, api)
string |
null
| void
GetModuleInfo
string (moduleId) => # (moduleId)
#
moduleId
ModuleInfo |
null
GlobalsOption
{} |
HMRPayload
HandleFunction
HasModuleSideEffects
Helpers
{
} & Postcss
ImportKind
"entry-point"
| "import-statement"
| "require-call"
| "dynamic-import"
| "require-resolve"
| "import-rule"
| "url-token"
IndexHtmlTransform
}
IndexHtmlTransformHook
string (html, ctx) => # (html, ctx)
#
html
IndexHtmlTransformResult | void | Promise<IndexHtmlTransformResult | void>
IndexHtmlTransformResult
string | HtmlTagDescriptor [] | {
}
InferCustomEventPayload
T extends keyof CustomEventMap ? CustomEventMap [T] : any
InputOption
string | string [] | {}
InternalModuleFormat
"amd"
| "cjs"
| "es"
| "iife"
| "system"
| "umd"
InteropType
boolean | "auto"
| "esModule"
| "default"
| "defaultOnly"
IsExternal
IsPureModule
KeyFormat
"pem"
| "der"
KeyObjectType
"secret"
| "public"
| "private"
KeyType
"rsa"
| "rsa-pss"
| "dsa"
| "ec"
| "ed25519"
| "ed448"
| "x25519"
| "x448"
LibraryFormats
"es"
| "cjs"
| "umd"
| "iife"
List
{
+
+```js
+Once (root, { list }) {
+ list.comma('black, linear-gradient(white, black)')
+ //=> ['black', 'linear-gradient(white, black)']
+}
+```
+
+ string comma(str) => #
comma
(str) – Safely splits comma-separated values (such as those for transition-*
+and background
properties).
#
str
– Comma-separated values.string []
space
(str) – Safely splits space-separated values (such as those for background
,
+border-radius
, and other shorthand properties).
+ +```js +Once (root, { list }) { + list.space('1px calc(10% + 1px)') //=> ['1px', 'calc(10% + 1px)'] +} +``` + +
+str
– Space-separated values.string
space(str) =>
split
(string, separators, last) – Safely splits values.
+ +```js +Once (root, { list }) { + list.split('1px calc(10% + 1px)', [' ', '\n', '\t']) //=> ['1px', 'calc(10% + 1px)'] +} +``` + +
+string
– separated values.string
separators
– array of separators.string []
last
– boolean indicator.boolean
split(string, separators, last) =>
LoadHook
(this, id) => # (this, id)
Promise<LoadResult> | LoadResult
LoadResult
SourceDescription | string | null
| void
Loader
"js"
| "jsx"
| "ts"
| "tsx"
| "css"
| "json"
| "text"
| "base64"
| "file"
| "dataurl"
| "binary"
| "copy"
| "default"
LogLevel
LogType | "silent"
LogLevel
"verbose"
| "debug"
| "info"
| "warning"
| "error"
| "silent"
LogType
"error"
| "warn"
| "info"
LookupFunction
(hostname, options, callback) =>
ManualChunksOption
{} | GetManualChunk
Matcher
ModuleFormat
InternalModuleFormat | "commonjs"
| "esm"
| "module"
| "systemjs"
ModuleParsedHook
(this, info) => # (this, info)
Promise<void> | void
ModuleSideEffectsOption
boolean | "no-external"
| string [] | HasModuleSideEffects
NextHandleFunction
(req, res, next) => # (req, res, next)
void
NormalizedAmdOptions
{
} | {
} & {
}
OptionsPaths
Record<string, string> |
OutgoingHttpHeader
number | string | string []
PackageCache
– Cache for package.json resolution and package.json contentsMap<string, PackageData>
Platform
"browser"
| "node"
| "neutral"
PluginOption
Plugin_2 | false
| null
| undefined | PluginOption [] | Promise<Plugin_2 | false
| null
| undefined | PluginOption []>
PreserveEntrySignaturesOption
false
| "strict"
| "allow-extension"
| "exports-only"
PreviewServerHook
ProxyTarget
ProxyTargetUrl
string | Partial<url.Url>
PureModulesOption
boolean | string [] | IsPureModule
RawData
– Data represents the raw message payload received over the WebSocket.RenderBuiltAssetUrl
RenderChunkHook
RequestListener
ResolveAssetUrlHook
# (this, { assetFileName, chunkId, format, moduleId, relativeAssetPath })
(this, { assetFileName, chunkId, format, moduleId, relativeAssetPath }) =>
null
| voidResolveDynamicImportHook
(this, specifier, importer) => # (this, specifier, importer)
Promise<ResolveIdResult> | ResolveIdResult
ResolveFileUrlHook
# (this, { assetReferenceId, chunkId, chunkReferenceId, fileName, format, moduleId, referenceId, relativePath })
(this, { assetReferenceId, chunkId, chunkReferenceId, fileName, format, moduleId, referenceId, relativePath }) =>
null
| voidResolveFn
ResolveIdHook
ResolveIdResult
string | false
| null
| void | PartialResolvedId
ResolveImportMetaHook
# (this, prop, { chunkId, format, moduleId })
(this, prop, { chunkId, format, moduleId }) =>
null
| voidResolvedUrl
[ named-tuple-member, named-tuple-member, named-tuple-member ]
RootProcessor
RuleProcessor
SSRFormat
"esm"
| "cjs"
SSRTarget
"node"
| "webworker"
SecureVersion
"TLSv1.3"
| "TLSv1.2"
| "TLSv1.1"
| "TLSv1"
ServerHandle
ServerHook
() =>
ServerOptions
ShouldTransformCachedModuleHook
# (this, { ast, code, id, meta, moduleSideEffects, resolvedSources, syntheticNamedExports })
(this, { ast, code, id, meta, moduleSideEffects, resolvedSources, syntheticNamedExports }) =>
SimpleHandleFunction
SocketConnectOpts
SocketReadyState
"opening"
| "open"
| "readOnly"
| "writeOnly"
| "closed"
SourceMap
toJSON() => #
toJSON
()
SourceMapInput
ExistingRawSourceMap | string | null
| {
}
SourceMapSegment
[ number ] | [ number, number, number, number ] | [ number, number, number, number, number ]
SourcemapPathTransformOption
TransformHook
string string (this, code, id) => # (this, code, id)
#
this
#
code
#
id
Promise<TransformResult> | TransformResult
TransformResult
string | null
| void | Partial<SourceDescription>
TreeshakingPreset
"smallest"
| "safest"
| "recommended"
TypedArray
Uint8Array | Uint8ClampedArray | Uint16Array | Uint32Array | Int8Array | Int16Array | Int32Array | BigUint64Array | BigInt64Array | Float32Array | Float64Array
WarningHandler
WarningHandlerWithDefault
(warning, defaultHandler) => # (warning, defaultHandler)
void
WatchChangeHook
# (this, id, { event })
(this, id, { event }) =>
WebSocketCustomListener
WithImplicitCoercion
T | {
Buffer
WebSocket
typeof WebSocketAlias
WebSocketAlias
typeof WebSocket_2
Options
noForce
= false
boolean
noOpen
= false
boolean
quiet
= false
boolean
responses
= {}
Record<string, {
root
= '.'
string
virtual
= {}
Record<string, any>
viteOptions
= {}
Partial<InlineConfig>
VirtualModules
ViteServer
– ViteServer return object.
VirtualModule
string | object
virtualPlugin
any
invalidateVirtualModule
(server, id) open
(options) – Open a file in Vite.
open(options) =>
#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L2152comments
boolean | RegExp |
}
"all"
|"some"
|# (node, { col, line, pos, type, value })
#
node
any
#
comment
{
#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L2164col
number
#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L2163line
number
#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L2162pos
number
#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L2161type
"comment1"
|"comment2"
|"comment3"
|"comment4"
#
src/.fastpm/-/vite@3.0.4/dist/node/index.d.ts#L2160value
string
(node, { col, line, pos, type, value }) =>
boolean