From d16fe63454118bbe885b6f35ed0824e907d26837 Mon Sep 17 00:00:00 2001
From: FoxxMD Creates a new {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 The total size of the v15.7.0, v14.18.0 The content-type of the v15.7.0, v14.18.0 Returns a promise that fulfills with an ArrayBuffer containing a copy of
+the v15.7.0, v14.18.0 Creates and returns a new The starting index. The ending index. The content-type for the new v15.7.0, v14.18.0 Returns a new v16.7.0 Generated using TypeDoc Instances of the v0.1.104 NOTE: According to the documentation: Instances of the NOTE: According to the documentation: Instances of the This symbol shall be used to install a listener for only monitoring Installing a listener using this symbol does not change the behavior once an
+ Sets or gets the default captureRejection value for all emitters. The current input data being processed by node. This can be used when collecting input from a TTY stream to retrieve the
+current value that has been processed thus far, prior to the Be aware that modifying the value during the instance runtime may have
+unintended consequences if If not using a TTY stream for input, use the One possible use case would be as follows: v0.1.98 The cursor position relative to This will track where the current cursor lands in the input string, when
+reading input from a TTY stream. The position of cursor determines the
+portion of the input string that will be modified as input is processed,
+as well as the column where the terminal caret will be rendered. v0.1.98 Creates a This method is intentionally generic and works with the web platform EventTarget interface, which has no special The special handling of the An v11.13.0, v10.16.0 Returns an An The name of the event being listened for that iterates v13.6.0, v12.16.0 A class method that returns the number of listeners for the given The emitter to query The event name v0.9.12 Since v3.2.0 - Use Returns a copy of the array of listeners for the event named For For v15.2.0, v14.17.0 Returns the currently set max amount of listeners. For For v18.17.0 A non-negative number. The maximum number of listeners per v15.4.0 Listens once to the Listening to the This API allows safely using Returns a disposable so that it may be unsubscribed from more easily. Disposable that removes the v18.18.0 Removes the specified Once an event is emitted, all listeners attached to it at the
+time of emitting are called in order. This implies that any 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 When a single function has been added as a handler multiple times for a single
+event (as in the example below), Returns a reference to the v0.1.26 Alias for v10.0.0 Removes all listeners, or those of the specified It is bad practice to remove listeners added elsewhere in the code,
+particularly when the Returns a reference to the v0.1.26 By default Returns a reference to the v0.3.5 Returns the current max listener value for the v1.0.0 Returns a copy of the array of listeners for the event named v0.1.26 Returns a copy of the array of listeners for the event named v9.4.0 Returns the number of listeners listening to the event named If The name of the event being listened for The event handler function v3.2.0 Returns an array listing the events for which the emitter has registered
+listeners. The values in the array are strings or v6.0.0 The When called, If the If v0.1.98 The When called, If the The Example usage: Using an If this method is invoked as it's util.promisify()ed version, it returns a
+Promise that fulfills with the answer. If the question is canceled using
+an A statement or query to write to A callback function that is invoked with the user's input in response to the v0.3.3 The Calling v0.1.98 The If When called, If the The v0.1.98 events.EventEmitter Synchronously calls each of the listeners registered for the event named Returns v0.1.26 Adds the Returns a reference to the By default, event listeners are invoked in the order they are added. The The name of the event. The callback function v0.1.101 Adds a one-time Returns a reference to the By default, event listeners are invoked in the order they are added. The The name of the event. The callback function v0.3.0 Adds the Returns a reference to the The name of the event. The callback function v6.0.0 Adds a one-time Returns a reference to the The name of the event. The callback function v6.0.0 Generated using TypeDoc Node.js uses a Most applications should consider using the new v11.6.0 For asymmetric keys, this property represents the type of the key. Supported key
+types are: This property is v11.6.0 For asymmetric keys, this property represents the size of the embedded key in
+bytes. This property is This property exists only on asymmetric keys. Depending on the type of the key,
+this object contains information about the key. None of the information obtained
+through this property can be used to uniquely identify a key or to compromise
+the security of the key. For RSA-PSS keys, if the key material contains a Other key details might be exposed via this API using additional attributes. v15.7.0 For secret keys, this property represents the size of the key in bytes. This
+property is v11.6.0 Depending on the type of this v11.6.0 Example: Converting a v15.0.0 For symmetric keys, the following encoding options can be used: 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 it will be an object. When JWK encoding format was selected, all other encoding options are
+ignored. PKCS#1, SEC1, and PKCS#8 type keys can be encrypted by using a combination of
+the v11.6.0 Returns v16.15.0 Generated using TypeDoc Instances of the This implementation matches browser v10.5.0 This symbol shall be used to install a listener for only monitoring Installing a listener using this symbol does not change the behavior once an
+ Sets or gets the default captureRejection value for all emitters. Creates a This method is intentionally generic and works with the web platform EventTarget interface, which has no special The special handling of the An v11.13.0, v10.16.0 Returns an An The name of the event being listened for that iterates v13.6.0, v12.16.0 A class method that returns the number of listeners for the given The emitter to query The event name v0.9.12 Since v3.2.0 - Use Returns a copy of the array of listeners for the event named For For v15.2.0, v14.17.0 Returns the currently set max amount of listeners. For For v18.17.0 A non-negative number. The maximum number of listeners per v15.4.0 Listens once to the Listening to the This API allows safely using Returns a disposable so that it may be unsubscribed from more easily. Disposable that removes the v18.18.0 Removes all listeners, or those of the specified It is bad practice to remove listeners added elsewhere in the code,
+particularly when the Returns a reference to the v0.1.26 By default Returns a reference to the v0.3.5 Returns the current max listener value for the v1.0.0 Returns a copy of the array of listeners for the event named v0.1.26 Returns a copy of the array of listeners for the event named v9.4.0 Returns the number of listeners listening to the event named If The name of the event being listened for The event handler function v3.2.0 Returns an array listing the events for which the emitter has registered
+listeners. The values in the array are strings or v6.0.0 Sends a JavaScript value to the receiving side of this channel. In particular, the significant differences to If The message object is cloned immediately, and can be modified after
+posting without having side effects. For more information on the serialization and deserialization mechanisms
+behind this API, see the v10.5.0 Opposite of If listeners are attached or removed using v10.5.0 Calling If listeners are attached or removed using v10.5.0 Starts receiving messages on this This method exists for parity with the Web v10.5.0 Alias for v0.1.26 Synchronously calls each of the listeners registered for the event named Returns v0.1.26 Adds the Returns a reference to the By default, event listeners are invoked in the order they are added. The The name of the event. The callback function v0.1.101 Adds a one-time Returns a reference to the By default, event listeners are invoked in the order they are added. The The name of the event. The callback function v0.3.0 Adds the Returns a reference to the The name of the event. The callback function v6.0.0 Adds a one-time Returns a reference to the The name of the event. The callback function v6.0.0 Removes the specified Once an event is emitted, all listeners attached to it at the
+time of emitting are called in order. This implies that any 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 When a single function has been added as a handler multiple times for a single
+event (as in the example below), Returns a reference to the v0.1.26 Alias for v10.0.0 Generated using TypeDoc Instances of v0.1.93 This symbol shall be used to install a listener for only monitoring Installing a listener using this symbol does not change the behavior once an
+ Sets or gets the default captureRejection value for all emitters. The number of bytes that have been read so far. v6.4.0 The path to the file the stream is reading from as specified in the first
+argument to v0.1.93 This property is v11.2.0, v10.16.0 Returns whether the stream was destroyed or errored before emitting v16.8.0 Is v11.4.0 Returns whether v16.7.0, v14.18.0 Getter for the property v12.7.0 Becomes v12.9.0 This property reflects the current state of a v9.4.0 Returns the value of v9.3.0 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 v9.4.0 Getter for the property v12.3.0 Is v8.0.0 Is true after 'close' has been emitted. v18.0.0 Returns error if the stream has been destroyed with an error. v18.0.0 Creates a This method is intentionally generic and works with the web platform EventTarget interface, which has no special The special handling of the An v11.13.0, v10.16.0 Returns an An The name of the event being listened for that iterates v13.6.0, v12.16.0 A class method that returns the number of listeners for the given The emitter to query The event name v0.9.12 Since v3.2.0 - Use Returns a copy of the array of listeners for the event named For For v15.2.0, v14.17.0 Returns the currently set max amount of listeners. For For v18.17.0 A non-negative number. The maximum number of listeners per v15.4.0 Listens once to the Listening to the This API allows safely using Returns a disposable so that it may be unsubscribed from more easily. Disposable that removes the v18.18.0 Alias for v10.0.0 Removes all listeners, or those of the specified It is bad practice to remove listeners added elsewhere in the code,
+particularly when the Returns a reference to the v0.1.26 By default Returns a reference to the v0.3.5 Returns the current max listener value for the v1.0.0 Returns a copy of the array of listeners for the event named v0.1.26 Returns a copy of the array of listeners for the event named v9.4.0 Returns the number of listeners listening to the event named If The name of the event being listened for The event handler function v3.2.0 Returns an array listing the events for which the emitter has registered
+listeners. The values in the array are strings or v6.0.0 events.EventEmitter Adds the Returns a reference to the By default, event listeners are invoked in the order they are added. The The name of the event. The callback function v0.1.101 Adds a one-time Returns a reference to the By default, event listeners are invoked in the order they are added. The The name of the event. The callback function v0.3.0 Adds the Returns a reference to the The name of the event. The callback function v6.0.0 Adds a one-time Returns a reference to the The name of the event. The callback function v6.0.0 A utility method for creating Readable Streams out of iterators. A utility method for creating a v17.0.0 Returns whether the stream has been read from or cancelled. v16.8.0 A utility method for creating a web v17.0.0 The The optional If the The The Each call to Therefore to read a file's whole contents from a A If the Calling read after the Optional argument to specify how much data to read. v0.9.4 The By default, no encoding is assigned and stream data will be returned as The The encoding to use. v0.9.4 The The v0.9.4 The The The v0.9.4 The v0.11.14 The If the If the Optional specific stream to unpipe v0.9.4 Passing The The Developers using Unlike push, Chunk of data to unshift onto the read queue. For streams not operating in object mode, Encoding of string chunks. Must be a valid v0.9.11 Prior to Node.js 0.10, streams did not implement the entire When using an older Node.js library that emits It will rarely be necessary to use An "old style" readable stream v0.9.4 The iterator created by this method gives users the option to cancel the destruction
+of the stream if the When set to v16.3.0 This method allows mapping over the stream. The fn function will be called for every chunk in the stream.
+If the fn function returns a promise - that promise will be a function to map over every chunk in the stream. Async or not. a stream mapped with the function fn. v17.4.0, v16.14.0 This method allows filtering the stream. For each chunk in the stream the fn function will be called
+and if it returns a truthy value, the chunk will be passed to the result stream.
+If the fn function returns a promise - that promise will be a function to filter chunks from the stream. Async or not. a stream filtered with the predicate fn. v17.4.0, v16.14.0 This method allows iterating a stream. For each chunk in the stream the fn function will be called.
+If the fn function returns a promise - that promise will be This method is different from This method is different from listening to the a function to call on each chunk of the stream. Async or not. a promise for when the stream has finished. v17.5.0 This method allows easily obtaining the contents of a stream. As this method reads the entire stream into memory, it negates the benefits of streams. It's intended
+for interoperability and convenience, not as the primary way to consume streams. a promise containing an array with the contents of the stream. v17.5.0 This method is similar to a function to call on each chunk of the stream. Async or not. a promise evaluating to v17.5.0 This method is similar to a function to call on each chunk of the stream. Async or not. a promise evaluating to the first chunk for which fn evaluated with a truthy value,
+or v17.5.0 This method is similar to a function to call on each chunk of the stream. Async or not. a promise evaluating to v17.5.0 This method returns a new stream by applying the given callback to each chunk of the stream
+and then flattening the result. It is possible to return a stream or another iterable or async iterable from fn and the result streams
+will be merged (flattened) into the returned stream. a function to map over every chunk in the stream. May be async. May be a stream or generator. a stream flat-mapped with the function fn. v17.5.0 This method returns a new stream with the first limit chunks dropped from the start. the number of chunks to drop from the readable. a stream with limit chunks dropped from the start. v17.5.0 This method returns a new stream with the first limit chunks. the number of chunks to take from the readable. a stream with limit chunks taken. v17.5.0 This method returns a new stream with chunks of the underlying stream paired with a counter
+in the form a stream of indexed pairs. v17.5.0 This method calls fn on each chunk of the stream in order, passing it the result from the calculation
+on the previous element. It returns a promise for the final value of the reduction. If no initial value is supplied the first chunk of the stream is used as the initial value.
+If the stream is empty, the promise is rejected with a The reducer function iterates the stream element-by-element which means that there is no concurrency parameter
+or parallelism. To perform a reduce concurrently, you can extract the async function to a reducer function to call over every chunk in the stream. Async or not. the initial value to use in the reduction. a promise for the final value of the reduction. v17.5.0 Destroy the stream. Optionally emit an Once Implementors should not override this method, but instead implement Error which will be passed as payload in v8.0.0 Synchronously calls each of the listeners registered for the event named Returns v0.1.26 Removes the specified Once an event is emitted, all listeners attached to it at the
+time of emitting are called in order. This implies that any 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 When a single function has been added as a handler multiple times for a single
+event (as in the example below), Returns a reference to the v0.1.26 Generated using TypeDoc v0.9.4 This symbol shall be used to install a listener for only monitoring Installing a listener using this symbol does not change the behavior once an
+ Sets or gets the default captureRejection value for all emitters. Returns whether the stream was destroyed or errored before emitting v16.8.0 Is v11.4.0 Returns whether v16.7.0, v14.18.0 Getter for the property v12.7.0 Becomes v12.9.0 This property reflects the current state of a v9.4.0 Returns the value of v9.3.0 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 v9.4.0 Getter for the property v12.3.0 Is v8.0.0 Is true after 'close' has been emitted. v18.0.0 Returns error if the stream has been destroyed with an error. v18.0.0 Creates a This method is intentionally generic and works with the web platform EventTarget interface, which has no special The special handling of the An v11.13.0, v10.16.0 Returns an An The name of the event being listened for that iterates v13.6.0, v12.16.0 A class method that returns the number of listeners for the given The emitter to query The event name v0.9.12 Since v3.2.0 - Use Returns a copy of the array of listeners for the event named For For v15.2.0, v14.17.0 Returns the currently set max amount of listeners. For For v18.17.0 A non-negative number. The maximum number of listeners per v15.4.0 Listens once to the Listening to the This API allows safely using Returns a disposable so that it may be unsubscribed from more easily. Disposable that removes the v18.18.0 Alias for v10.0.0 Removes all listeners, or those of the specified It is bad practice to remove listeners added elsewhere in the code,
+particularly when the Returns a reference to the v0.1.26 By default Returns a reference to the v0.3.5 Returns the current max listener value for the v1.0.0 Returns a copy of the array of listeners for the event named v0.1.26 Returns a copy of the array of listeners for the event named v9.4.0 Returns the number of listeners listening to the event named If The name of the event being listened for The event handler function v3.2.0 Returns an array listing the events for which the emitter has registered
+listeners. The values in the array are strings or v6.0.0 A utility method for creating Readable Streams out of iterators. A utility method for creating a v17.0.0 Returns whether the stream has been read from or cancelled. v16.8.0 A utility method for creating a web v17.0.0 The The optional If the The The Each call to Therefore to read a file's whole contents from a A If the Calling read after the Optional argument to specify how much data to read. v0.9.4 The By default, no encoding is assigned and stream data will be returned as The The encoding to use. v0.9.4 The The v0.9.4 The The The v0.9.4 The v0.11.14 The If the If the Optional specific stream to unpipe v0.9.4 Passing The The Developers using Unlike push, Chunk of data to unshift onto the read queue. For streams not operating in object mode, Encoding of string chunks. Must be a valid v0.9.11 Prior to Node.js 0.10, streams did not implement the entire When using an older Node.js library that emits It will rarely be necessary to use An "old style" readable stream v0.9.4 The iterator created by this method gives users the option to cancel the destruction
+of the stream if the When set to v16.3.0 This method allows mapping over the stream. The fn function will be called for every chunk in the stream.
+If the fn function returns a promise - that promise will be a function to map over every chunk in the stream. Async or not. a stream mapped with the function fn. v17.4.0, v16.14.0 This method allows filtering the stream. For each chunk in the stream the fn function will be called
+and if it returns a truthy value, the chunk will be passed to the result stream.
+If the fn function returns a promise - that promise will be a function to filter chunks from the stream. Async or not. a stream filtered with the predicate fn. v17.4.0, v16.14.0 This method allows iterating a stream. For each chunk in the stream the fn function will be called.
+If the fn function returns a promise - that promise will be This method is different from This method is different from listening to the a function to call on each chunk of the stream. Async or not. a promise for when the stream has finished. v17.5.0 This method allows easily obtaining the contents of a stream. As this method reads the entire stream into memory, it negates the benefits of streams. It's intended
+for interoperability and convenience, not as the primary way to consume streams. a promise containing an array with the contents of the stream. v17.5.0 This method is similar to a function to call on each chunk of the stream. Async or not. a promise evaluating to v17.5.0 This method is similar to a function to call on each chunk of the stream. Async or not. a promise evaluating to the first chunk for which fn evaluated with a truthy value,
+or v17.5.0 This method is similar to a function to call on each chunk of the stream. Async or not. a promise evaluating to v17.5.0 This method returns a new stream by applying the given callback to each chunk of the stream
+and then flattening the result. It is possible to return a stream or another iterable or async iterable from fn and the result streams
+will be merged (flattened) into the returned stream. a function to map over every chunk in the stream. May be async. May be a stream or generator. a stream flat-mapped with the function fn. v17.5.0 This method returns a new stream with the first limit chunks dropped from the start. the number of chunks to drop from the readable. a stream with limit chunks dropped from the start. v17.5.0 This method returns a new stream with the first limit chunks. the number of chunks to take from the readable. a stream with limit chunks taken. v17.5.0 This method returns a new stream with chunks of the underlying stream paired with a counter
+in the form a stream of indexed pairs. v17.5.0 This method calls fn on each chunk of the stream in order, passing it the result from the calculation
+on the previous element. It returns a promise for the final value of the reduction. If no initial value is supplied the first chunk of the stream is used as the initial value.
+If the stream is empty, the promise is rejected with a The reducer function iterates the stream element-by-element which means that there is no concurrency parameter
+or parallelism. To perform a reduce concurrently, you can extract the async function to a reducer function to call over every chunk in the stream. Async or not. the initial value to use in the reduction. a promise for the final value of the reduction. v17.5.0 Destroy the stream. Optionally emit an Once Implementors should not override this method, but instead implement Error which will be passed as payload in v8.0.0 Event emitter
+The defined events on documents including: Synchronously calls each of the listeners registered for the event named Returns v0.1.26 Adds the Returns a reference to the By default, event listeners are invoked in the order they are added. The The name of the event. The callback function v0.1.101 Adds a one-time Returns a reference to the By default, event listeners are invoked in the order they are added. The The name of the event. The callback function v0.3.0 Adds the Returns a reference to the The name of the event. The callback function v6.0.0 Adds a one-time Returns a reference to the The name of the event. The callback function v6.0.0 Removes the specified Once an event is emitted, all listeners attached to it at the
+time of emitting are called in order. This implies that any 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 When a single function has been added as a handler multiple times for a single
+event (as in the example below), Returns a reference to the v0.1.26 Generated using TypeDoc A Objects returned from stat, lstat and fstat and
+their synchronous counterparts are of this type.
+If v0.1.21 Generated using TypeDoc The All It supports the following option: v0.1.26 This symbol shall be used to install a listener for only monitoring Installing a listener using this symbol does not change the behavior once an
+ Sets or gets the default captureRejection value for all emitters. Creates a This method is intentionally generic and works with the web platform EventTarget interface, which has no special The special handling of the An v11.13.0, v10.16.0 Returns an An The name of the event being listened for that iterates v13.6.0, v12.16.0 A class method that returns the number of listeners for the given The emitter to query The event name v0.9.12 Since v3.2.0 - Use Returns a copy of the array of listeners for the event named For For v15.2.0, v14.17.0 Returns the currently set max amount of listeners. For For v18.17.0 A non-negative number. The maximum number of listeners per v15.4.0 Listens once to the Listening to the This API allows safely using Returns a disposable so that it may be unsubscribed from more easily. Disposable that removes the v18.18.0 Alias for v0.1.26 Adds the Returns a reference to the By default, event listeners are invoked in the order they are added. The The name of the event. The callback function v0.1.101 Adds a one-time Returns a reference to the By default, event listeners are invoked in the order they are added. The The name of the event. The callback function v0.3.0 Removes the specified Once an event is emitted, all listeners attached to it at the
+time of emitting are called in order. This implies that any 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 When a single function has been added as a handler multiple times for a single
+event (as in the example below), Returns a reference to the v0.1.26 Alias for v10.0.0 Removes all listeners, or those of the specified It is bad practice to remove listeners added elsewhere in the code,
+particularly when the Returns a reference to the v0.1.26 By default Returns a reference to the v0.3.5 Returns the current max listener value for the v1.0.0 Returns a copy of the array of listeners for the event named v0.1.26 Returns a copy of the array of listeners for the event named v9.4.0 Synchronously calls each of the listeners registered for the event named Returns v0.1.26 Returns the number of listeners listening to the event named If The name of the event being listened for The event handler function v3.2.0 Adds the Returns a reference to the The name of the event. The callback function v6.0.0 Adds a one-time Returns a reference to the The name of the event. The callback function v6.0.0 Returns an array listing the events for which the emitter has registered
+listeners. The values in the array are strings or v6.0.0 Generated using TypeDoc v0.9.4 This symbol shall be used to install a listener for only monitoring Installing a listener using this symbol does not change the behavior once an
+ Sets or gets the default captureRejection value for all emitters. Is v11.4.0 Is v12.9.0 Is set to v12.6.0 Return the value of v9.3.0 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 v9.4.0 Getter for the property v12.3.0 Number of times v13.2.0, v12.16.0 Is v8.0.0 Is true after 'close' has been emitted. v18.0.0 Returns error if the stream has been destroyed with an error. v18.0.0 Is v15.2.0, v14.17.0 Creates a This method is intentionally generic and works with the web platform EventTarget interface, which has no special The special handling of the An v11.13.0, v10.16.0 Returns an An The name of the event being listened for that iterates v13.6.0, v12.16.0 A class method that returns the number of listeners for the given The emitter to query The event name v0.9.12 Since v3.2.0 - Use Returns a copy of the array of listeners for the event named For For v15.2.0, v14.17.0 Returns the currently set max amount of listeners. For For v18.17.0 A non-negative number. The maximum number of listeners per v15.4.0 Listens once to the Listening to the This API allows safely using Returns a disposable so that it may be unsubscribed from more easily. Disposable that removes the v18.18.0 Alias for v10.0.0 Removes all listeners, or those of the specified It is bad practice to remove listeners added elsewhere in the code,
+particularly when the Returns a reference to the v0.1.26 By default Returns a reference to the v0.3.5 Returns the current max listener value for the v1.0.0 Returns a copy of the array of listeners for the event named v0.1.26 Returns a copy of the array of listeners for the event named v9.4.0 Returns the number of listeners listening to the event named If The name of the event being listened for The event handler function v3.2.0 Returns an array listing the events for which the emitter has registered
+listeners. The values in the array are strings or v6.0.0 A utility method for creating a v17.0.0 A utility method for creating a web v17.0.0 The The return value is While a stream is not draining, calls to Writing data while the stream is not draining is particularly
+problematic for a If the data to be written can be generated or fetched on demand, it is
+recommended to encapsulate the logic into a A Optional data to write. For streams not operating in object mode, Callback for when this chunk of data is flushed. v0.9.4 The The new default encoding v0.11.15 Calling the Calling the write method after calling end will raise an error. v0.9.4 The The primary intent of See also: v0.11.2 The When using If the See also: v0.11.2 Destroy the stream. Optionally emit an Once Implementors should not override this method,
+but instead implement Optional, an error to emit with v8.0.0 Event emitter
+The defined events on documents including: Synchronously calls each of the listeners registered for the event named Returns v0.1.26 Adds the Returns a reference to the By default, event listeners are invoked in the order they are added. The The name of the event. The callback function v0.1.101 Adds a one-time Returns a reference to the By default, event listeners are invoked in the order they are added. The The name of the event. The callback function v0.3.0 Adds the Returns a reference to the The name of the event. The callback function v6.0.0 Adds a one-time Returns a reference to the The name of the event. The callback function v6.0.0 Removes the specified Once an event is emitted, all listeners attached to it at the
+time of emitting are called in order. This implies that any 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 When a single function has been added as a handler multiple times for a single
+event (as in the example below), Returns a reference to the v0.1.26 Generated using TypeDoc Instances of v0.1.93 This symbol shall be used to install a listener for only monitoring Installing a listener using this symbol does not change the behavior once an
+ Sets or gets the default captureRejection value for all emitters. The number of bytes written so far. Does not include data that is still queued
+for writing. v0.4.7 The path to the file the stream is writing to as specified in the first
+argument to createWriteStream. If v0.1.93 This property is v11.2.0 Is v11.4.0 Is v12.9.0 Is set to v12.6.0 Return the value of v9.3.0 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 v9.4.0 Getter for the property v12.3.0 Number of times v13.2.0, v12.16.0 Is v8.0.0 Is true after 'close' has been emitted. v18.0.0 Returns error if the stream has been destroyed with an error. v18.0.0 Is v15.2.0, v14.17.0 Creates a This method is intentionally generic and works with the web platform EventTarget interface, which has no special The special handling of the An v11.13.0, v10.16.0 Returns an An The name of the event being listened for that iterates v13.6.0, v12.16.0 A class method that returns the number of listeners for the given The emitter to query The event name v0.9.12 Since v3.2.0 - Use Returns a copy of the array of listeners for the event named For For v15.2.0, v14.17.0 Returns the currently set max amount of listeners. For For v18.17.0 A non-negative number. The maximum number of listeners per v15.4.0 Listens once to the Listening to the This API allows safely using Returns a disposable so that it may be unsubscribed from more easily. Disposable that removes the v18.18.0 Alias for v10.0.0 Removes all listeners, or those of the specified It is bad practice to remove listeners added elsewhere in the code,
+particularly when the Returns a reference to the v0.1.26 By default Returns a reference to the v0.3.5 Returns the current max listener value for the v1.0.0 Returns a copy of the array of listeners for the event named v0.1.26 Returns a copy of the array of listeners for the event named v9.4.0 Returns the number of listeners listening to the event named If The name of the event being listened for The event handler function v3.2.0 Returns an array listing the events for which the emitter has registered
+listeners. The values in the array are strings or v6.0.0 Closes v0.9.4 events.EventEmitter Adds the Returns a reference to the By default, event listeners are invoked in the order they are added. The The name of the event. The callback function v0.1.101 Adds a one-time Returns a reference to the By default, event listeners are invoked in the order they are added. The The name of the event. The callback function v0.3.0 Adds the Returns a reference to the The name of the event. The callback function v6.0.0 Adds a one-time Returns a reference to the The name of the event. The callback function v6.0.0 A utility method for creating a v17.0.0 A utility method for creating a web v17.0.0 The The return value is While a stream is not draining, calls to Writing data while the stream is not draining is particularly
+problematic for a If the data to be written can be generated or fetched on demand, it is
+recommended to encapsulate the logic into a A Optional data to write. For streams not operating in object mode, Callback for when this chunk of data is flushed. v0.9.4 The The new default encoding v0.11.15 Calling the Calling the write method after calling end will raise an error. v0.9.4 The The primary intent of See also: v0.11.2 The When using If the See also: v0.11.2 Destroy the stream. Optionally emit an Once Implementors should not override this method,
+but instead implement Optional, an error to emit with v8.0.0 Synchronously calls each of the listeners registered for the event named Returns v0.1.26 Removes the specified Once an event is emitted, all listeners attached to it at the
+time of emitting are called in order. This implies that any 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 When a single function has been added as a handler multiple times for a single
+event (as in the example below), Returns a reference to the v0.1.26 Generated using TypeDoc Encapsulates an X509 certificate and provides read-only access to
+its information. v15.6.0 Will be v15.6.0 The SHA-1 fingerprint of this certificate. Because SHA-1 is cryptographically broken and because the security of SHA-1 is
+significantly worse than that of algorithms that are commonly used to sign
+certificates, consider using v15.6.0 The SHA-256 fingerprint of this certificate. v15.6.0 The SHA-512 fingerprint of this certificate. v16.14.0 The complete subject of this certificate. v15.6.0 The subject alternative name specified for this certificate or v15.6.0 The information access content of this certificate or v15.6.0 An array detailing the key usages for this certificate. v15.6.0 The issuer identification included in this certificate. v15.6.0 The issuer certificate or v15.9.0 The public key v15.6.0 A v15.6.0 The serial number of this certificate. Serial numbers are assigned by certificate authorities and do not uniquely
+identify certificates. Consider using v15.6.0 The date/time from which this certificate is considered valid. v15.6.0 The date/time until which this certificate is considered valid. v15.6.0 Checks whether the certificate matches the given email address. If the If the If the Returns v15.6.0 Checks whether the certificate matches the given host name. If the certificate matches the given host name, the matching subject name is
+returned. The returned name might be an exact match (e.g., If the If the If the Returns a subject name that matches v15.6.0 Checks whether the certificate matches the given IP address (IPv4 or IPv6). Only RFC 5280 Returns v15.6.0 Checks whether this certificate was issued by the given v15.6.0 Checks whether the public key for this certificate is consistent with
+the given private key. A private key. v15.6.0 Returns information about this certificate using the legacy v15.6.0 Verifies that this certificate was signed by the given public key.
+Does not perform any other validation checks on the certificate. A public key. v15.6.0 Generated using TypeDoc Duplex streams are streams that implement both the Examples of v0.9.4 This symbol shall be used to install a listener for only monitoring Installing a listener using this symbol does not change the behavior once an
+ Sets or gets the default captureRejection value for all emitters. Returns whether the stream was destroyed or errored before emitting v16.8.0 Is v11.4.0 Returns whether v16.7.0, v14.18.0 Getter for the property v12.7.0 Becomes v12.9.0 This property reflects the current state of a v9.4.0 Returns the value of v9.3.0 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 v9.4.0 Getter for the property v12.3.0 Is v8.0.0 Is v11.4.0 Is v12.9.0 Is set to v12.6.0 Return the value of v9.3.0 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 v9.4.0 Getter for the property v12.3.0 Number of times v13.2.0, v12.16.0 Is v15.2.0, v14.17.0 Is true after 'close' has been emitted. v18.0.0 Returns error if the stream has been destroyed with an error. v18.0.0 If This can be changed manually to change the half-open behavior of an existing v0.9.4 Creates a This method is intentionally generic and works with the web platform EventTarget interface, which has no special The special handling of the An v11.13.0, v10.16.0 Returns an An The name of the event being listened for that iterates v13.6.0, v12.16.0 A class method that returns the number of listeners for the given The emitter to query The event name v0.9.12 Since v3.2.0 - Use Returns a copy of the array of listeners for the event named For For v15.2.0, v14.17.0 Returns the currently set max amount of listeners. For For v18.17.0 A non-negative number. The maximum number of listeners per v15.4.0 Listens once to the Listening to the This API allows safely using Returns a disposable so that it may be unsubscribed from more easily. Disposable that removes the v18.18.0 Alias for v10.0.0 Removes all listeners, or those of the specified It is bad practice to remove listeners added elsewhere in the code,
+particularly when the Returns a reference to the v0.1.26 By default Returns a reference to the v0.3.5 Returns the current max listener value for the v1.0.0 Returns a copy of the array of listeners for the event named v0.1.26 Returns a copy of the array of listeners for the event named v9.4.0 Returns the number of listeners listening to the event named If The name of the event being listened for The event handler function v3.2.0 Returns an array listing the events for which the emitter has registered
+listeners. The values in the array are strings or v6.0.0 A utility method for creating a v17.0.0 Returns whether the stream has been read from or cancelled. v16.8.0 A utility method for creating a web v17.0.0 The The optional If the The The Each call to Therefore to read a file's whole contents from a A If the Calling read after the Optional argument to specify how much data to read. v0.9.4 The By default, no encoding is assigned and stream data will be returned as The The encoding to use. v0.9.4 The The v0.9.4 The The The v0.9.4 The v0.11.14 The If the If the Optional specific stream to unpipe v0.9.4 Passing The The Developers using Unlike push, Chunk of data to unshift onto the read queue. For streams not operating in object mode, Encoding of string chunks. Must be a valid v0.9.11 Prior to Node.js 0.10, streams did not implement the entire When using an older Node.js library that emits It will rarely be necessary to use An "old style" readable stream v0.9.4 The iterator created by this method gives users the option to cancel the destruction
+of the stream if the When set to v16.3.0 This method allows mapping over the stream. The fn function will be called for every chunk in the stream.
+If the fn function returns a promise - that promise will be a function to map over every chunk in the stream. Async or not. a stream mapped with the function fn. v17.4.0, v16.14.0 This method allows filtering the stream. For each chunk in the stream the fn function will be called
+and if it returns a truthy value, the chunk will be passed to the result stream.
+If the fn function returns a promise - that promise will be a function to filter chunks from the stream. Async or not. a stream filtered with the predicate fn. v17.4.0, v16.14.0 This method allows iterating a stream. For each chunk in the stream the fn function will be called.
+If the fn function returns a promise - that promise will be This method is different from This method is different from listening to the a function to call on each chunk of the stream. Async or not. a promise for when the stream has finished. v17.5.0 This method allows easily obtaining the contents of a stream. As this method reads the entire stream into memory, it negates the benefits of streams. It's intended
+for interoperability and convenience, not as the primary way to consume streams. a promise containing an array with the contents of the stream. v17.5.0 This method is similar to a function to call on each chunk of the stream. Async or not. a promise evaluating to v17.5.0 This method is similar to a function to call on each chunk of the stream. Async or not. a promise evaluating to the first chunk for which fn evaluated with a truthy value,
+or v17.5.0 This method is similar to a function to call on each chunk of the stream. Async or not. a promise evaluating to v17.5.0 This method returns a new stream by applying the given callback to each chunk of the stream
+and then flattening the result. It is possible to return a stream or another iterable or async iterable from fn and the result streams
+will be merged (flattened) into the returned stream. a function to map over every chunk in the stream. May be async. May be a stream or generator. a stream flat-mapped with the function fn. v17.5.0 This method returns a new stream with the first limit chunks dropped from the start. the number of chunks to drop from the readable. a stream with limit chunks dropped from the start. v17.5.0 This method returns a new stream with the first limit chunks. the number of chunks to take from the readable. a stream with limit chunks taken. v17.5.0 This method returns a new stream with chunks of the underlying stream paired with a counter
+in the form a stream of indexed pairs. v17.5.0 This method calls fn on each chunk of the stream in order, passing it the result from the calculation
+on the previous element. It returns a promise for the final value of the reduction. If no initial value is supplied the first chunk of the stream is used as the initial value.
+If the stream is empty, the promise is rejected with a The reducer function iterates the stream element-by-element which means that there is no concurrency parameter
+or parallelism. To perform a reduce concurrently, you can extract the async function to a reducer function to call over every chunk in the stream. Async or not. the initial value to use in the reduction. a promise for the final value of the reduction. v17.5.0 Destroy the stream. Optionally emit an Once Implementors should not override this method, but instead implement Error which will be passed as payload in v8.0.0 A utility method for creating duplex streams. v16.8.0 The The return value is While a stream is not draining, calls to Writing data while the stream is not draining is particularly
+problematic for a If the data to be written can be generated or fetched on demand, it is
+recommended to encapsulate the logic into a A Optional data to write. For streams not operating in object mode, Callback for when this chunk of data is flushed. v0.9.4 The The new default encoding v0.11.15 Calling the Calling the write method after calling end will raise an error. v0.9.4 The The primary intent of See also: v0.11.2 The When using If the See also: v0.11.2 Event emitter
+The defined events on documents including: Synchronously calls each of the listeners registered for the event named Returns v0.1.26 Adds the Returns a reference to the By default, event listeners are invoked in the order they are added. The The name of the event. The callback function v0.1.101 Adds a one-time Returns a reference to the By default, event listeners are invoked in the order they are added. The The name of the event. The callback function v0.3.0 Adds the Returns a reference to the The name of the event. The callback function v6.0.0 Adds a one-time Returns a reference to the The name of the event. The callback function v6.0.0 Removes the specified Once an event is emitted, all listeners attached to it at the
+time of emitting are called in order. This implies that any 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 When a single function has been added as a handler multiple times for a single
+event (as in the example below), Returns a reference to the v0.1.26 Generated using TypeDoc The This symbol shall be used to install a listener for only monitoring Installing a listener using this symbol does not change the behavior once an
+ Sets or gets the default captureRejection value for all emitters. Returns whether the stream was destroyed or errored before emitting v16.8.0 Is v11.4.0 Returns whether v16.7.0, v14.18.0 Getter for the property v12.7.0 Becomes v12.9.0 This property reflects the current state of a v9.4.0 Returns the value of v9.3.0 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 v9.4.0 Getter for the property v12.3.0 Is v8.0.0 Is v11.4.0 Is v12.9.0 Is set to v12.6.0 Return the value of v9.3.0 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 v9.4.0 Getter for the property v12.3.0 Number of times v13.2.0, v12.16.0 Is v15.2.0, v14.17.0 Is true after 'close' has been emitted. v18.0.0 Returns error if the stream has been destroyed with an error. v18.0.0 If This can be changed manually to change the half-open behavior of an existing v0.9.4 Creates a This method is intentionally generic and works with the web platform EventTarget interface, which has no special The special handling of the An v11.13.0, v10.16.0 Returns an An The name of the event being listened for that iterates v13.6.0, v12.16.0 A class method that returns the number of listeners for the given The emitter to query The event name v0.9.12 Since v3.2.0 - Use Returns a copy of the array of listeners for the event named For For v15.2.0, v14.17.0 Returns the currently set max amount of listeners. For For v18.17.0 A non-negative number. The maximum number of listeners per v15.4.0 Listens once to the Listening to the This API allows safely using Returns a disposable so that it may be unsubscribed from more easily. Disposable that removes the v18.18.0 Alias for v10.0.0 Removes all listeners, or those of the specified It is bad practice to remove listeners added elsewhere in the code,
+particularly when the Returns a reference to the v0.1.26 By default Returns a reference to the v0.3.5 Returns the current max listener value for the v1.0.0 Returns a copy of the array of listeners for the event named v0.1.26 Returns a copy of the array of listeners for the event named v9.4.0 Returns the number of listeners listening to the event named If The name of the event being listened for The event handler function v3.2.0 Returns an array listing the events for which the emitter has registered
+listeners. The values in the array are strings or v6.0.0 A utility method for creating a v17.0.0 Returns whether the stream has been read from or cancelled. v16.8.0 A utility method for creating a web v17.0.0 The The optional If the The The Each call to Therefore to read a file's whole contents from a A If the Calling read after the Optional argument to specify how much data to read. v0.9.4 The By default, no encoding is assigned and stream data will be returned as The The encoding to use. v0.9.4 The The v0.9.4 The The The v0.9.4 The v0.11.14 The If the If the Optional specific stream to unpipe v0.9.4 Passing The The Developers using Unlike push, Chunk of data to unshift onto the read queue. For streams not operating in object mode, Encoding of string chunks. Must be a valid v0.9.11 Prior to Node.js 0.10, streams did not implement the entire When using an older Node.js library that emits It will rarely be necessary to use An "old style" readable stream v0.9.4 The iterator created by this method gives users the option to cancel the destruction
+of the stream if the When set to v16.3.0 This method allows mapping over the stream. The fn function will be called for every chunk in the stream.
+If the fn function returns a promise - that promise will be a function to map over every chunk in the stream. Async or not. a stream mapped with the function fn. v17.4.0, v16.14.0 This method allows filtering the stream. For each chunk in the stream the fn function will be called
+and if it returns a truthy value, the chunk will be passed to the result stream.
+If the fn function returns a promise - that promise will be a function to filter chunks from the stream. Async or not. a stream filtered with the predicate fn. v17.4.0, v16.14.0 This method allows iterating a stream. For each chunk in the stream the fn function will be called.
+If the fn function returns a promise - that promise will be This method is different from This method is different from listening to the a function to call on each chunk of the stream. Async or not. a promise for when the stream has finished. v17.5.0 This method allows easily obtaining the contents of a stream. As this method reads the entire stream into memory, it negates the benefits of streams. It's intended
+for interoperability and convenience, not as the primary way to consume streams. a promise containing an array with the contents of the stream. v17.5.0 This method is similar to a function to call on each chunk of the stream. Async or not. a promise evaluating to v17.5.0 This method is similar to a function to call on each chunk of the stream. Async or not. a promise evaluating to the first chunk for which fn evaluated with a truthy value,
+or v17.5.0 This method is similar to a function to call on each chunk of the stream. Async or not. a promise evaluating to v17.5.0 This method returns a new stream by applying the given callback to each chunk of the stream
+and then flattening the result. It is possible to return a stream or another iterable or async iterable from fn and the result streams
+will be merged (flattened) into the returned stream. a function to map over every chunk in the stream. May be async. May be a stream or generator. a stream flat-mapped with the function fn. v17.5.0 This method returns a new stream with the first limit chunks dropped from the start. the number of chunks to drop from the readable. a stream with limit chunks dropped from the start. v17.5.0 This method returns a new stream with the first limit chunks. the number of chunks to take from the readable. a stream with limit chunks taken. v17.5.0 This method returns a new stream with chunks of the underlying stream paired with a counter
+in the form a stream of indexed pairs. v17.5.0 This method calls fn on each chunk of the stream in order, passing it the result from the calculation
+on the previous element. It returns a promise for the final value of the reduction. If no initial value is supplied the first chunk of the stream is used as the initial value.
+If the stream is empty, the promise is rejected with a The reducer function iterates the stream element-by-element which means that there is no concurrency parameter
+or parallelism. To perform a reduce concurrently, you can extract the async function to a reducer function to call over every chunk in the stream. Async or not. the initial value to use in the reduction. a promise for the final value of the reduction. v17.5.0 Destroy the stream. Optionally emit an Once Implementors should not override this method, but instead implement Error which will be passed as payload in v8.0.0 A utility method for creating duplex streams. v16.8.0 The The return value is While a stream is not draining, calls to Writing data while the stream is not draining is particularly
+problematic for a If the data to be written can be generated or fetched on demand, it is
+recommended to encapsulate the logic into a A Optional data to write. For streams not operating in object mode, Callback for when this chunk of data is flushed. v0.9.4 The The new default encoding v0.11.15 Calling the Calling the write method after calling end will raise an error. v0.9.4 The The primary intent of See also: v0.11.2 The When using If the See also: v0.11.2 Event emitter
+The defined events on documents including: Synchronously calls each of the listeners registered for the event named Returns v0.1.26 Adds the Returns a reference to the By default, event listeners are invoked in the order they are added. The The name of the event. The callback function v0.1.101 Adds a one-time Returns a reference to the By default, event listeners are invoked in the order they are added. The The name of the event. The callback function v0.3.0 Adds the Returns a reference to the The name of the event. The callback function v6.0.0 Adds a one-time Returns a reference to the The name of the event. The callback function v6.0.0 Removes the specified Once an event is emitted, all listeners attached to it at the
+time of emitting are called in order. This implies that any 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 When a single function has been added as a handler multiple times for a single
+event (as in the example below), Returns a reference to the v0.1.26 Generated using TypeDoc Transform streams are Examples of v0.9.4 This symbol shall be used to install a listener for only monitoring Installing a listener using this symbol does not change the behavior once an
+ Sets or gets the default captureRejection value for all emitters. Returns whether the stream was destroyed or errored before emitting v16.8.0 Is v11.4.0 Returns whether v16.7.0, v14.18.0 Getter for the property v12.7.0 Becomes v12.9.0 This property reflects the current state of a v9.4.0 Returns the value of v9.3.0 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 v9.4.0 Getter for the property v12.3.0 Is v8.0.0 Is v11.4.0 Is v12.9.0 Is set to v12.6.0 Return the value of v9.3.0 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 v9.4.0 Getter for the property v12.3.0 Number of times v13.2.0, v12.16.0 Is v15.2.0, v14.17.0 Is true after 'close' has been emitted. v18.0.0 Returns error if the stream has been destroyed with an error. v18.0.0 If This can be changed manually to change the half-open behavior of an existing v0.9.4 Creates a This method is intentionally generic and works with the web platform EventTarget interface, which has no special The special handling of the An v11.13.0, v10.16.0 Returns an An The name of the event being listened for that iterates v13.6.0, v12.16.0 A class method that returns the number of listeners for the given The emitter to query The event name v0.9.12 Since v3.2.0 - Use Returns a copy of the array of listeners for the event named For For v15.2.0, v14.17.0 Returns the currently set max amount of listeners. For For v18.17.0 A non-negative number. The maximum number of listeners per v15.4.0 Listens once to the Listening to the This API allows safely using Returns a disposable so that it may be unsubscribed from more easily. Disposable that removes the v18.18.0 Alias for v10.0.0 Removes all listeners, or those of the specified It is bad practice to remove listeners added elsewhere in the code,
+particularly when the Returns a reference to the v0.1.26 By default Returns a reference to the v0.3.5 Returns the current max listener value for the v1.0.0 Returns a copy of the array of listeners for the event named v0.1.26 Returns a copy of the array of listeners for the event named v9.4.0 Returns the number of listeners listening to the event named If The name of the event being listened for The event handler function v3.2.0 Returns an array listing the events for which the emitter has registered
+listeners. The values in the array are strings or v6.0.0 A utility method for creating a v17.0.0 Returns whether the stream has been read from or cancelled. v16.8.0 A utility method for creating a web v17.0.0 The The optional If the The The Each call to Therefore to read a file's whole contents from a A If the Calling read after the Optional argument to specify how much data to read. v0.9.4 The By default, no encoding is assigned and stream data will be returned as The The encoding to use. v0.9.4 The The v0.9.4 The The The v0.9.4 The v0.11.14 The If the If the Optional specific stream to unpipe v0.9.4 Passing The The Developers using Unlike push, Chunk of data to unshift onto the read queue. For streams not operating in object mode, Encoding of string chunks. Must be a valid v0.9.11 Prior to Node.js 0.10, streams did not implement the entire When using an older Node.js library that emits It will rarely be necessary to use An "old style" readable stream v0.9.4 The iterator created by this method gives users the option to cancel the destruction
+of the stream if the When set to v16.3.0 This method allows mapping over the stream. The fn function will be called for every chunk in the stream.
+If the fn function returns a promise - that promise will be a function to map over every chunk in the stream. Async or not. a stream mapped with the function fn. v17.4.0, v16.14.0 This method allows filtering the stream. For each chunk in the stream the fn function will be called
+and if it returns a truthy value, the chunk will be passed to the result stream.
+If the fn function returns a promise - that promise will be a function to filter chunks from the stream. Async or not. a stream filtered with the predicate fn. v17.4.0, v16.14.0 This method allows iterating a stream. For each chunk in the stream the fn function will be called.
+If the fn function returns a promise - that promise will be This method is different from This method is different from listening to the a function to call on each chunk of the stream. Async or not. a promise for when the stream has finished. v17.5.0 This method allows easily obtaining the contents of a stream. As this method reads the entire stream into memory, it negates the benefits of streams. It's intended
+for interoperability and convenience, not as the primary way to consume streams. a promise containing an array with the contents of the stream. v17.5.0 This method is similar to a function to call on each chunk of the stream. Async or not. a promise evaluating to v17.5.0 This method is similar to a function to call on each chunk of the stream. Async or not. a promise evaluating to the first chunk for which fn evaluated with a truthy value,
+or v17.5.0 This method is similar to a function to call on each chunk of the stream. Async or not. a promise evaluating to v17.5.0 This method returns a new stream by applying the given callback to each chunk of the stream
+and then flattening the result. It is possible to return a stream or another iterable or async iterable from fn and the result streams
+will be merged (flattened) into the returned stream. a function to map over every chunk in the stream. May be async. May be a stream or generator. a stream flat-mapped with the function fn. v17.5.0 This method returns a new stream with the first limit chunks dropped from the start. the number of chunks to drop from the readable. a stream with limit chunks dropped from the start. v17.5.0 This method returns a new stream with the first limit chunks. the number of chunks to take from the readable. a stream with limit chunks taken. v17.5.0 This method returns a new stream with chunks of the underlying stream paired with a counter
+in the form a stream of indexed pairs. v17.5.0 This method calls fn on each chunk of the stream in order, passing it the result from the calculation
+on the previous element. It returns a promise for the final value of the reduction. If no initial value is supplied the first chunk of the stream is used as the initial value.
+If the stream is empty, the promise is rejected with a The reducer function iterates the stream element-by-element which means that there is no concurrency parameter
+or parallelism. To perform a reduce concurrently, you can extract the async function to a reducer function to call over every chunk in the stream. Async or not. the initial value to use in the reduction. a promise for the final value of the reduction. v17.5.0 Destroy the stream. Optionally emit an Once Implementors should not override this method, but instead implement Error which will be passed as payload in v8.0.0 A utility method for creating duplex streams. v16.8.0 The The return value is While a stream is not draining, calls to Writing data while the stream is not draining is particularly
+problematic for a If the data to be written can be generated or fetched on demand, it is
+recommended to encapsulate the logic into a A Optional data to write. For streams not operating in object mode, Callback for when this chunk of data is flushed. v0.9.4 The The new default encoding v0.11.15 Calling the Calling the write method after calling end will raise an error. v0.9.4 The The primary intent of See also: v0.11.2 The When using If the See also: v0.11.2 Event emitter
+The defined events on documents including: Synchronously calls each of the listeners registered for the event named Returns v0.1.26 Adds the Returns a reference to the By default, event listeners are invoked in the order they are added. The The name of the event. The callback function v0.1.101 Adds a one-time Returns a reference to the By default, event listeners are invoked in the order they are added. The The name of the event. The callback function v0.3.0 Adds the Returns a reference to the The name of the event. The callback function v6.0.0 Adds a one-time Returns a reference to the The name of the event. The callback function v6.0.0 Removes the specified Once an event is emitted, all listeners attached to it at the
+time of emitting are called in order. This implies that any 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 When a single function has been added as a handler multiple times for a single
+event (as in the example below), Returns a reference to the v0.1.26 Generated using TypeDoc The All It supports the following option: v0.1.26 This symbol shall be used to install a listener for only monitoring Installing a listener using this symbol does not change the behavior once an
+ Sets or gets the default captureRejection value for all emitters. Creates a This method is intentionally generic and works with the web platform EventTarget interface, which has no special The special handling of the An v11.13.0, v10.16.0 Returns an An The name of the event being listened for that iterates v13.6.0, v12.16.0 A class method that returns the number of listeners for the given The emitter to query The event name v0.9.12 Since v3.2.0 - Use Returns a copy of the array of listeners for the event named For For v15.2.0, v14.17.0 Returns the currently set max amount of listeners. For For v18.17.0 A non-negative number. The maximum number of listeners per v15.4.0 Listens once to the Listening to the This API allows safely using Returns a disposable so that it may be unsubscribed from more easily. Disposable that removes the v18.18.0 Alias for v0.1.26 Adds the Returns a reference to the By default, event listeners are invoked in the order they are added. The The name of the event. The callback function v0.1.101 Adds a one-time Returns a reference to the By default, event listeners are invoked in the order they are added. The The name of the event. The callback function v0.3.0 Removes the specified Once an event is emitted, all listeners attached to it at the
+time of emitting are called in order. This implies that any 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 When a single function has been added as a handler multiple times for a single
+event (as in the example below), Returns a reference to the v0.1.26 Alias for v10.0.0 Removes all listeners, or those of the specified It is bad practice to remove listeners added elsewhere in the code,
+particularly when the Returns a reference to the v0.1.26 By default Returns a reference to the v0.3.5 Returns the current max listener value for the v1.0.0 Returns a copy of the array of listeners for the event named v0.1.26 Returns a copy of the array of listeners for the event named v9.4.0 Synchronously calls each of the listeners registered for the event named Returns v0.1.26 Returns the number of listeners listening to the event named If The name of the event being listened for The event handler function v3.2.0 Adds the Returns a reference to the The name of the event. The callback function v6.0.0 Adds a one-time Returns a reference to the The name of the event. The callback function v6.0.0 Returns an array listing the events for which the emitter has registered
+listeners. The values in the array are strings or v6.0.0 Generated using TypeDocClass Blob
Index
Constructors
constructor
Blob object containing a concatenation of the given sources.Blob.Parameters
Optional options: BlobOptionsReturns Blob
Properties
Readonly sizeBlob in bytes.Since
Readonly typeBlob.Since
Methods
array
Blob data.Returns Promise<ArrayBuffer>
Since
slice
Blob containing a subset of this Blob objects
+data. The original Blob is not altered.Parameters
Optional start: numberOptional end: numberOptional type: stringBlobReturns Blob
Since
text
stream
ReadableStream that allows the content of the Blob to be read.Returns ReadableStream<any>
Since
Class Interface
readline.Interface class are constructed using thereadline.createInterface() method. Every instance is associated with a
+single input Readable stream and a single output Writable stream.
+The output stream is used to print prompts for user input that arrives on,
+and is read from, the input stream.Since
Hierarchy (view full)
Index
Constructors
Properties
Methods
Constructors
Protected constructor
+
+readline.Interface class are constructed using the
+readline.createInterface() method.Parameters
Optional output: WritableStreamOptional completer: Completer | AsyncCompleterOptional terminal: booleanReturns Interface
+
+readline.Interface class are constructed using the
+readline.createInterface() method.Parameters
Returns Interface
Properties
Static Readonly error'error'
+events. Listeners installed using this symbol are called before the regular
+'error' listeners are called.'error' event is emitted, therefore the process will still crash if no
+regular 'error' listener is installed.Static Readonly captureStatic captureStatic defaultReadonly terminalReadonly lineline event
+being emitted. Once the line event has been emitted, this property will
+be an empty string.rl.cursor is not also controlled.'line' event.
+const values = ['lorem ipsum', 'dolor sit amet'];
const rl = readline.createInterface(process.stdin);
const showResults = debounce(() => {
console.log(
'\n',
values.filter((val) => val.startsWith(rl.line)).join(' ')
);
}, 300);
process.stdin.on('keypress', (c, k) => {
showResults();
});
+Since
Readonly cursorrl.line.Since
Methods
Optional [captureStatic oncePromise 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.'error' event
+semantics and does not listen to the 'error' event.
+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();
+'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:
+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
+AbortSignal can be used to cancel waiting for the event:
+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!
+Parameters
Optional options: StaticEventEmitterOptionsReturns Promise<any[]>
Since
Parameters
Optional options: StaticEventEmitterOptionsReturns Promise<any[]>
Static on
+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
})();
+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.AbortSignal can be used to cancel waiting on events:
+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());
+Parameters
Optional options: StaticEventEmitterOptionsReturns AsyncIterableIterator<any>
eventName events emitted by the emitterSince
Static listenereventNameregistered on the given emitter.
+const { EventEmitter, listenerCount } = require('events');
const myEmitter = new EventEmitter();
myEmitter.on('event', () => {});
myEmitter.on('event', () => {});
console.log(listenerCount(myEmitter, 'event'));
// Prints: 2
+Parameters
Returns number
Since
Deprecated
listenerCount instead.Static geteventName.EventEmitters this behaves exactly the same as calling .listeners on
+the emitter.EventTargets this is the only way to get the event listeners for the
+event target. This is useful for debugging and diagnostic purposes.
+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]
}
+Parameters
Returns Function[]
Since
Static getEventEmitters this behaves exactly the same as calling .getMaxListeners on
+the emitter.EventTargets this is the only way to get the max event listeners for the
+event target. If the number of event handlers on a single EventTarget exceeds
+the max set, the EventTarget will print a warning.
+import { getMaxListeners, setMaxListeners, EventEmitter } from 'node:events';
{
const ee = new EventEmitter();
console.log(getMaxListeners(ee)); // 10
setMaxListeners(11, ee);
console.log(getMaxListeners(ee)); // 11
}
{
const et = new EventTarget();
console.log(getMaxListeners(et)); // 10
setMaxListeners(11, et);
console.log(getMaxListeners(et)); // 11
}
+Parameters
Returns number
Since
Static set
+const {
setMaxListeners,
EventEmitter
} = require('events');
const target = new EventTarget();
const emitter = new EventEmitter();
setMaxListeners(5, target, emitter);
+Parameters
Optional n: numberEventTarget event.Rest ...eventTargets: (EventEmitter<DefaultEventMap> | _DOMEventTarget)[]Returns void
Since
Static addExperimental abort event on the provided signal.abort event on abort signals is unsafe and may
+lead to resource leaks since another third party with the signal can
+call e.stopImmediatePropagation(). Unfortunately Node.js cannot change
+this since it would violate the web standard. Additionally, the original
+API makes it easy to forget to remove listeners.AbortSignals in Node.js APIs by solving these
+two issues by listening to the event such that stopImmediatePropagation does
+not prevent the listener from running.
+import { addAbortListener } from 'node:events';
function example(signal) {
let disposable;
try {
signal.addEventListener('abort', (e) => e.stopImmediatePropagation());
disposable = addAbortListener(signal, (e) => {
// Do something when signal is aborted.
});
} finally {
disposable?.[Symbol.dispose]();
}
}
+Parameters
Parameters
Returns void
Returns Disposable
abort listener.Since
remove
listener from the listener array for the event namedeventName.
+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.removeListener() or removeAllListeners() calls after emitting and before the last listener finishes execution
+will not remove them fromemit() in progress. Subsequent events behave as expected.
+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
+emitter.listeners() method will need to be recreated.removeListener() will remove the most
+recently added instance. In the example the once('ping')listener is removed:
+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');
+EventEmitter, so that calls can be chained.Type Parameters
Parameters
Parameters
Rest ...args: any[]Returns void
Returns this
Since
off
emitter.removeListener().Type Parameters
Parameters
Parameters
Rest ...args: any[]Returns void
Returns this
Since
remove
eventName.EventEmitter instance was created by some other
+component or module (e.g. sockets or file streams).EventEmitter, so that calls can be chained.Parameters
Optional event: string | symbolReturns this
Since
set
EventEmitters will print a warning if more than 10 listeners are
+added for a particular event. This is a useful default that helps finding
+memory leaks. The emitter.setMaxListeners() method allows the limit to be
+modified for this specific EventEmitter instance. The value can be set toInfinity (or 0) to indicate an unlimited number of listeners.EventEmitter, so that calls can be chained.Parameters
Returns this
Since
get
EventEmitter which is either
+set by emitter.setMaxListeners(n) or defaults to defaultMaxListeners.Returns number
Since
listeners
eventName.
+server.on('connection', (stream) => {
console.log('someone connected!');
});
console.log(util.inspect(server.listeners('connection')));
// Prints: [ [Function] ]
+Type Parameters
Parameters
Returns Function[]
Since
raw
eventName,
+including any wrappers (such as those created by .once()).
+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');
+Type Parameters
Parameters
Returns Function[]
Since
listener
eventName.listener is provided, it will return how many times the listener
+is found in the list of the listeners of the event.Type Parameters
Parameters
Optional listener: FunctionReturns number
Since
event
Symbols.
+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) ]
+Returns (string | symbol)[]
Since
get
set
prompt
rl.prompt() method writes the readline.Interface instances configuredprompt to a new line in output in order to provide a user with a new
+location at which to provide input.rl.prompt() will resume the input stream if it has been
+paused.readline.Interface was created with output set to null orundefined the prompt is not written.Parameters
Optional preserveCursor: booleantrue, prevents the cursor placement from being reset to 0.Returns void
Since
question
rl.question() method displays the query by writing it to the output,
+waits for user input to be provided on input, then invokes the callbackfunction passing the provided input as the first argument.rl.question() will resume the input stream if it has been
+paused.readline.Interface was created with output set to null orundefined the query is not written.callback function passed to rl.question() does not follow the typical
+pattern of accepting an Error object or null as the first argument.
+The callback is called with the provided answer as the only argument.
+rl.question('What is your favorite food? ', (answer) => {
console.log(`Oh, so your favorite food is ${answer}`);
});
+AbortController to cancel a question.
+const ac = new AbortController();
const signal = ac.signal;
rl.question('What is your favorite food? ', { signal }, (answer) => {
console.log(`Oh, so your favorite food is ${answer}`);
});
signal.addEventListener('abort', () => {
console.log('The food question timed out');
}, { once: true });
setTimeout(() => ac.abort(), 10000);
+AbortController it will reject with an AbortError.
+const util = require('util');
const question = util.promisify(rl.question).bind(rl);
async function questionExample() {
try {
const answer = await question('What is you favorite food? ');
console.log(`Oh, so your favorite food is ${answer}`);
} catch (err) {
console.error('Question rejected', err);
}
}
questionExample();
+Parameters
output, prepended to the prompt.query.Parameters
Returns void
Returns void
Since
Parameters
Parameters
Returns void
Returns void
pause
resume
close
rl.close() method closes the readline.Interface instance and
+relinquishes control over the input and output streams. When called,
+the 'close' event will be emitted.rl.close() does not immediately stop other events (including 'line')
+from being emitted by the readline.Interface instance.Returns void
Since
write
rl.write() method will write either data or a key sequence identified
+by key to the output. The key argument is supported only if output is
+a TTY text terminal. See TTY keybindings for a list of key
+combinations.key is specified, data is ignored.rl.write() will resume the input stream if it has been
+paused.readline.Interface was created with output set to null orundefined the data and key are not written.
+rl.write('Delete this!');
// Simulate Ctrl+U to delete the line written previously
rl.write(null, { ctrl: true, name: 'u' });
+rl.write() method will write the data to the readline Interface'sinputas if it were provided by the user.Returns void
Since
Returns void
get
add
+
+Parameters
Parameters
Rest ...args: any[]Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
emit
eventName, in the order they were registered, passing the supplied arguments
+to each.true if the event had listeners, false otherwise.
+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
+Parameters
Rest ...args: any[]Returns boolean
Since
Parameters
Returns boolean
Parameters
Returns boolean
Parameters
Returns boolean
Parameters
Returns boolean
Parameters
Returns boolean
Parameters
Returns boolean
Parameters
Returns boolean
Parameters
Returns boolean
on
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 eventNameand listener will result in the listener being added, and called, multiple
+times.
+server.on('connection', (stream) => {
console.log('someone connected!');
});
+EventEmitter, so that calls can be chained.emitter.prependListener() method can be used as an alternative to add the
+event listener to the beginning of the listeners array.
+const myEE = new EventEmitter();
myEE.on('foo', () => console.log('a'));
myEE.prependListener('foo', () => console.log('b'));
myEE.emit('foo');
// Prints:
// b
// a
+Parameters
Parameters
Rest ...args: any[]Returns void
Returns this
Since
Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
once
listener function for the event named eventName. The
+next time eventName is triggered, this listener is removed and then invoked.
+server.once('connection', (stream) => {
console.log('Ah, we have our first user!');
});
+EventEmitter, so that calls can be chained.emitter.prependOnceListener() method can be used as an alternative to add the
+event listener to the beginning of the listeners array.
+const myEE = new EventEmitter();
myEE.once('foo', () => console.log('a'));
myEE.prependOnceListener('foo', () => console.log('b'));
myEE.emit('foo');
// Prints:
// b
// a
+Parameters
Parameters
Rest ...args: any[]Returns void
Returns this
Since
Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
prepend
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 eventNameand listener will result in the listener being added, and called, multiple
+times.
+server.prependListener('connection', (stream) => {
console.log('someone connected!');
});
+EventEmitter, so that calls can be chained.Parameters
Parameters
Rest ...args: any[]Returns void
Returns this
Since
Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
prepend
listener function for the event named eventName to the beginning of the listeners array. The next time eventName is triggered, this
+listener is removed, and then invoked.
+server.prependOnceListener('connection', (stream) => {
console.log('Ah, we have our first user!');
});
+EventEmitter, so that calls can be chained.Parameters
Parameters
Rest ...args: any[]Returns void
Returns this
Since
Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
[async
Returns AsyncIterableIterator<string>
Class KeyObject
KeyObject class to represent a symmetric or asymmetric key,
+and each kind of key exposes different functions. The createSecretKey, createPublicKey and createPrivateKey methods are used to create KeyObjectinstances. KeyObject
+objects are not to be created directly using the newkeyword.KeyObject API instead of
+passing keys as strings or Buffers due to improved security features.KeyObject instances can be passed to other threads via postMessage().
+The receiver obtains a cloned KeyObject, and the KeyObject does not need to
+be listed in the transferList argument.Since
Index
Constructors
Properties
Methods
Constructors
Private constructorProperties
Optional asymmetric
+
+'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)undefined for unrecognized KeyObject types and symmetric
+keys.Since
Optional asymmetricundefined for symmetric keys.Optional asymmetricRSASSA-PSS-params sequence,
+the hashAlgorithm, mgf1HashAlgorithm, and saltLength properties will be
+set.Since
Optional symmetricundefined for asymmetric keys.Since
type
KeyObject, this property is either'secret' for secret (symmetric) keys, 'public' for public (asymmetric) keys
+or 'private' for private (asymmetric) keys.Since
Methods
Static fromCryptoKey instance to a KeyObject:
+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)
+Parameters
Returns KeyObject
Since
export
cipher and format options. The PKCS#8 type can be used with anyformat to encrypt any key algorithm (RSA, EC, or DH) by specifying acipher. PKCS#1 and SEC1 can only be
+encrypted by specifying a cipherwhen the PEM format is used. For maximum compatibility, use PKCS#8 for
+encrypted private keys. Since PKCS#8 defines its own
+encryption mechanism, PEM-level encryption is not supported when encrypting
+a PKCS#8 key. See RFC 5208 for PKCS#8 encryption and RFC 1421 for
+PKCS#1 and SEC1 encryption.Parameters
Returns string | Buffer
Since
Parameters
Optional options: KeyExportOptions<"der">Returns Buffer
Parameters
Optional options: JwkKeyExportOptionsReturns JsonWebKey
equals
true or false depending on whether the keys have exactly the same type, value, and parameters.
+This method is not constant time.Parameters
Returns boolean
Since
Class MessagePort
worker.MessagePort class represent one end of an
+asynchronous, two-way communications channel. It can be used to transfer
+structured data, memory regions and other MessagePorts between different Worker s.MessagePort s.Since
Hierarchy (view full)
Index
Constructors
Properties
Methods
Constructors
constructor
Parameters
Optional options: EventEmitterOptionsReturns MessagePort
Properties
Static Readonly error'error'
+events. Listeners installed using this symbol are called before the regular
+'error' listeners are called.'error' event is emitted, therefore the process will still crash if no
+regular 'error' listener is installed.Static Readonly captureStatic captureStatic defaultMethods
Optional [captureStatic oncePromise 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.'error' event
+semantics and does not listen to the 'error' event.
+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();
+'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:
+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
+AbortSignal can be used to cancel waiting for the event:
+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!
+Parameters
Optional options: StaticEventEmitterOptionsReturns Promise<any[]>
Since
Parameters
Optional options: StaticEventEmitterOptionsReturns Promise<any[]>
Static on
+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
})();
+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.AbortSignal can be used to cancel waiting on events:
+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());
+Parameters
Optional options: StaticEventEmitterOptionsReturns AsyncIterableIterator<any>
eventName events emitted by the emitterSince
Static listenereventNameregistered on the given emitter.
+const { EventEmitter, listenerCount } = require('events');
const myEmitter = new EventEmitter();
myEmitter.on('event', () => {});
myEmitter.on('event', () => {});
console.log(listenerCount(myEmitter, 'event'));
// Prints: 2
+Parameters
Returns number
Since
Deprecated
listenerCount instead.Static geteventName.EventEmitters this behaves exactly the same as calling .listeners on
+the emitter.EventTargets this is the only way to get the event listeners for the
+event target. This is useful for debugging and diagnostic purposes.
+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]
}
+Parameters
Returns Function[]
Since
Static getEventEmitters this behaves exactly the same as calling .getMaxListeners on
+the emitter.EventTargets this is the only way to get the max event listeners for the
+event target. If the number of event handlers on a single EventTarget exceeds
+the max set, the EventTarget will print a warning.
+import { getMaxListeners, setMaxListeners, EventEmitter } from 'node:events';
{
const ee = new EventEmitter();
console.log(getMaxListeners(ee)); // 10
setMaxListeners(11, ee);
console.log(getMaxListeners(ee)); // 11
}
{
const et = new EventTarget();
console.log(getMaxListeners(et)); // 10
setMaxListeners(11, et);
console.log(getMaxListeners(et)); // 11
}
+Parameters
Returns number
Since
Static set
+const {
setMaxListeners,
EventEmitter
} = require('events');
const target = new EventTarget();
const emitter = new EventEmitter();
setMaxListeners(5, target, emitter);
+Parameters
Optional n: numberEventTarget event.Rest ...eventTargets: (EventEmitter<DefaultEventMap> | _DOMEventTarget)[]Returns void
Since
Static addExperimental abort event on the provided signal.abort event on abort signals is unsafe and may
+lead to resource leaks since another third party with the signal can
+call e.stopImmediatePropagation(). Unfortunately Node.js cannot change
+this since it would violate the web standard. Additionally, the original
+API makes it easy to forget to remove listeners.AbortSignals in Node.js APIs by solving these
+two issues by listening to the event such that stopImmediatePropagation does
+not prevent the listener from running.
+import { addAbortListener } from 'node:events';
function example(signal) {
let disposable;
try {
signal.addEventListener('abort', (e) => e.stopImmediatePropagation());
disposable = addAbortListener(signal, (e) => {
// Do something when signal is aborted.
});
} finally {
disposable?.[Symbol.dispose]();
}
}
+Parameters
Parameters
Returns void
Returns Disposable
abort listener.Since
remove
eventName.EventEmitter instance was created by some other
+component or module (e.g. sockets or file streams).EventEmitter, so that calls can be chained.Parameters
Optional event: string | symbolReturns this
Since
set
EventEmitters will print a warning if more than 10 listeners are
+added for a particular event. This is a useful default that helps finding
+memory leaks. The emitter.setMaxListeners() method allows the limit to be
+modified for this specific EventEmitter instance. The value can be set toInfinity (or 0) to indicate an unlimited number of listeners.EventEmitter, so that calls can be chained.Parameters
Returns this
Since
get
EventEmitter which is either
+set by emitter.setMaxListeners(n) or defaults to defaultMaxListeners.Returns number
Since
listeners
eventName.
+server.on('connection', (stream) => {
console.log('someone connected!');
});
console.log(util.inspect(server.listeners('connection')));
// Prints: [ [Function] ]
+Type Parameters
Parameters
Returns Function[]
Since
raw
eventName,
+including any wrappers (such as those created by .once()).
+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');
+Type Parameters
Parameters
Returns Function[]
Since
listener
eventName.listener is provided, it will return how many times the listener
+is found in the list of the listeners of the event.Type Parameters
Parameters
Optional listener: FunctionReturns number
Since
event
Symbols.
+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) ]
+Returns (string | symbol)[]
Since
close
post
value is transferred in a way which is compatible with
+the HTML structured clone algorithm.JSON are:
+
+value may contain circular references.value may contain instances of builtin JS types such as RegExps,BigInts, Maps, Sets, etc.value may contain typed arrays, both using ArrayBuffers
+and SharedArrayBuffers.value may contain WebAssembly.Module instances.value may not contain native (C++-backed) objects other than:
+const { MessageChannel } = require('worker_threads');
const { port1, port2 } = new MessageChannel();
port1.on('message', (message) => console.log(message));
const circularData = {};
circularData.foo = circularData;
// Prints: { foo: [Circular] }
port2.postMessage(circularData);
+transferList may be a list of ArrayBuffer, MessagePort and FileHandle objects.
+After transferring, they are not usable on the sending side of the channel
+anymore (even if they are not contained in value). Unlike with child processes, transferring handles such as network sockets is currently
+not supported.value contains SharedArrayBuffer instances, those are accessible
+from either thread. They cannot be listed in transferList.value may still contain ArrayBuffer instances that are not intransferList; in that case, the underlying memory is copied rather than moved.
+const { MessageChannel } = require('worker_threads');
const { port1, port2 } = new MessageChannel();
port1.on('message', (message) => console.log(message));
const uint8Array = new Uint8Array([ 1, 2, 3, 4 ]);
// This posts a copy of `uint8Array`:
port2.postMessage(uint8Array);
// This does not copy data, but renders `uint8Array` unusable:
port2.postMessage(uint8Array, [ uint8Array.buffer ]);
// The memory for the `sharedUint8Array` is accessible from both the
// original and the copy received by `.on('message')`:
const sharedUint8Array = new Uint8Array(new SharedArrayBuffer(4));
port2.postMessage(sharedUint8Array);
// This transfers a freshly created message port to the receiver.
// This can be used, for example, to create communication channels between
// multiple `Worker` threads that are children of the same parent thread.
const otherChannel = new MessageChannel();
port2.postMessage({ port: otherChannel.port1 }, [ otherChannel.port1 ]);
+serialization API of the v8 module.Parameters
Optional transferList: readonly TransferListItem[]Returns void
Since
ref
unref(). Calling ref() on a previously unref()ed port does not let the program exit if it's the only active handle left (the default
+behavior). If the port is ref()ed, calling ref() again has no effect..on('message'), the port
+is ref()ed and unref()ed automatically depending on whether
+listeners for the event exist.Returns void
Since
unref
unref() on a port allows the thread to exit if this is the only
+active handle in the event system. If the port is already unref()ed callingunref() again has no effect..on('message'), the port isref()ed and unref()ed automatically depending on whether
+listeners for the event exist.Returns void
Since
start
MessagePort. When using this port
+as an event emitter, this is called automatically once 'message'listeners are attached.MessagePort API. In Node.js,
+it is only useful for ignoring messages when no event listener is present.
+Node.js also diverges in its handling of .onmessage. Setting it
+automatically calls .start(), but unsetting it lets messages queue up
+until a new handler is set or the port is discarded.Returns void
Since
add
emitter.on(eventName, listener).Parameters
Returns void
Returns this
Since
Parameters
Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
Parameters
Parameters
Rest ...args: any[]Returns void
Returns this
emit
eventName, in the order they were registered, passing the supplied arguments
+to each.true if the event had listeners, false otherwise.
+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
+Parameters
Returns boolean
Since
Parameters
Returns boolean
Parameters
Returns boolean
Parameters
Rest ...args: any[]Returns boolean
on
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 eventNameand listener will result in the listener being added, and called, multiple
+times.
+server.on('connection', (stream) => {
console.log('someone connected!');
});
+EventEmitter, so that calls can be chained.emitter.prependListener() method can be used as an alternative to add the
+event listener to the beginning of the listeners array.
+const myEE = new EventEmitter();
myEE.on('foo', () => console.log('a'));
myEE.prependListener('foo', () => console.log('b'));
myEE.emit('foo');
// Prints:
// b
// a
+Parameters
Returns void
Returns this
Since
Parameters
Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
Parameters
Parameters
Rest ...args: any[]Returns void
Returns this
once
listener function for the event named eventName. The
+next time eventName is triggered, this listener is removed and then invoked.
+server.once('connection', (stream) => {
console.log('Ah, we have our first user!');
});
+EventEmitter, so that calls can be chained.emitter.prependOnceListener() method can be used as an alternative to add the
+event listener to the beginning of the listeners array.
+const myEE = new EventEmitter();
myEE.once('foo', () => console.log('a'));
myEE.prependOnceListener('foo', () => console.log('b'));
myEE.emit('foo');
// Prints:
// b
// a
+Parameters
Returns void
Returns this
Since
Parameters
Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
Parameters
Parameters
Rest ...args: any[]Returns void
Returns this
prepend
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 eventNameand listener will result in the listener being added, and called, multiple
+times.
+server.prependListener('connection', (stream) => {
console.log('someone connected!');
});
+EventEmitter, so that calls can be chained.Parameters
Returns void
Returns this
Since
Parameters
Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
Parameters
Parameters
Rest ...args: any[]Returns void
Returns this
prepend
listener function for the event named eventName to the beginning of the listeners array. The next time eventName is triggered, this
+listener is removed, and then invoked.
+server.prependOnceListener('connection', (stream) => {
console.log('Ah, we have our first user!');
});
+EventEmitter, so that calls can be chained.Parameters
Returns void
Returns this
Since
Parameters
Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
Parameters
Parameters
Rest ...args: any[]Returns void
Returns this
remove
listener from the listener array for the event namedeventName.
+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.removeListener() or removeAllListeners() calls after emitting and before the last listener finishes execution
+will not remove them fromemit() in progress. Subsequent events behave as expected.
+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
+emitter.listeners() method will need to be recreated.removeListener() will remove the most
+recently added instance. In the example the once('ping')listener is removed:
+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');
+EventEmitter, so that calls can be chained.Parameters
Returns void
Returns this
Since
Parameters
Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
Parameters
Parameters
Rest ...args: any[]Returns void
Returns this
off
emitter.removeListener().Parameters
Returns void
Returns this
Since
Parameters
Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
Parameters
Parameters
Rest ...args: any[]Returns void
Returns this
Class ReadStream
fs.ReadStream are created and returned using the createReadStream function.Since
Hierarchy (view full)
Index
Constructors
Properties
Methods
Constructors
constructor
Parameters
Optional opts: ReadableOptionsReturns ReadStream
Properties
Static Readonly error'error'
+events. Listeners installed using this symbol are called before the regular
+'error' listeners are called.'error' event is emitted, therefore the process will still crash if no
+regular 'error' listener is installed.Static Readonly captureStatic captureStatic defaultbytes
Since
path
fs.createReadStream(). If path is passed as a string, thenreadStream.path will be a string. If path is passed as a Buffer, thenreadStream.path will be a
+Buffer. If fd is specified, thenreadStream.path will be undefined.Since
pending
true if the underlying file has not been opened yet,
+i.e. before the 'ready' event is emitted.Since
Readonly Experimental readable'end'.Since
readable
true if it is safe to call readable.read(), which means
+the stream has not been destroyed or emitted 'error' or 'end'.Since
Readonly Experimental readable'data' has been emitted.Since
Readonly readableencoding of a given Readable stream. The encodingproperty can be set using the readable.setEncoding() method.Since
Readonly readabletrue when 'end' event is emitted.Since
Readonly readableReadable stream as described
+in the Three states section.Since
Readonly readablehighWaterMark passed when creating this Readable.Since
Readonly readablehighWaterMark.Since
Readonly readableobjectMode of a given Readable stream.Since
destroyed
true after readable.destroy() has been called.Since
Readonly closedSince
Readonly erroredSince
Methods
Optional [captureStatic oncePromise 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.'error' event
+semantics and does not listen to the 'error' event.
+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();
+'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:
+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
+AbortSignal can be used to cancel waiting for the event:
+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!
+Parameters
Optional options: StaticEventEmitterOptionsReturns Promise<any[]>
Since
Parameters
Optional options: StaticEventEmitterOptionsReturns Promise<any[]>
Static on
+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
})();
+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.AbortSignal can be used to cancel waiting on events:
+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());
+Parameters
Optional options: StaticEventEmitterOptionsReturns AsyncIterableIterator<any>
eventName events emitted by the emitterSince
Static listenereventNameregistered on the given emitter.
+const { EventEmitter, listenerCount } = require('events');
const myEmitter = new EventEmitter();
myEmitter.on('event', () => {});
myEmitter.on('event', () => {});
console.log(listenerCount(myEmitter, 'event'));
// Prints: 2
+Parameters
Returns number
Since
Deprecated
listenerCount instead.Static geteventName.EventEmitters this behaves exactly the same as calling .listeners on
+the emitter.EventTargets this is the only way to get the event listeners for the
+event target. This is useful for debugging and diagnostic purposes.
+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]
}
+Parameters
Returns Function[]
Since
Static getEventEmitters this behaves exactly the same as calling .getMaxListeners on
+the emitter.EventTargets this is the only way to get the max event listeners for the
+event target. If the number of event handlers on a single EventTarget exceeds
+the max set, the EventTarget will print a warning.
+import { getMaxListeners, setMaxListeners, EventEmitter } from 'node:events';
{
const ee = new EventEmitter();
console.log(getMaxListeners(ee)); // 10
setMaxListeners(11, ee);
console.log(getMaxListeners(ee)); // 11
}
{
const et = new EventTarget();
console.log(getMaxListeners(et)); // 10
setMaxListeners(11, et);
console.log(getMaxListeners(et)); // 11
}
+Parameters
Returns number
Since
Static set
+const {
setMaxListeners,
EventEmitter
} = require('events');
const target = new EventTarget();
const emitter = new EventEmitter();
setMaxListeners(5, target, emitter);
+Parameters
Optional n: numberEventTarget event.Rest ...eventTargets: (EventEmitter<DefaultEventMap> | _DOMEventTarget)[]Returns void
Since
Static addExperimental abort event on the provided signal.abort event on abort signals is unsafe and may
+lead to resource leaks since another third party with the signal can
+call e.stopImmediatePropagation(). Unfortunately Node.js cannot change
+this since it would violate the web standard. Additionally, the original
+API makes it easy to forget to remove listeners.AbortSignals in Node.js APIs by solving these
+two issues by listening to the event such that stopImmediatePropagation does
+not prevent the listener from running.
+import { addAbortListener } from 'node:events';
function example(signal) {
let disposable;
try {
signal.addEventListener('abort', (e) => e.stopImmediatePropagation());
disposable = addAbortListener(signal, (e) => {
// Do something when signal is aborted.
});
} finally {
disposable?.[Symbol.dispose]();
}
}
+Parameters
Parameters
Returns void
Returns Disposable
abort listener.Since
off
emitter.removeListener().Type Parameters
Parameters
Parameters
Rest ...args: any[]Returns void
Returns this
Since
remove
eventName.EventEmitter instance was created by some other
+component or module (e.g. sockets or file streams).EventEmitter, so that calls can be chained.Parameters
Optional event: string | symbolReturns this
Since
set
EventEmitters will print a warning if more than 10 listeners are
+added for a particular event. This is a useful default that helps finding
+memory leaks. The emitter.setMaxListeners() method allows the limit to be
+modified for this specific EventEmitter instance. The value can be set toInfinity (or 0) to indicate an unlimited number of listeners.EventEmitter, so that calls can be chained.Parameters
Returns this
Since
get
EventEmitter which is either
+set by emitter.setMaxListeners(n) or defaults to defaultMaxListeners.Returns number
Since
listeners
eventName.
+server.on('connection', (stream) => {
console.log('someone connected!');
});
console.log(util.inspect(server.listeners('connection')));
// Prints: [ [Function] ]
+Type Parameters
Parameters
Returns Function[]
Since
raw
eventName,
+including any wrappers (such as those created by .once()).
+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');
+Type Parameters
Parameters
Returns Function[]
Since
listener
eventName.listener is provided, it will return how many times the listener
+is found in the list of the listeners of the event.Type Parameters
Parameters
Optional listener: FunctionReturns number
Since
event
Symbols.
+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) ]
+Returns (string | symbol)[]
Since
close
Parameters
Optional callback: ((err?) => void)Parameters
Optional err: ErrnoExceptionReturns void
Returns void
add
+
+Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Parameters
Rest ...args: any[]Returns void
Returns this
on
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 eventNameand listener will result in the listener being added, and called, multiple
+times.
+server.on('connection', (stream) => {
console.log('someone connected!');
});
+EventEmitter, so that calls can be chained.emitter.prependListener() method can be used as an alternative to add the
+event listener to the beginning of the listeners array.
+const myEE = new EventEmitter();
myEE.on('foo', () => console.log('a'));
myEE.prependListener('foo', () => console.log('b'));
myEE.emit('foo');
// Prints:
// b
// a
+Parameters
Returns void
Returns this
Since
Parameters
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Parameters
Rest ...args: any[]Returns void
Returns this
once
listener function for the event named eventName. The
+next time eventName is triggered, this listener is removed and then invoked.
+server.once('connection', (stream) => {
console.log('Ah, we have our first user!');
});
+EventEmitter, so that calls can be chained.emitter.prependOnceListener() method can be used as an alternative to add the
+event listener to the beginning of the listeners array.
+const myEE = new EventEmitter();
myEE.once('foo', () => console.log('a'));
myEE.prependOnceListener('foo', () => console.log('b'));
myEE.emit('foo');
// Prints:
// b
// a
+Parameters
Returns void
Returns this
Since
Parameters
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Parameters
Rest ...args: any[]Returns void
Returns this
prepend
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 eventNameand listener will result in the listener being added, and called, multiple
+times.
+server.prependListener('connection', (stream) => {
console.log('someone connected!');
});
+EventEmitter, so that calls can be chained.Parameters
Returns void
Returns this
Since
Parameters
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Parameters
Rest ...args: any[]Returns void
Returns this
prepend
listener function for the event named eventName to the beginning of the listeners array. The next time eventName is triggered, this
+listener is removed, and then invoked.
+server.prependOnceListener('connection', (stream) => {
console.log('Ah, we have our first user!');
});
+EventEmitter, so that calls can be chained.Parameters
Returns void
Returns this
Since
Parameters
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Parameters
Rest ...args: any[]Returns void
Returns this
pipe
Type Parameters
Parameters
Optional options: {
end?: boolean;
}Optional end?: booleanReturns T
compose
Type Parameters
Parameters
Optional options: {
signal: AbortSignal;
}signal: AbortSignal
Returns T
Static fromParameters
Optional options: ReadableOptionsReturns Readable
Static fromExperimental Readable from a web ReadableStream.Parameters
Optional options: Pick<ReadableOptions, "encoding" | "highWaterMark" | "objectMode" | "signal">Returns Readable
Since
Static isParameters
Returns boolean
Since
Static toExperimental ReadableStream from a Readable.Parameters
Returns ReadableStream<any>
Since
Optional _construct_read
read
readable.read() method reads data out of the internal buffer and
+returns it. If no data is available to be read, null is returned. By default,
+the data is returned as a Buffer object unless an encoding has been
+specified using the readable.setEncoding() method or the stream is operating
+in object mode.size argument specifies a specific number of bytes to read. Ifsize 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.size argument is not specified, all of the data contained in the
+internal buffer will be returned.size argument must be less than or equal to 1 GiB.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.
+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.');
});
+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.readable, it is necessary
+to collect chunks across multiple 'readable' events:
+const chunks = [];
readable.on('readable', () => {
let chunk;
while (null !== (chunk = readable.read())) {
chunks.push(chunk);
}
});
readable.on('end', () => {
const content = chunks.join('');
});
+Readable stream in object mode will always return a single item from
+a call to readable.read(size), regardless of the value of thesize argument.readable.read() method returns a chunk of data, a 'data' event will
+also be emitted.'end' event has
+been emitted will return null. No runtime error will be raised.Parameters
Optional size: numberReturns any
Since
set
readable.setEncoding() method sets the character encoding for
+data read from the Readable stream.Buffer objects. Setting an encoding causes the stream data
+to be returned as strings of the specified encoding rather than as Bufferobjects. For instance, calling readable.setEncoding('utf8') will cause the
+output data to be interpreted as UTF-8 data, and passed as strings. Callingreadable.setEncoding('hex') will cause the data to be encoded in hexadecimal
+string format.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.
+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);
});
+Parameters
Returns this
Since
pause
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.
+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);
});
+readable.pause() method has no effect if there is a 'readable'event listener.Returns this
Since
resume
readable.resume() method causes an explicitly paused Readable stream to
+resume emitting 'data' events, switching the stream into flowing mode.readable.resume() method can be used to fully consume the data from a
+stream without actually processing any of that data:
+getReadableStreamSomehow()
.resume()
.on('end', () => {
console.log('Reached the end, but did not read anything.');
});
+readable.resume() method has no effect if there is a 'readable'event listener.Returns this
Since
is
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.
+const readable = new stream.Readable();
readable.isPaused(); // === false
readable.pause();
readable.isPaused(); // === true
readable.resume();
readable.isPaused(); // === false
+Returns boolean
Since
unpipe
readable.unpipe() method detaches a Writable stream previously attached
+using the pipe method.destination is not specified, then all pipes are detached.destination is specified, but no pipe is set up for it, then
+the method does nothing.
+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);
+Parameters
Optional destination: WritableStreamReturns this
Since
unshift
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.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.stream.unshift(chunk) method cannot be called after the 'end' event
+has been emitted or a runtime error will be thrown.stream.unshift() often should consider switching to
+use of a Transform stream instead. See the API for stream implementers section for more information.
+// 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.includes('\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);
return;
}
// Still reading the header.
header += str;
}
}
}
+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 _read implementation on a
+custom stream). Following the call to readable.unshift() with an immediate 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.Parameters
chunk must be a string, Buffer, Uint8Array or null. For object mode
+streams, chunk may be any JavaScript value.Optional encoding: BufferEncodingBuffer encoding, such as 'utf8' or 'ascii'.Returns void
Since
wrap
stream module API
+as it is currently defined. (See Compatibility for more information.)'data' events and has a pause method that is advisory only, thereadable.wrap() method can be used to create a Readable
+stream that uses
+the old stream as its data source.readable.wrap() but the method has been
+provided as a convenience for interacting with older Node.js applications and
+libraries.
+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.
});
+Parameters
Returns this
Since
push
Parameters
Optional encoding: BufferEncodingReturns boolean
iterator
for await...of loop is exited by return, break, or throw,
+or if the iterator should destroy the stream if the stream emitted an error during iteration.Parameters
Optional options: {
destroyOnReturn?: boolean;
}Optional destroyfalse, calling return on the async iterator,
+or exiting a for await...of iteration using a break, return, or throw will not destroy the stream.
+Default: true.Returns AsyncIterableIterator<any>
Since
map
awaited before being passed to the result stream.Parameters
Parameters
Optional options: Pick<ArrayOptions, "signal">Returns any
Optional options: ArrayOptionsReturns Readable
Since
filter
awaited.Parameters
Parameters
Optional options: Pick<ArrayOptions, "signal">Returns boolean | Promise<boolean>
Optional options: ArrayOptionsReturns Readable
Since
for
awaited.for await...of loops in that it can optionally process chunks concurrently.
+In addition, a forEach iteration can only be stopped by having passed a signal option
+and aborting the related AbortController while for await...of can be stopped with break or return.
+In either case the stream will be destroyed.'data' event in that it uses the readable event
+in the underlying machinary and can limit the number of concurrent fn calls.Parameters
Parameters
Optional options: Pick<ArrayOptions, "signal">Returns void | Promise<void>
Optional options: ArrayOptionsReturns Promise<void>
Since
to
Parameters
Optional options: Pick<ArrayOptions, "signal">Returns Promise<any[]>
Since
some
Array.prototype.some and calls fn on each chunk in the stream
+until the awaited return value is true (or any truthy value). Once an fn call on a chunk
+awaited return value is truthy, the stream is destroyed and the promise is fulfilled with true.
+If none of the fn calls on the chunks return a truthy value, the promise is fulfilled with false.Parameters
Parameters
Optional options: Pick<ArrayOptions, "signal">Returns boolean | Promise<boolean>
Optional options: ArrayOptionsReturns Promise<boolean>
true if fn returned a truthy value for at least one of the chunks.Since
find
Array.prototype.find and calls fn on each chunk in the stream
+to find a chunk with a truthy value for fn. Once an fn call's awaited return value is truthy,
+the stream is destroyed and the promise is fulfilled with value for which fn returned a truthy value.
+If all of the fn calls on the chunks return a falsy value, the promise is fulfilled with undefined.Type Parameters
Parameters
Parameters
Optional options: Pick<ArrayOptions, "signal">Returns data is T
Optional options: ArrayOptionsReturns Promise<T>
undefined if no element was found.Since
Parameters
Parameters
Optional options: Pick<ArrayOptions, "signal">Returns boolean | Promise<boolean>
Optional options: ArrayOptionsReturns Promise<any>
every
Array.prototype.every and calls fn on each chunk in the stream
+to check if all awaited return values are truthy value for fn. Once an fn call on a chunk
+awaited return value is falsy, the stream is destroyed and the promise is fulfilled with false.
+If all of the fn calls on the chunks return a truthy value, the promise is fulfilled with true.Parameters
Parameters
Optional options: Pick<ArrayOptions, "signal">Returns boolean | Promise<boolean>
Optional options: ArrayOptionsReturns Promise<boolean>
true if fn returned a truthy value for every one of the chunks.Since
flat
Parameters
Parameters
Optional options: Pick<ArrayOptions, "signal">Returns any
Optional options: ArrayOptionsReturns Readable
Since
drop
Parameters
Optional options: Pick<ArrayOptions, "signal">Returns Readable
Since
take
Parameters
Optional options: Pick<ArrayOptions, "signal">Returns Readable
Since
as
[index, chunk]. The first index value is 0 and it increases by 1 for each chunk produced.Parameters
Optional options: Pick<ArrayOptions, "signal">Returns Readable
Since
reduce
TypeError with the ERR_INVALID_ARGS code property.readable.map method.Type Parameters
Parameters
Parameters
Optional options: Pick<ArrayOptions, "signal">Returns T
Optional initial: undefinedOptional options: Pick<ArrayOptions, "signal">Returns Promise<T>
Since
Type Parameters
Parameters
Parameters
Optional options: Pick<ArrayOptions, "signal">Returns T
Optional options: Pick<ArrayOptions, "signal">Returns Promise<T>
_destroy
destroy
'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.destroy() has been called any further calls will be a no-op and no
+further errors except from _destroy() may be emitted as 'error'.readable._destroy().Parameters
Optional error: Error'error' eventReturns this
Since
emit
eventName, in the order they were registered, passing the supplied arguments
+to each.true if the event had listeners, false otherwise.
+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
+Parameters
Returns boolean
Since
Parameters
Returns boolean
Parameters
Returns boolean
Parameters
Returns boolean
Parameters
Returns boolean
Parameters
Returns boolean
Parameters
Returns boolean
Parameters
Rest ...args: any[]Returns boolean
remove
listener from the listener array for the event namedeventName.
+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.removeListener() or removeAllListeners() calls after emitting and before the last listener finishes execution
+will not remove them fromemit() in progress. Subsequent events behave as expected.
+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
+emitter.listeners() method will need to be recreated.removeListener() will remove the most
+recently added instance. In the example the once('ping')listener is removed:
+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');
+EventEmitter, so that calls can be chained.Parameters
Returns void
Returns this
Since
Parameters
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Parameters
Rest ...args: any[]Returns void
Returns this
[async
Returns AsyncIterableIterator<any>
[async
Class Readable
Since
Hierarchy (view full)
Implements
Index
Constructors
Properties
Methods
Constructors
constructor
Parameters
Optional opts: ReadableOptionsReturns Readable
Properties
Static Readonly error'error'
+events. Listeners installed using this symbol are called before the regular
+'error' listeners are called.'error' event is emitted, therefore the process will still crash if no
+regular 'error' listener is installed.Static Readonly captureStatic captureStatic defaultReadonly Experimental readable'end'.Since
readable
true if it is safe to call readable.read(), which means
+the stream has not been destroyed or emitted 'error' or 'end'.Since
Readonly Experimental readable'data' has been emitted.Since
Readonly readableencoding of a given Readable stream. The encodingproperty can be set using the readable.setEncoding() method.Since
Readonly readabletrue when 'end' event is emitted.Since
Readonly readableReadable stream as described
+in the Three states section.Since
Readonly readablehighWaterMark passed when creating this Readable.Since
Readonly readablehighWaterMark.Since
Readonly readableobjectMode of a given Readable stream.Since
destroyed
true after readable.destroy() has been called.Since
Readonly closedSince
Readonly erroredSince
Methods
Optional [captureStatic oncePromise 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.'error' event
+semantics and does not listen to the 'error' event.
+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();
+'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:
+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
+AbortSignal can be used to cancel waiting for the event:
+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!
+Parameters
Optional options: StaticEventEmitterOptionsReturns Promise<any[]>
Since
Parameters
Optional options: StaticEventEmitterOptionsReturns Promise<any[]>
Static on
+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
})();
+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.AbortSignal can be used to cancel waiting on events:
+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());
+Parameters
Optional options: StaticEventEmitterOptionsReturns AsyncIterableIterator<any>
eventName events emitted by the emitterSince
Static listenereventNameregistered on the given emitter.
+const { EventEmitter, listenerCount } = require('events');
const myEmitter = new EventEmitter();
myEmitter.on('event', () => {});
myEmitter.on('event', () => {});
console.log(listenerCount(myEmitter, 'event'));
// Prints: 2
+Parameters
Returns number
Since
Deprecated
listenerCount instead.Static geteventName.EventEmitters this behaves exactly the same as calling .listeners on
+the emitter.EventTargets this is the only way to get the event listeners for the
+event target. This is useful for debugging and diagnostic purposes.
+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]
}
+Parameters
Returns Function[]
Since
Static getEventEmitters this behaves exactly the same as calling .getMaxListeners on
+the emitter.EventTargets this is the only way to get the max event listeners for the
+event target. If the number of event handlers on a single EventTarget exceeds
+the max set, the EventTarget will print a warning.
+import { getMaxListeners, setMaxListeners, EventEmitter } from 'node:events';
{
const ee = new EventEmitter();
console.log(getMaxListeners(ee)); // 10
setMaxListeners(11, ee);
console.log(getMaxListeners(ee)); // 11
}
{
const et = new EventTarget();
console.log(getMaxListeners(et)); // 10
setMaxListeners(11, et);
console.log(getMaxListeners(et)); // 11
}
+Parameters
Returns number
Since
Static set
+const {
setMaxListeners,
EventEmitter
} = require('events');
const target = new EventTarget();
const emitter = new EventEmitter();
setMaxListeners(5, target, emitter);
+Parameters
Optional n: numberEventTarget event.Rest ...eventTargets: (EventEmitter<DefaultEventMap> | _DOMEventTarget)[]Returns void
Since
Static addExperimental abort event on the provided signal.abort event on abort signals is unsafe and may
+lead to resource leaks since another third party with the signal can
+call e.stopImmediatePropagation(). Unfortunately Node.js cannot change
+this since it would violate the web standard. Additionally, the original
+API makes it easy to forget to remove listeners.AbortSignals in Node.js APIs by solving these
+two issues by listening to the event such that stopImmediatePropagation does
+not prevent the listener from running.
+import { addAbortListener } from 'node:events';
function example(signal) {
let disposable;
try {
signal.addEventListener('abort', (e) => e.stopImmediatePropagation());
disposable = addAbortListener(signal, (e) => {
// Do something when signal is aborted.
});
} finally {
disposable?.[Symbol.dispose]();
}
}
+Parameters
Parameters
Returns void
Returns Disposable
abort listener.Since
off
emitter.removeListener().Type Parameters
Parameters
Parameters
Rest ...args: any[]Returns void
Returns this
Since
remove
eventName.EventEmitter instance was created by some other
+component or module (e.g. sockets or file streams).EventEmitter, so that calls can be chained.Parameters
Optional event: string | symbolReturns this
Since
set
EventEmitters will print a warning if more than 10 listeners are
+added for a particular event. This is a useful default that helps finding
+memory leaks. The emitter.setMaxListeners() method allows the limit to be
+modified for this specific EventEmitter instance. The value can be set toInfinity (or 0) to indicate an unlimited number of listeners.EventEmitter, so that calls can be chained.Parameters
Returns this
Since
get
EventEmitter which is either
+set by emitter.setMaxListeners(n) or defaults to defaultMaxListeners.Returns number
Since
listeners
eventName.
+server.on('connection', (stream) => {
console.log('someone connected!');
});
console.log(util.inspect(server.listeners('connection')));
// Prints: [ [Function] ]
+Type Parameters
Parameters
Returns Function[]
Since
raw
eventName,
+including any wrappers (such as those created by .once()).
+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');
+Type Parameters
Parameters
Returns Function[]
Since
listener
eventName.listener is provided, it will return how many times the listener
+is found in the list of the listeners of the event.Type Parameters
Parameters
Optional listener: FunctionReturns number
Since
event
Symbols.
+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) ]
+Returns (string | symbol)[]
Since
pipe
Type Parameters
Parameters
Optional options: {
end?: boolean;
}Optional end?: booleanReturns T
compose
Type Parameters
Parameters
Optional options: {
signal: AbortSignal;
}signal: AbortSignal
Returns T
Static fromParameters
Optional options: ReadableOptionsReturns Readable
Static fromExperimental Readable from a web ReadableStream.Parameters
Optional options: Pick<ReadableOptions, "encoding" | "highWaterMark" | "objectMode" | "signal">Returns Readable
Since
Static isParameters
Returns boolean
Since
Static toExperimental ReadableStream from a Readable.Parameters
Returns ReadableStream<any>
Since
Optional _construct_read
read
readable.read() method reads data out of the internal buffer and
+returns it. If no data is available to be read, null is returned. By default,
+the data is returned as a Buffer object unless an encoding has been
+specified using the readable.setEncoding() method or the stream is operating
+in object mode.size argument specifies a specific number of bytes to read. Ifsize 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.size argument is not specified, all of the data contained in the
+internal buffer will be returned.size argument must be less than or equal to 1 GiB.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.
+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.');
});
+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.readable, it is necessary
+to collect chunks across multiple 'readable' events:
+const chunks = [];
readable.on('readable', () => {
let chunk;
while (null !== (chunk = readable.read())) {
chunks.push(chunk);
}
});
readable.on('end', () => {
const content = chunks.join('');
});
+Readable stream in object mode will always return a single item from
+a call to readable.read(size), regardless of the value of thesize argument.readable.read() method returns a chunk of data, a 'data' event will
+also be emitted.'end' event has
+been emitted will return null. No runtime error will be raised.Parameters
Optional size: numberReturns any
Since
set
readable.setEncoding() method sets the character encoding for
+data read from the Readable stream.Buffer objects. Setting an encoding causes the stream data
+to be returned as strings of the specified encoding rather than as Bufferobjects. For instance, calling readable.setEncoding('utf8') will cause the
+output data to be interpreted as UTF-8 data, and passed as strings. Callingreadable.setEncoding('hex') will cause the data to be encoded in hexadecimal
+string format.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.
+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);
});
+Parameters
Returns this
Since
pause
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.
+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);
});
+readable.pause() method has no effect if there is a 'readable'event listener.Returns this
Since
resume
readable.resume() method causes an explicitly paused Readable stream to
+resume emitting 'data' events, switching the stream into flowing mode.readable.resume() method can be used to fully consume the data from a
+stream without actually processing any of that data:
+getReadableStreamSomehow()
.resume()
.on('end', () => {
console.log('Reached the end, but did not read anything.');
});
+readable.resume() method has no effect if there is a 'readable'event listener.Returns this
Since
is
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.
+const readable = new stream.Readable();
readable.isPaused(); // === false
readable.pause();
readable.isPaused(); // === true
readable.resume();
readable.isPaused(); // === false
+Returns boolean
Since
unpipe
readable.unpipe() method detaches a Writable stream previously attached
+using the pipe method.destination is not specified, then all pipes are detached.destination is specified, but no pipe is set up for it, then
+the method does nothing.
+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);
+Parameters
Optional destination: WritableStreamReturns this
Since
unshift
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.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.stream.unshift(chunk) method cannot be called after the 'end' event
+has been emitted or a runtime error will be thrown.stream.unshift() often should consider switching to
+use of a Transform stream instead. See the API for stream implementers section for more information.
+// 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.includes('\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);
return;
}
// Still reading the header.
header += str;
}
}
}
+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 _read implementation on a
+custom stream). Following the call to readable.unshift() with an immediate 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.Parameters
chunk must be a string, Buffer, Uint8Array or null. For object mode
+streams, chunk may be any JavaScript value.Optional encoding: BufferEncodingBuffer encoding, such as 'utf8' or 'ascii'.Returns void
Since
wrap
stream module API
+as it is currently defined. (See Compatibility for more information.)'data' events and has a pause method that is advisory only, thereadable.wrap() method can be used to create a Readable
+stream that uses
+the old stream as its data source.readable.wrap() but the method has been
+provided as a convenience for interacting with older Node.js applications and
+libraries.
+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.
});
+Parameters
Returns this
Since
push
Parameters
Optional encoding: BufferEncodingReturns boolean
iterator
for await...of loop is exited by return, break, or throw,
+or if the iterator should destroy the stream if the stream emitted an error during iteration.Parameters
Optional options: {
destroyOnReturn?: boolean;
}Optional destroyfalse, calling return on the async iterator,
+or exiting a for await...of iteration using a break, return, or throw will not destroy the stream.
+Default: true.Returns AsyncIterableIterator<any>
Since
map
awaited before being passed to the result stream.Parameters
Parameters
Optional options: Pick<ArrayOptions, "signal">Returns any
Optional options: ArrayOptionsReturns Readable
Since
filter
awaited.Parameters
Parameters
Optional options: Pick<ArrayOptions, "signal">Returns boolean | Promise<boolean>
Optional options: ArrayOptionsReturns Readable
Since
for
awaited.for await...of loops in that it can optionally process chunks concurrently.
+In addition, a forEach iteration can only be stopped by having passed a signal option
+and aborting the related AbortController while for await...of can be stopped with break or return.
+In either case the stream will be destroyed.'data' event in that it uses the readable event
+in the underlying machinary and can limit the number of concurrent fn calls.Parameters
Parameters
Optional options: Pick<ArrayOptions, "signal">Returns void | Promise<void>
Optional options: ArrayOptionsReturns Promise<void>
Since
to
Parameters
Optional options: Pick<ArrayOptions, "signal">Returns Promise<any[]>
Since
some
Array.prototype.some and calls fn on each chunk in the stream
+until the awaited return value is true (or any truthy value). Once an fn call on a chunk
+awaited return value is truthy, the stream is destroyed and the promise is fulfilled with true.
+If none of the fn calls on the chunks return a truthy value, the promise is fulfilled with false.Parameters
Parameters
Optional options: Pick<ArrayOptions, "signal">Returns boolean | Promise<boolean>
Optional options: ArrayOptionsReturns Promise<boolean>
true if fn returned a truthy value for at least one of the chunks.Since
find
Array.prototype.find and calls fn on each chunk in the stream
+to find a chunk with a truthy value for fn. Once an fn call's awaited return value is truthy,
+the stream is destroyed and the promise is fulfilled with value for which fn returned a truthy value.
+If all of the fn calls on the chunks return a falsy value, the promise is fulfilled with undefined.Type Parameters
Parameters
Parameters
Optional options: Pick<ArrayOptions, "signal">Returns data is T
Optional options: ArrayOptionsReturns Promise<T>
undefined if no element was found.Since
Parameters
Parameters
Optional options: Pick<ArrayOptions, "signal">Returns boolean | Promise<boolean>
Optional options: ArrayOptionsReturns Promise<any>
every
Array.prototype.every and calls fn on each chunk in the stream
+to check if all awaited return values are truthy value for fn. Once an fn call on a chunk
+awaited return value is falsy, the stream is destroyed and the promise is fulfilled with false.
+If all of the fn calls on the chunks return a truthy value, the promise is fulfilled with true.Parameters
Parameters
Optional options: Pick<ArrayOptions, "signal">Returns boolean | Promise<boolean>
Optional options: ArrayOptionsReturns Promise<boolean>
true if fn returned a truthy value for every one of the chunks.Since
flat
Parameters
Parameters
Optional options: Pick<ArrayOptions, "signal">Returns any
Optional options: ArrayOptionsReturns Readable
Since
drop
Parameters
Optional options: Pick<ArrayOptions, "signal">Returns Readable
Since
take
Parameters
Optional options: Pick<ArrayOptions, "signal">Returns Readable
Since
as
[index, chunk]. The first index value is 0 and it increases by 1 for each chunk produced.Parameters
Optional options: Pick<ArrayOptions, "signal">Returns Readable
Since
reduce
TypeError with the ERR_INVALID_ARGS code property.readable.map method.Type Parameters
Parameters
Parameters
Optional options: Pick<ArrayOptions, "signal">Returns T
Optional initial: undefinedOptional options: Pick<ArrayOptions, "signal">Returns Promise<T>
Since
Type Parameters
Parameters
Parameters
Optional options: Pick<ArrayOptions, "signal">Returns T
Optional options: Pick<ArrayOptions, "signal">Returns Promise<T>
_destroy
destroy
'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.destroy() has been called any further calls will be a no-op and no
+further errors except from _destroy() may be emitted as 'error'.readable._destroy().Parameters
Optional error: Error'error' eventReturns this
Since
add
+
+Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Parameters
Rest ...args: any[]Returns void
Returns this
emit
eventName, in the order they were registered, passing the supplied arguments
+to each.true if the event had listeners, false otherwise.
+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
+Parameters
Returns boolean
Since
Parameters
Returns boolean
Parameters
Returns boolean
Parameters
Returns boolean
Parameters
Returns boolean
Parameters
Returns boolean
Parameters
Returns boolean
Parameters
Rest ...args: any[]Returns boolean
on
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 eventNameand listener will result in the listener being added, and called, multiple
+times.
+server.on('connection', (stream) => {
console.log('someone connected!');
});
+EventEmitter, so that calls can be chained.emitter.prependListener() method can be used as an alternative to add the
+event listener to the beginning of the listeners array.
+const myEE = new EventEmitter();
myEE.on('foo', () => console.log('a'));
myEE.prependListener('foo', () => console.log('b'));
myEE.emit('foo');
// Prints:
// b
// a
+Parameters
Returns void
Returns this
Since
Parameters
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Parameters
Rest ...args: any[]Returns void
Returns this
once
listener function for the event named eventName. The
+next time eventName is triggered, this listener is removed and then invoked.
+server.once('connection', (stream) => {
console.log('Ah, we have our first user!');
});
+EventEmitter, so that calls can be chained.emitter.prependOnceListener() method can be used as an alternative to add the
+event listener to the beginning of the listeners array.
+const myEE = new EventEmitter();
myEE.once('foo', () => console.log('a'));
myEE.prependOnceListener('foo', () => console.log('b'));
myEE.emit('foo');
// Prints:
// b
// a
+Parameters
Returns void
Returns this
Since
Parameters
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Parameters
Rest ...args: any[]Returns void
Returns this
prepend
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 eventNameand listener will result in the listener being added, and called, multiple
+times.
+server.prependListener('connection', (stream) => {
console.log('someone connected!');
});
+EventEmitter, so that calls can be chained.Parameters
Returns void
Returns this
Since
Parameters
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Parameters
Rest ...args: any[]Returns void
Returns this
prepend
listener function for the event named eventName to the beginning of the listeners array. The next time eventName is triggered, this
+listener is removed, and then invoked.
+server.prependOnceListener('connection', (stream) => {
console.log('Ah, we have our first user!');
});
+EventEmitter, so that calls can be chained.Parameters
Returns void
Returns this
Since
Parameters
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Parameters
Rest ...args: any[]Returns void
Returns this
remove
listener from the listener array for the event namedeventName.
+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.removeListener() or removeAllListeners() calls after emitting and before the last listener finishes execution
+will not remove them fromemit() in progress. Subsequent events behave as expected.
+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
+emitter.listeners() method will need to be recreated.removeListener() will remove the most
+recently added instance. In the example the once('ping')listener is removed:
+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');
+EventEmitter, so that calls can be chained.Parameters
Returns void
Returns this
Since
Parameters
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Parameters
Rest ...args: any[]Returns void
Returns this
[async
Returns AsyncIterableIterator<any>
[async
Class Stats
fs.Stats object provides information about a file.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.
+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:
+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 }
+Since
Hierarchy (view full)
Index
Constructors
Properties
Methods
Constructors
constructor
Properties
dev
ino
mode
nlink
uid
gid
rdev
size
blksize
blocks
atime
mtime
ctime
birthtime
atime
mtime
ctime
birthtime
Methods
is
is
is
is
is
isFIFO
is
Class Stream
EventEmitter class is defined and exposed by the events module:
+const EventEmitter = require('events');
+EventEmitters emit the event 'newListener' when new listeners are
+added and 'removeListener' when existing listeners are removed.Since
Hierarchy (view full)
Index
Constructors
Properties
Methods
Constructors
constructor
Parameters
Optional opts: ReadableOptionsReturns Stream
Properties
Static Readonly error'error'
+events. Listeners installed using this symbol are called before the regular
+'error' listeners are called.'error' event is emitted, therefore the process will still crash if no
+regular 'error' listener is installed.Static Readonly captureStatic captureStatic defaultMethods
Optional [captureStatic oncePromise 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.'error' event
+semantics and does not listen to the 'error' event.
+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();
+'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:
+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
+AbortSignal can be used to cancel waiting for the event:
+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!
+Parameters
Optional options: StaticEventEmitterOptionsReturns Promise<any[]>
Since
Parameters
Optional options: StaticEventEmitterOptionsReturns Promise<any[]>
Static on
+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
})();
+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.AbortSignal can be used to cancel waiting on events:
+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());
+Parameters
Optional options: StaticEventEmitterOptionsReturns AsyncIterableIterator<any>
eventName events emitted by the emitterSince
Static listenereventNameregistered on the given emitter.
+const { EventEmitter, listenerCount } = require('events');
const myEmitter = new EventEmitter();
myEmitter.on('event', () => {});
myEmitter.on('event', () => {});
console.log(listenerCount(myEmitter, 'event'));
// Prints: 2
+Parameters
Returns number
Since
Deprecated
listenerCount instead.Static geteventName.EventEmitters this behaves exactly the same as calling .listeners on
+the emitter.EventTargets this is the only way to get the event listeners for the
+event target. This is useful for debugging and diagnostic purposes.
+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]
}
+Parameters
Returns Function[]
Since
Static getEventEmitters this behaves exactly the same as calling .getMaxListeners on
+the emitter.EventTargets this is the only way to get the max event listeners for the
+event target. If the number of event handlers on a single EventTarget exceeds
+the max set, the EventTarget will print a warning.
+import { getMaxListeners, setMaxListeners, EventEmitter } from 'node:events';
{
const ee = new EventEmitter();
console.log(getMaxListeners(ee)); // 10
setMaxListeners(11, ee);
console.log(getMaxListeners(ee)); // 11
}
{
const et = new EventTarget();
console.log(getMaxListeners(et)); // 10
setMaxListeners(11, et);
console.log(getMaxListeners(et)); // 11
}
+Parameters
Returns number
Since
Static set
+const {
setMaxListeners,
EventEmitter
} = require('events');
const target = new EventTarget();
const emitter = new EventEmitter();
setMaxListeners(5, target, emitter);
+Parameters
Optional n: numberEventTarget event.Rest ...eventTargets: (EventEmitter<DefaultEventMap> | _DOMEventTarget)[]Returns void
Since
Static addExperimental abort event on the provided signal.abort event on abort signals is unsafe and may
+lead to resource leaks since another third party with the signal can
+call e.stopImmediatePropagation(). Unfortunately Node.js cannot change
+this since it would violate the web standard. Additionally, the original
+API makes it easy to forget to remove listeners.AbortSignals in Node.js APIs by solving these
+two issues by listening to the event such that stopImmediatePropagation does
+not prevent the listener from running.
+import { addAbortListener } from 'node:events';
function example(signal) {
let disposable;
try {
signal.addEventListener('abort', (e) => e.stopImmediatePropagation());
disposable = addAbortListener(signal, (e) => {
// Do something when signal is aborted.
});
} finally {
disposable?.[Symbol.dispose]();
}
}
+Parameters
Parameters
Returns void
Returns Disposable
abort listener.Since
add
emitter.on(eventName, listener).Type Parameters
Parameters
Parameters
Rest ...args: any[]Returns void
Returns this
Since
on
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 eventNameand listener will result in the listener being added, and called, multiple
+times.
+server.on('connection', (stream) => {
console.log('someone connected!');
});
+EventEmitter, so that calls can be chained.emitter.prependListener() method can be used as an alternative to add the
+event listener to the beginning of the listeners array.
+const myEE = new EventEmitter();
myEE.on('foo', () => console.log('a'));
myEE.prependListener('foo', () => console.log('b'));
myEE.emit('foo');
// Prints:
// b
// a
+Type Parameters
Parameters
Parameters
Rest ...args: any[]Returns void
Returns this
Since
once
listener function for the event named eventName. The
+next time eventName is triggered, this listener is removed and then invoked.
+server.once('connection', (stream) => {
console.log('Ah, we have our first user!');
});
+EventEmitter, so that calls can be chained.emitter.prependOnceListener() method can be used as an alternative to add the
+event listener to the beginning of the listeners array.
+const myEE = new EventEmitter();
myEE.once('foo', () => console.log('a'));
myEE.prependOnceListener('foo', () => console.log('b'));
myEE.emit('foo');
// Prints:
// b
// a
+Type Parameters
Parameters
Parameters
Rest ...args: any[]Returns void
Returns this
Since
remove
listener from the listener array for the event namedeventName.
+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.removeListener() or removeAllListeners() calls after emitting and before the last listener finishes execution
+will not remove them fromemit() in progress. Subsequent events behave as expected.
+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
+emitter.listeners() method will need to be recreated.removeListener() will remove the most
+recently added instance. In the example the once('ping')listener is removed:
+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');
+EventEmitter, so that calls can be chained.Type Parameters
Parameters
Parameters
Rest ...args: any[]Returns void
Returns this
Since
off
emitter.removeListener().Type Parameters
Parameters
Parameters
Rest ...args: any[]Returns void
Returns this
Since
remove
eventName.EventEmitter instance was created by some other
+component or module (e.g. sockets or file streams).EventEmitter, so that calls can be chained.Parameters
Optional event: string | symbolReturns this
Since
set
EventEmitters will print a warning if more than 10 listeners are
+added for a particular event. This is a useful default that helps finding
+memory leaks. The emitter.setMaxListeners() method allows the limit to be
+modified for this specific EventEmitter instance. The value can be set toInfinity (or 0) to indicate an unlimited number of listeners.EventEmitter, so that calls can be chained.Parameters
Returns this
Since
get
EventEmitter which is either
+set by emitter.setMaxListeners(n) or defaults to defaultMaxListeners.Returns number
Since
listeners
eventName.
+server.on('connection', (stream) => {
console.log('someone connected!');
});
console.log(util.inspect(server.listeners('connection')));
// Prints: [ [Function] ]
+Type Parameters
Parameters
Returns Function[]
Since
raw
eventName,
+including any wrappers (such as those created by .once()).
+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');
+Type Parameters
Parameters
Returns Function[]
Since
emit
eventName, in the order they were registered, passing the supplied arguments
+to each.true if the event had listeners, false otherwise.
+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
+Type Parameters
Parameters
Rest ...args: AnyRestReturns boolean
Since
listener
eventName.listener is provided, it will return how many times the listener
+is found in the list of the listeners of the event.Type Parameters
Parameters
Optional listener: FunctionReturns number
Since
prepend
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 eventNameand listener will result in the listener being added, and called, multiple
+times.
+server.prependListener('connection', (stream) => {
console.log('someone connected!');
});
+EventEmitter, so that calls can be chained.Type Parameters
Parameters
Parameters
Rest ...args: any[]Returns void
Returns this
Since
prepend
listener function for the event named eventName to the beginning of the listeners array. The next time eventName is triggered, this
+listener is removed, and then invoked.
+server.prependOnceListener('connection', (stream) => {
console.log('Ah, we have our first user!');
});
+EventEmitter, so that calls can be chained.Type Parameters
Parameters
Parameters
Rest ...args: any[]Returns void
Returns this
Since
event
Symbols.
+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) ]
+Returns (string | symbol)[]
Since
pipe
Type Parameters
Parameters
Optional options: {
end?: boolean;
}Optional end?: booleanReturns T
compose
Type Parameters
Parameters
Optional options: {
signal: AbortSignal;
}signal: AbortSignal
Returns T
Class Writable
Since
Hierarchy (view full)
Implements
Implemented by
Index
Constructors
Properties
Methods
Constructors
constructor
Parameters
Optional opts: WritableOptionsReturns Writable
Properties
Static Readonly error'error'
+events. Listeners installed using this symbol are called before the regular
+'error' listeners are called.'error' event is emitted, therefore the process will still crash if no
+regular 'error' listener is installed.Static Readonly captureStatic captureStatic defaultReadonly writabletrue if it is safe to call writable.write(), which means
+the stream has not been destroyed, errored or ended.Since
Readonly writabletrue after writable.end() has been called. This property
+does not indicate whether the data has been flushed, for this use writable.writableFinished instead.Since
Readonly writabletrue immediately before the 'finish' event is emitted.Since
Readonly writablehighWaterMark passed when creating this Writable.Since
Readonly writablehighWaterMark.Since
Readonly writableobjectMode of a given Writable stream.Since
Readonly writablewritable.uncork() needs to be
+called in order to fully uncork the stream.Since
destroyed
true after writable.destroy() has been called.Since
Readonly closedSince
Readonly erroredSince
Readonly writabletrue if the stream's buffer has been full and stream will emit 'drain'.Since
Methods
Optional [captureStatic oncePromise 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.'error' event
+semantics and does not listen to the 'error' event.
+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();
+'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:
+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
+AbortSignal can be used to cancel waiting for the event:
+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!
+Parameters
Optional options: StaticEventEmitterOptionsReturns Promise<any[]>
Since
Parameters
Optional options: StaticEventEmitterOptionsReturns Promise<any[]>
Static on
+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
})();
+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.AbortSignal can be used to cancel waiting on events:
+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());
+Parameters
Optional options: StaticEventEmitterOptionsReturns AsyncIterableIterator<any>
eventName events emitted by the emitterSince
Static listenereventNameregistered on the given emitter.
+const { EventEmitter, listenerCount } = require('events');
const myEmitter = new EventEmitter();
myEmitter.on('event', () => {});
myEmitter.on('event', () => {});
console.log(listenerCount(myEmitter, 'event'));
// Prints: 2
+Parameters
Returns number
Since
Deprecated
listenerCount instead.Static geteventName.EventEmitters this behaves exactly the same as calling .listeners on
+the emitter.EventTargets this is the only way to get the event listeners for the
+event target. This is useful for debugging and diagnostic purposes.
+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]
}
+Parameters
Returns Function[]
Since
Static getEventEmitters this behaves exactly the same as calling .getMaxListeners on
+the emitter.EventTargets this is the only way to get the max event listeners for the
+event target. If the number of event handlers on a single EventTarget exceeds
+the max set, the EventTarget will print a warning.
+import { getMaxListeners, setMaxListeners, EventEmitter } from 'node:events';
{
const ee = new EventEmitter();
console.log(getMaxListeners(ee)); // 10
setMaxListeners(11, ee);
console.log(getMaxListeners(ee)); // 11
}
{
const et = new EventTarget();
console.log(getMaxListeners(et)); // 10
setMaxListeners(11, et);
console.log(getMaxListeners(et)); // 11
}
+Parameters
Returns number
Since
Static set
+const {
setMaxListeners,
EventEmitter
} = require('events');
const target = new EventTarget();
const emitter = new EventEmitter();
setMaxListeners(5, target, emitter);
+Parameters
Optional n: numberEventTarget event.Rest ...eventTargets: (EventEmitter<DefaultEventMap> | _DOMEventTarget)[]Returns void
Since
Static addExperimental abort event on the provided signal.abort event on abort signals is unsafe and may
+lead to resource leaks since another third party with the signal can
+call e.stopImmediatePropagation(). Unfortunately Node.js cannot change
+this since it would violate the web standard. Additionally, the original
+API makes it easy to forget to remove listeners.AbortSignals in Node.js APIs by solving these
+two issues by listening to the event such that stopImmediatePropagation does
+not prevent the listener from running.
+import { addAbortListener } from 'node:events';
function example(signal) {
let disposable;
try {
signal.addEventListener('abort', (e) => e.stopImmediatePropagation());
disposable = addAbortListener(signal, (e) => {
// Do something when signal is aborted.
});
} finally {
disposable?.[Symbol.dispose]();
}
}
+Parameters
Parameters
Returns void
Returns Disposable
abort listener.Since
off
emitter.removeListener().Type Parameters
Parameters
Parameters
Rest ...args: any[]Returns void
Returns this
Since
remove
eventName.EventEmitter instance was created by some other
+component or module (e.g. sockets or file streams).EventEmitter, so that calls can be chained.Parameters
Optional event: string | symbolReturns this
Since
set
EventEmitters will print a warning if more than 10 listeners are
+added for a particular event. This is a useful default that helps finding
+memory leaks. The emitter.setMaxListeners() method allows the limit to be
+modified for this specific EventEmitter instance. The value can be set toInfinity (or 0) to indicate an unlimited number of listeners.EventEmitter, so that calls can be chained.Parameters
Returns this
Since
get
EventEmitter which is either
+set by emitter.setMaxListeners(n) or defaults to defaultMaxListeners.Returns number
Since
listeners
eventName.
+server.on('connection', (stream) => {
console.log('someone connected!');
});
console.log(util.inspect(server.listeners('connection')));
// Prints: [ [Function] ]
+Type Parameters
Parameters
Returns Function[]
Since
raw
eventName,
+including any wrappers (such as those created by .once()).
+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');
+Type Parameters
Parameters
Returns Function[]
Since
listener
eventName.listener is provided, it will return how many times the listener
+is found in the list of the listeners of the event.Type Parameters
Parameters
Optional listener: FunctionReturns number
Since
event
Symbols.
+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) ]
+Returns (string | symbol)[]
Since
pipe
Type Parameters
Parameters
Optional options: {
end?: boolean;
}Optional end?: booleanReturns T
compose
Type Parameters
Parameters
Optional options: {
signal: AbortSignal;
}signal: AbortSignal
Returns T
Static fromExperimental Writable from a web WritableStream.Parameters
Optional options: Pick<WritableOptions, "highWaterMark" | "objectMode" | "signal" | "decodeStrings">Returns Writable
Since
Static toExperimental WritableStream from a Writable.Parameters
Returns WritableStream<any>
Since
_write
Parameters
Parameters
Optional error: ErrorReturns void
Returns void
Optional _writevParameters
chunk: any;
encoding: BufferEncoding;
}[]Parameters
Optional error: ErrorReturns void
Returns void
Optional _construct_destroy
_final
write
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.true if the internal buffer is less than thehighWaterMark 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.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.
+Once write() returns false, do not write more chunks
+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.Transform, because the Transform streams are paused
+by default until they are piped or a 'data' or 'readable' event handler
+is added.Readable and use pipe. However, if calling write() is preferred, it is
+possible to respect backpressure and avoid memory issues using the 'drain' event:
+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.');
});
+Writable stream in object mode will always ignore the encoding argument.Parameters
chunk must be a string, Buffer or Uint8Array. For object mode streams, chunk may be any
+JavaScript value other than null.Optional callback: ((error) => void)Parameters
Returns void
Returns boolean
false if the stream wishes for the calling code to wait for the 'drain' event to be emitted before continuing to write additional data; otherwise true.Since
Parameters
Optional callback: ((error) => void)Parameters
Returns void
Returns boolean
set
writable.setDefaultEncoding() method sets the default encoding for a Writable stream.Parameters
Returns this
Since
end
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.
+// 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!
+Parameters
Optional cb: (() => void)Returns void
Returns this
Since
Parameters
Optional cb: (() => void)Returns void
Returns this
Parameters
Optional cb: (() => void)Returns void
Returns this
cork
writable.cork() method forces all written data to be buffered in memory.
+The buffered data will be flushed when either the uncork or end methods are called.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 implementingwritable._writev() may have an adverse effect on throughput.writable.uncork(), writable._writev().Returns void
Since
uncork
writable.uncork() method flushes all data buffered since cork was called.writable.cork() and writable.uncork() to manage the buffering
+of writes to a stream, defer calls to writable.uncork() usingprocess.nextTick(). Doing so allows batching of allwritable.write() calls that occur within a given Node.js event
+loop phase.
+stream.cork();
stream.write('some ');
stream.write('data ');
process.nextTick(() => stream.uncork());
+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.
+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();
});
+writable.cork().Returns void
Since
destroy
'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.destroy() has been called any further calls will be a no-op and no
+further errors except from _destroy() may be emitted as 'error'.writable._destroy().Parameters
Optional error: Error'error' event.Returns this
Since
add
+
+Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
Parameters
Parameters
Rest ...args: any[]Returns void
Returns this
emit
eventName, in the order they were registered, passing the supplied arguments
+to each.true if the event had listeners, false otherwise.
+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
+Parameters
Returns boolean
Since
Parameters
Returns boolean
Parameters
Returns boolean
Parameters
Returns boolean
Parameters
Returns boolean
Parameters
Returns boolean
Parameters
Rest ...args: any[]Returns boolean
on
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 eventNameand listener will result in the listener being added, and called, multiple
+times.
+server.on('connection', (stream) => {
console.log('someone connected!');
});
+EventEmitter, so that calls can be chained.emitter.prependListener() method can be used as an alternative to add the
+event listener to the beginning of the listeners array.
+const myEE = new EventEmitter();
myEE.on('foo', () => console.log('a'));
myEE.prependListener('foo', () => console.log('b'));
myEE.emit('foo');
// Prints:
// b
// a
+Parameters
Returns void
Returns this
Since
Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
Parameters
Parameters
Rest ...args: any[]Returns void
Returns this
once
listener function for the event named eventName. The
+next time eventName is triggered, this listener is removed and then invoked.
+server.once('connection', (stream) => {
console.log('Ah, we have our first user!');
});
+EventEmitter, so that calls can be chained.emitter.prependOnceListener() method can be used as an alternative to add the
+event listener to the beginning of the listeners array.
+const myEE = new EventEmitter();
myEE.once('foo', () => console.log('a'));
myEE.prependOnceListener('foo', () => console.log('b'));
myEE.emit('foo');
// Prints:
// b
// a
+Parameters
Returns void
Returns this
Since
Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
Parameters
Parameters
Rest ...args: any[]Returns void
Returns this
prepend
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 eventNameand listener will result in the listener being added, and called, multiple
+times.
+server.prependListener('connection', (stream) => {
console.log('someone connected!');
});
+EventEmitter, so that calls can be chained.Parameters
Returns void
Returns this
Since
Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
Parameters
Parameters
Rest ...args: any[]Returns void
Returns this
prepend
listener function for the event named eventName to the beginning of the listeners array. The next time eventName is triggered, this
+listener is removed, and then invoked.
+server.prependOnceListener('connection', (stream) => {
console.log('Ah, we have our first user!');
});
+EventEmitter, so that calls can be chained.Parameters
Returns void
Returns this
Since
Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
Parameters
Parameters
Rest ...args: any[]Returns void
Returns this
remove
listener from the listener array for the event namedeventName.
+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.removeListener() or removeAllListeners() calls after emitting and before the last listener finishes execution
+will not remove them fromemit() in progress. Subsequent events behave as expected.
+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
+emitter.listeners() method will need to be recreated.removeListener() will remove the most
+recently added instance. In the example the once('ping')listener is removed:
+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');
+EventEmitter, so that calls can be chained.Parameters
Returns void
Returns this
Since
Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
Parameters
Parameters
Rest ...args: any[]Returns void
Returns this
Class WriteStream
+
+stream.Writablefs.WriteStream are created and returned using the createWriteStream function.Since
Hierarchy (view full)
Index
Constructors
Properties
Methods
Constructors
constructor
Parameters
Optional opts: WritableOptionsReturns WriteStream
Properties
Static Readonly error'error'
+events. Listeners installed using this symbol are called before the regular
+'error' listeners are called.'error' event is emitted, therefore the process will still crash if no
+regular 'error' listener is installed.Static Readonly captureStatic captureStatic defaultbytes
Since
path
path is passed as a string, thenwriteStream.path will be a string. If path is passed as a Buffer, thenwriteStream.path will be a
+Buffer.Since
pending
true if the underlying file has not been opened yet,
+i.e. before the 'ready' event is emitted.Since
Readonly writabletrue if it is safe to call writable.write(), which means
+the stream has not been destroyed, errored or ended.Since
Readonly writabletrue after writable.end() has been called. This property
+does not indicate whether the data has been flushed, for this use writable.writableFinished instead.Since
Readonly writabletrue immediately before the 'finish' event is emitted.Since
Readonly writablehighWaterMark passed when creating this Writable.Since
Readonly writablehighWaterMark.Since
Readonly writableobjectMode of a given Writable stream.Since
Readonly writablewritable.uncork() needs to be
+called in order to fully uncork the stream.Since
destroyed
true after writable.destroy() has been called.Since
Readonly closedSince
Readonly erroredSince
Readonly writabletrue if the stream's buffer has been full and stream will emit 'drain'.Since
Methods
Optional [captureStatic oncePromise 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.'error' event
+semantics and does not listen to the 'error' event.
+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();
+'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:
+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
+AbortSignal can be used to cancel waiting for the event:
+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!
+Parameters
Optional options: StaticEventEmitterOptionsReturns Promise<any[]>
Since
Parameters
Optional options: StaticEventEmitterOptionsReturns Promise<any[]>
Static on
+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
})();
+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.AbortSignal can be used to cancel waiting on events:
+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());
+Parameters
Optional options: StaticEventEmitterOptionsReturns AsyncIterableIterator<any>
eventName events emitted by the emitterSince
Static listenereventNameregistered on the given emitter.
+const { EventEmitter, listenerCount } = require('events');
const myEmitter = new EventEmitter();
myEmitter.on('event', () => {});
myEmitter.on('event', () => {});
console.log(listenerCount(myEmitter, 'event'));
// Prints: 2
+Parameters
Returns number
Since
Deprecated
listenerCount instead.Static geteventName.EventEmitters this behaves exactly the same as calling .listeners on
+the emitter.EventTargets this is the only way to get the event listeners for the
+event target. This is useful for debugging and diagnostic purposes.
+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]
}
+Parameters
Returns Function[]
Since
Static getEventEmitters this behaves exactly the same as calling .getMaxListeners on
+the emitter.EventTargets this is the only way to get the max event listeners for the
+event target. If the number of event handlers on a single EventTarget exceeds
+the max set, the EventTarget will print a warning.
+import { getMaxListeners, setMaxListeners, EventEmitter } from 'node:events';
{
const ee = new EventEmitter();
console.log(getMaxListeners(ee)); // 10
setMaxListeners(11, ee);
console.log(getMaxListeners(ee)); // 11
}
{
const et = new EventTarget();
console.log(getMaxListeners(et)); // 10
setMaxListeners(11, et);
console.log(getMaxListeners(et)); // 11
}
+Parameters
Returns number
Since
Static set
+const {
setMaxListeners,
EventEmitter
} = require('events');
const target = new EventTarget();
const emitter = new EventEmitter();
setMaxListeners(5, target, emitter);
+Parameters
Optional n: numberEventTarget event.Rest ...eventTargets: (EventEmitter<DefaultEventMap> | _DOMEventTarget)[]Returns void
Since
Static addExperimental abort event on the provided signal.abort event on abort signals is unsafe and may
+lead to resource leaks since another third party with the signal can
+call e.stopImmediatePropagation(). Unfortunately Node.js cannot change
+this since it would violate the web standard. Additionally, the original
+API makes it easy to forget to remove listeners.AbortSignals in Node.js APIs by solving these
+two issues by listening to the event such that stopImmediatePropagation does
+not prevent the listener from running.
+import { addAbortListener } from 'node:events';
function example(signal) {
let disposable;
try {
signal.addEventListener('abort', (e) => e.stopImmediatePropagation());
disposable = addAbortListener(signal, (e) => {
// Do something when signal is aborted.
});
} finally {
disposable?.[Symbol.dispose]();
}
}
+Parameters
Parameters
Returns void
Returns Disposable
abort listener.Since
off
emitter.removeListener().Type Parameters
Parameters
Parameters
Rest ...args: any[]Returns void
Returns this
Since
remove
eventName.EventEmitter instance was created by some other
+component or module (e.g. sockets or file streams).EventEmitter, so that calls can be chained.Parameters
Optional event: string | symbolReturns this
Since
set
EventEmitters will print a warning if more than 10 listeners are
+added for a particular event. This is a useful default that helps finding
+memory leaks. The emitter.setMaxListeners() method allows the limit to be
+modified for this specific EventEmitter instance. The value can be set toInfinity (or 0) to indicate an unlimited number of listeners.EventEmitter, so that calls can be chained.Parameters
Returns this
Since
get
EventEmitter which is either
+set by emitter.setMaxListeners(n) or defaults to defaultMaxListeners.Returns number
Since
listeners
eventName.
+server.on('connection', (stream) => {
console.log('someone connected!');
});
console.log(util.inspect(server.listeners('connection')));
// Prints: [ [Function] ]
+Type Parameters
Parameters
Returns Function[]
Since
raw
eventName,
+including any wrappers (such as those created by .once()).
+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');
+Type Parameters
Parameters
Returns Function[]
Since
listener
eventName.listener is provided, it will return how many times the listener
+is found in the list of the listeners of the event.Type Parameters
Parameters
Optional listener: FunctionReturns number
Since
event
Symbols.
+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) ]
+Returns (string | symbol)[]
Since
close
writeStream. Optionally accepts a
+callback that will be executed once the writeStreamis closed.Parameters
Optional callback: ((err?) => void)Parameters
Optional err: ErrnoExceptionReturns void
Returns void
Since
add
+
+Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
Parameters
Parameters
Rest ...args: any[]Returns void
Returns this
on
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 eventNameand listener will result in the listener being added, and called, multiple
+times.
+server.on('connection', (stream) => {
console.log('someone connected!');
});
+EventEmitter, so that calls can be chained.emitter.prependListener() method can be used as an alternative to add the
+event listener to the beginning of the listeners array.
+const myEE = new EventEmitter();
myEE.on('foo', () => console.log('a'));
myEE.prependListener('foo', () => console.log('b'));
myEE.emit('foo');
// Prints:
// b
// a
+Parameters
Returns void
Returns this
Since
Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
Parameters
Parameters
Rest ...args: any[]Returns void
Returns this
once
listener function for the event named eventName. The
+next time eventName is triggered, this listener is removed and then invoked.
+server.once('connection', (stream) => {
console.log('Ah, we have our first user!');
});
+EventEmitter, so that calls can be chained.emitter.prependOnceListener() method can be used as an alternative to add the
+event listener to the beginning of the listeners array.
+const myEE = new EventEmitter();
myEE.once('foo', () => console.log('a'));
myEE.prependOnceListener('foo', () => console.log('b'));
myEE.emit('foo');
// Prints:
// b
// a
+Parameters
Returns void
Returns this
Since
Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
Parameters
Parameters
Rest ...args: any[]Returns void
Returns this
prepend
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 eventNameand listener will result in the listener being added, and called, multiple
+times.
+server.prependListener('connection', (stream) => {
console.log('someone connected!');
});
+EventEmitter, so that calls can be chained.Parameters
Returns void
Returns this
Since
Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
Parameters
Parameters
Rest ...args: any[]Returns void
Returns this
prepend
listener function for the event named eventName to the beginning of the listeners array. The next time eventName is triggered, this
+listener is removed, and then invoked.
+server.prependOnceListener('connection', (stream) => {
console.log('Ah, we have our first user!');
});
+EventEmitter, so that calls can be chained.Parameters
Returns void
Returns this
Since
Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
Parameters
Parameters
Rest ...args: any[]Returns void
Returns this
pipe
Type Parameters
Parameters
Optional options: {
end?: boolean;
}Optional end?: booleanReturns T
compose
Type Parameters
Parameters
Optional options: {
signal: AbortSignal;
}signal: AbortSignal
Returns T
Static fromExperimental Writable from a web WritableStream.Parameters
Optional options: Pick<WritableOptions, "highWaterMark" | "objectMode" | "signal" | "decodeStrings">Returns Writable
Since
Static toExperimental WritableStream from a Writable.Parameters
Returns WritableStream<any>
Since
_write
Parameters
Parameters
Optional error: ErrorReturns void
Returns void
Optional _writevParameters
chunk: any;
encoding: BufferEncoding;
}[]Parameters
Optional error: ErrorReturns void
Returns void
Optional _construct_destroy
_final
write
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.true if the internal buffer is less than thehighWaterMark 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.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.
+Once write() returns false, do not write more chunks
+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.Transform, because the Transform streams are paused
+by default until they are piped or a 'data' or 'readable' event handler
+is added.Readable and use pipe. However, if calling write() is preferred, it is
+possible to respect backpressure and avoid memory issues using the 'drain' event:
+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.');
});
+Writable stream in object mode will always ignore the encoding argument.Parameters
chunk must be a string, Buffer or Uint8Array. For object mode streams, chunk may be any
+JavaScript value other than null.Optional callback: ((error) => void)Parameters
Returns void
Returns boolean
false if the stream wishes for the calling code to wait for the 'drain' event to be emitted before continuing to write additional data; otherwise true.Since
Parameters
Optional callback: ((error) => void)Parameters
Returns void
Returns boolean
set
writable.setDefaultEncoding() method sets the default encoding for a Writable stream.Parameters
Returns this
Since
end
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.
+// 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!
+Parameters
Optional cb: (() => void)Returns void
Returns this
Since
Parameters
Optional cb: (() => void)Returns void
Returns this
Parameters
Optional cb: (() => void)Returns void
Returns this
cork
writable.cork() method forces all written data to be buffered in memory.
+The buffered data will be flushed when either the uncork or end methods are called.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 implementingwritable._writev() may have an adverse effect on throughput.writable.uncork(), writable._writev().Returns void
Since
uncork
writable.uncork() method flushes all data buffered since cork was called.writable.cork() and writable.uncork() to manage the buffering
+of writes to a stream, defer calls to writable.uncork() usingprocess.nextTick(). Doing so allows batching of allwritable.write() calls that occur within a given Node.js event
+loop phase.
+stream.cork();
stream.write('some ');
stream.write('data ');
process.nextTick(() => stream.uncork());
+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.
+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();
});
+writable.cork().Returns void
Since
destroy
'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.destroy() has been called any further calls will be a no-op and no
+further errors except from _destroy() may be emitted as 'error'.writable._destroy().Parameters
Optional error: Error'error' event.Returns this
Since
emit
eventName, in the order they were registered, passing the supplied arguments
+to each.true if the event had listeners, false otherwise.
+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
+Parameters
Returns boolean
Since
Parameters
Returns boolean
Parameters
Returns boolean
Parameters
Returns boolean
Parameters
Returns boolean
Parameters
Returns boolean
Parameters
Rest ...args: any[]Returns boolean
remove
listener from the listener array for the event namedeventName.
+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.removeListener() or removeAllListeners() calls after emitting and before the last listener finishes execution
+will not remove them fromemit() in progress. Subsequent events behave as expected.
+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
+emitter.listeners() method will need to be recreated.removeListener() will remove the most
+recently added instance. In the example the once('ping')listener is removed:
+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');
+EventEmitter, so that calls can be chained.Parameters
Returns void
Returns this
Since
Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
Parameters
Parameters
Rest ...args: any[]Returns void
Returns this
Class X509Certificate
+const { X509Certificate } = await import('crypto');
const x509 = new X509Certificate('{... pem encoded cert ...}');
console.log(x509.subject);
+Since
Index
Constructors
Properties
Methods
Constructors
constructor
Parameters
Returns X509Certificate
Properties
Readonly catrue if this is a Certificate Authority (CA) certificate.Since
Readonly fingerprintx509.fingerprint256 instead.Since
Readonly fingerprint256Since
Readonly fingerprint512Since
Readonly subjectSince
Readonly subjectundefined
+if not available.Since
Readonly infoundefined if not
+available.Since
Readonly keySince
Readonly issuerSince
Optional Readonly issuerundefined if the issuer certificate is not
+available.Since
Readonly publicKeyObject for this certificate.Since
Readonly rawBuffer containing the DER encoding of this certificate.Since
Readonly serialx509.fingerprint256 as a unique
+identifier instead.Since
Readonly validSince
Readonly validSince
Methods
check
'subject' option is undefined or set to 'default', the certificate
+subject is only considered if the subject alternative name extension either does
+not exist or does not contain any email addresses.'subject' option is set to 'always' and if the subject alternative
+name extension either does not exist or does not contain a matching email
+address, the certificate subject is considered.'subject' option is set to 'never', the certificate subject is never
+considered, even if the certificate contains no subject alternative names.Parameters
Optional options: Pick<X509CheckOptions, "subject">Returns string
email if the certificate matches, undefined if it does not.Since
check
foo.example.com)
+or it might contain wildcards (e.g., *.example.com). Because host name
+comparisons are case-insensitive, the returned subject name might also differ
+from the given name in capitalization.'subject' option is undefined or set to 'default', the certificate
+subject is only considered if the subject alternative name extension either does
+not exist or does not contain any DNS names. This behavior is consistent with RFC 2818 ("HTTP Over TLS").'subject' option is set to 'always' and if the subject alternative
+name extension either does not exist or does not contain a matching DNS name,
+the certificate subject is considered.'subject' option is set to 'never', the certificate subject is never
+considered, even if the certificate contains no subject alternative names.Parameters
Optional options: X509CheckOptionsReturns string
name, or undefined if no subject name matches name.Since
checkIP
iPAddress subject alternative names are considered, and they
+must match the given ip address exactly. Other subject alternative names as
+well as the subject field of the certificate are ignored.Parameters
Returns string
ip if the certificate matches, undefined if it does not.Since
check
otherCert.Parameters
Returns boolean
Since
check
Parameters
Returns boolean
Since
toJSON
to
certificate object encoding.Returns PeerCertificate
Since
to
verify
Parameters
Returns boolean
Since
Class Duplex
Readable and Writable interfaces.Duplex streams include:
+
+TCP socketszlib streamscrypto streamsSince
Hierarchy (view full)
Implements
Index
Constructors
Properties
Methods
Constructors
constructor
Parameters
Optional opts: DuplexOptionsReturns Duplex
Properties
Static Readonly error'error'
+events. Listeners installed using this symbol are called before the regular
+'error' listeners are called.'error' event is emitted, therefore the process will still crash if no
+regular 'error' listener is installed.Static Readonly captureStatic captureStatic defaultReadonly Experimental readable'end'.Since
readable
true if it is safe to call readable.read(), which means
+the stream has not been destroyed or emitted 'error' or 'end'.Since
Readonly Experimental readable'data' has been emitted.Since
Readonly readableencoding of a given Readable stream. The encodingproperty can be set using the readable.setEncoding() method.Since
Readonly readabletrue when 'end' event is emitted.Since
Readonly readableReadable stream as described
+in the Three states section.Since
Readonly readablehighWaterMark passed when creating this Readable.Since
Readonly readablehighWaterMark.Since
Readonly readableobjectMode of a given Readable stream.Since
destroyed
true after readable.destroy() has been called.Since
Readonly writabletrue if it is safe to call writable.write(), which means
+the stream has not been destroyed, errored or ended.Since
Readonly writabletrue after writable.end() has been called. This property
+does not indicate whether the data has been flushed, for this use writable.writableFinished instead.Since
Readonly writabletrue immediately before the 'finish' event is emitted.Since
Readonly writablehighWaterMark passed when creating this Writable.Since
Readonly writablehighWaterMark.Since
Readonly writableobjectMode of a given Writable stream.Since
Readonly writablewritable.uncork() needs to be
+called in order to fully uncork the stream.Since
Readonly writabletrue if the stream's buffer has been full and stream will emit 'drain'.Since
Readonly closedSince
Readonly erroredSince
allow
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.Duplex stream instance, but must be changed before the 'end' event is
+emitted.Since
Methods
Optional [captureStatic oncePromise 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.'error' event
+semantics and does not listen to the 'error' event.
+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();
+'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:
+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
+AbortSignal can be used to cancel waiting for the event:
+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!
+Parameters
Optional options: StaticEventEmitterOptionsReturns Promise<any[]>
Since
Parameters
Optional options: StaticEventEmitterOptionsReturns Promise<any[]>
Static on
+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
})();
+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.AbortSignal can be used to cancel waiting on events:
+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());
+Parameters
Optional options: StaticEventEmitterOptionsReturns AsyncIterableIterator<any>
eventName events emitted by the emitterSince
Static listenereventNameregistered on the given emitter.
+const { EventEmitter, listenerCount } = require('events');
const myEmitter = new EventEmitter();
myEmitter.on('event', () => {});
myEmitter.on('event', () => {});
console.log(listenerCount(myEmitter, 'event'));
// Prints: 2
+Parameters
Returns number
Since
Deprecated
listenerCount instead.Static geteventName.EventEmitters this behaves exactly the same as calling .listeners on
+the emitter.EventTargets this is the only way to get the event listeners for the
+event target. This is useful for debugging and diagnostic purposes.
+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]
}
+Parameters
Returns Function[]
Since
Static getEventEmitters this behaves exactly the same as calling .getMaxListeners on
+the emitter.EventTargets this is the only way to get the max event listeners for the
+event target. If the number of event handlers on a single EventTarget exceeds
+the max set, the EventTarget will print a warning.
+import { getMaxListeners, setMaxListeners, EventEmitter } from 'node:events';
{
const ee = new EventEmitter();
console.log(getMaxListeners(ee)); // 10
setMaxListeners(11, ee);
console.log(getMaxListeners(ee)); // 11
}
{
const et = new EventTarget();
console.log(getMaxListeners(et)); // 10
setMaxListeners(11, et);
console.log(getMaxListeners(et)); // 11
}
+Parameters
Returns number
Since
Static set
+const {
setMaxListeners,
EventEmitter
} = require('events');
const target = new EventTarget();
const emitter = new EventEmitter();
setMaxListeners(5, target, emitter);
+Parameters
Optional n: numberEventTarget event.Rest ...eventTargets: (EventEmitter<DefaultEventMap> | _DOMEventTarget)[]Returns void
Since
Static addExperimental abort event on the provided signal.abort event on abort signals is unsafe and may
+lead to resource leaks since another third party with the signal can
+call e.stopImmediatePropagation(). Unfortunately Node.js cannot change
+this since it would violate the web standard. Additionally, the original
+API makes it easy to forget to remove listeners.AbortSignals in Node.js APIs by solving these
+two issues by listening to the event such that stopImmediatePropagation does
+not prevent the listener from running.
+import { addAbortListener } from 'node:events';
function example(signal) {
let disposable;
try {
signal.addEventListener('abort', (e) => e.stopImmediatePropagation());
disposable = addAbortListener(signal, (e) => {
// Do something when signal is aborted.
});
} finally {
disposable?.[Symbol.dispose]();
}
}
+Parameters
Parameters
Returns void
Returns Disposable
abort listener.Since
off
emitter.removeListener().Type Parameters
Parameters
Parameters
Rest ...args: any[]Returns void
Returns this
Since
remove
eventName.EventEmitter instance was created by some other
+component or module (e.g. sockets or file streams).EventEmitter, so that calls can be chained.Parameters
Optional event: string | symbolReturns this
Since
set
EventEmitters will print a warning if more than 10 listeners are
+added for a particular event. This is a useful default that helps finding
+memory leaks. The emitter.setMaxListeners() method allows the limit to be
+modified for this specific EventEmitter instance. The value can be set toInfinity (or 0) to indicate an unlimited number of listeners.EventEmitter, so that calls can be chained.Parameters
Returns this
Since
get
EventEmitter which is either
+set by emitter.setMaxListeners(n) or defaults to defaultMaxListeners.Returns number
Since
listeners
eventName.
+server.on('connection', (stream) => {
console.log('someone connected!');
});
console.log(util.inspect(server.listeners('connection')));
// Prints: [ [Function] ]
+Type Parameters
Parameters
Returns Function[]
Since
raw
eventName,
+including any wrappers (such as those created by .once()).
+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');
+Type Parameters
Parameters
Returns Function[]
Since
listener
eventName.listener is provided, it will return how many times the listener
+is found in the list of the listeners of the event.Type Parameters
Parameters
Optional listener: FunctionReturns number
Since
event
Symbols.
+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) ]
+Returns (string | symbol)[]
Since
pipe
Type Parameters
Parameters
Optional options: {
end?: boolean;
}Optional end?: booleanReturns T
compose
Type Parameters
Parameters
Optional options: {
signal: AbortSignal;
}signal: AbortSignal
Returns T
Static fromExperimental Readable from a web ReadableStream.Parameters
Optional options: Pick<ReadableOptions, "encoding" | "highWaterMark" | "objectMode" | "signal">Returns Readable
Since
Static isParameters
Returns boolean
Since
Static toExperimental ReadableStream from a Readable.Parameters
Returns ReadableStream<any>
Since
Optional _construct_read
read
readable.read() method reads data out of the internal buffer and
+returns it. If no data is available to be read, null is returned. By default,
+the data is returned as a Buffer object unless an encoding has been
+specified using the readable.setEncoding() method or the stream is operating
+in object mode.size argument specifies a specific number of bytes to read. Ifsize 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.size argument is not specified, all of the data contained in the
+internal buffer will be returned.size argument must be less than or equal to 1 GiB.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.
+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.');
});
+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.readable, it is necessary
+to collect chunks across multiple 'readable' events:
+const chunks = [];
readable.on('readable', () => {
let chunk;
while (null !== (chunk = readable.read())) {
chunks.push(chunk);
}
});
readable.on('end', () => {
const content = chunks.join('');
});
+Readable stream in object mode will always return a single item from
+a call to readable.read(size), regardless of the value of thesize argument.readable.read() method returns a chunk of data, a 'data' event will
+also be emitted.'end' event has
+been emitted will return null. No runtime error will be raised.Parameters
Optional size: numberReturns any
Since
set
readable.setEncoding() method sets the character encoding for
+data read from the Readable stream.Buffer objects. Setting an encoding causes the stream data
+to be returned as strings of the specified encoding rather than as Bufferobjects. For instance, calling readable.setEncoding('utf8') will cause the
+output data to be interpreted as UTF-8 data, and passed as strings. Callingreadable.setEncoding('hex') will cause the data to be encoded in hexadecimal
+string format.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.
+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);
});
+Parameters
Returns this
Since
pause
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.
+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);
});
+readable.pause() method has no effect if there is a 'readable'event listener.Returns this
Since
resume
readable.resume() method causes an explicitly paused Readable stream to
+resume emitting 'data' events, switching the stream into flowing mode.readable.resume() method can be used to fully consume the data from a
+stream without actually processing any of that data:
+getReadableStreamSomehow()
.resume()
.on('end', () => {
console.log('Reached the end, but did not read anything.');
});
+readable.resume() method has no effect if there is a 'readable'event listener.Returns this
Since
is
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.
+const readable = new stream.Readable();
readable.isPaused(); // === false
readable.pause();
readable.isPaused(); // === true
readable.resume();
readable.isPaused(); // === false
+Returns boolean
Since
unpipe
readable.unpipe() method detaches a Writable stream previously attached
+using the pipe method.destination is not specified, then all pipes are detached.destination is specified, but no pipe is set up for it, then
+the method does nothing.
+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);
+Parameters
Optional destination: WritableStreamReturns this
Since
unshift
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.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.stream.unshift(chunk) method cannot be called after the 'end' event
+has been emitted or a runtime error will be thrown.stream.unshift() often should consider switching to
+use of a Transform stream instead. See the API for stream implementers section for more information.
+// 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.includes('\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);
return;
}
// Still reading the header.
header += str;
}
}
}
+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 _read implementation on a
+custom stream). Following the call to readable.unshift() with an immediate 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.Parameters
chunk must be a string, Buffer, Uint8Array or null. For object mode
+streams, chunk may be any JavaScript value.Optional encoding: BufferEncodingBuffer encoding, such as 'utf8' or 'ascii'.Returns void
Since
wrap
stream module API
+as it is currently defined. (See Compatibility for more information.)'data' events and has a pause method that is advisory only, thereadable.wrap() method can be used to create a Readable
+stream that uses
+the old stream as its data source.readable.wrap() but the method has been
+provided as a convenience for interacting with older Node.js applications and
+libraries.
+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.
});
+Parameters
Returns this
Since
push
Parameters
Optional encoding: BufferEncodingReturns boolean
iterator
for await...of loop is exited by return, break, or throw,
+or if the iterator should destroy the stream if the stream emitted an error during iteration.Parameters
Optional options: {
destroyOnReturn?: boolean;
}Optional destroyfalse, calling return on the async iterator,
+or exiting a for await...of iteration using a break, return, or throw will not destroy the stream.
+Default: true.Returns AsyncIterableIterator<any>
Since
map
awaited before being passed to the result stream.Parameters
Parameters
Optional options: Pick<ArrayOptions, "signal">Returns any
Optional options: ArrayOptionsReturns Readable
Since
filter
awaited.Parameters
Parameters
Optional options: Pick<ArrayOptions, "signal">Returns boolean | Promise<boolean>
Optional options: ArrayOptionsReturns Readable
Since
for
awaited.for await...of loops in that it can optionally process chunks concurrently.
+In addition, a forEach iteration can only be stopped by having passed a signal option
+and aborting the related AbortController while for await...of can be stopped with break or return.
+In either case the stream will be destroyed.'data' event in that it uses the readable event
+in the underlying machinary and can limit the number of concurrent fn calls.Parameters
Parameters
Optional options: Pick<ArrayOptions, "signal">Returns void | Promise<void>
Optional options: ArrayOptionsReturns Promise<void>
Since
to
Parameters
Optional options: Pick<ArrayOptions, "signal">Returns Promise<any[]>
Since
some
Array.prototype.some and calls fn on each chunk in the stream
+until the awaited return value is true (or any truthy value). Once an fn call on a chunk
+awaited return value is truthy, the stream is destroyed and the promise is fulfilled with true.
+If none of the fn calls on the chunks return a truthy value, the promise is fulfilled with false.Parameters
Parameters
Optional options: Pick<ArrayOptions, "signal">Returns boolean | Promise<boolean>
Optional options: ArrayOptionsReturns Promise<boolean>
true if fn returned a truthy value for at least one of the chunks.Since
find
Array.prototype.find and calls fn on each chunk in the stream
+to find a chunk with a truthy value for fn. Once an fn call's awaited return value is truthy,
+the stream is destroyed and the promise is fulfilled with value for which fn returned a truthy value.
+If all of the fn calls on the chunks return a falsy value, the promise is fulfilled with undefined.Type Parameters
Parameters
Parameters
Optional options: Pick<ArrayOptions, "signal">Returns data is T
Optional options: ArrayOptionsReturns Promise<T>
undefined if no element was found.Since
Parameters
Parameters
Optional options: Pick<ArrayOptions, "signal">Returns boolean | Promise<boolean>
Optional options: ArrayOptionsReturns Promise<any>
every
Array.prototype.every and calls fn on each chunk in the stream
+to check if all awaited return values are truthy value for fn. Once an fn call on a chunk
+awaited return value is falsy, the stream is destroyed and the promise is fulfilled with false.
+If all of the fn calls on the chunks return a truthy value, the promise is fulfilled with true.Parameters
Parameters
Optional options: Pick<ArrayOptions, "signal">Returns boolean | Promise<boolean>
Optional options: ArrayOptionsReturns Promise<boolean>
true if fn returned a truthy value for every one of the chunks.Since
flat
Parameters
Parameters
Optional options: Pick<ArrayOptions, "signal">Returns any
Optional options: ArrayOptionsReturns Readable
Since
drop
Parameters
Optional options: Pick<ArrayOptions, "signal">Returns Readable
Since
take
Parameters
Optional options: Pick<ArrayOptions, "signal">Returns Readable
Since
as
[index, chunk]. The first index value is 0 and it increases by 1 for each chunk produced.Parameters
Optional options: Pick<ArrayOptions, "signal">Returns Readable
Since
reduce
TypeError with the ERR_INVALID_ARGS code property.readable.map method.Type Parameters
Parameters
Parameters
Optional options: Pick<ArrayOptions, "signal">Returns T
Optional initial: undefinedOptional options: Pick<ArrayOptions, "signal">Returns Promise<T>
Since
Type Parameters
Parameters
Parameters
Optional options: Pick<ArrayOptions, "signal">Returns T
Optional options: Pick<ArrayOptions, "signal">Returns Promise<T>
destroy
'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.destroy() has been called any further calls will be a no-op and no
+further errors except from _destroy() may be emitted as 'error'.readable._destroy().Parameters
Optional error: Error'error' eventReturns this
Since
[async
Returns AsyncIterableIterator<any>
[async
Static from
+
+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 undefinedObject ({ 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.Parameters
Returns Duplex
Since
_write
Parameters
Parameters
Optional error: ErrorReturns void
Returns void
Optional _writevParameters
chunk: any;
encoding: BufferEncoding;
}[]Parameters
Optional error: ErrorReturns void
Returns void
_destroy
_final
write
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.true if the internal buffer is less than thehighWaterMark 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.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.
+Once write() returns false, do not write more chunks
+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.Transform, because the Transform streams are paused
+by default until they are piped or a 'data' or 'readable' event handler
+is added.Readable and use pipe. However, if calling write() is preferred, it is
+possible to respect backpressure and avoid memory issues using the 'drain' event:
+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.');
});
+Writable stream in object mode will always ignore the encoding argument.Parameters
chunk must be a string, Buffer or Uint8Array. For object mode streams, chunk may be any
+JavaScript value other than null.Optional encoding: BufferEncodingOptional cb: ((error) => void)Parameters
Returns void
Returns boolean
false if the stream wishes for the calling code to wait for the 'drain' event to be emitted before continuing to write additional data; otherwise true.Since
Parameters
Optional cb: ((error) => void)Parameters
Returns void
Returns boolean
set
writable.setDefaultEncoding() method sets the default encoding for a Writable stream.Parameters
Returns this
Since
end
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.
+// 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!
+Parameters
Optional cb: (() => void)Returns void
Returns this
Since
Parameters
Optional cb: (() => void)Returns void
Returns this
Parameters
Optional encoding: BufferEncodingOptional cb: (() => void)Returns void
Returns this
cork
writable.cork() method forces all written data to be buffered in memory.
+The buffered data will be flushed when either the uncork or end methods are called.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 implementingwritable._writev() may have an adverse effect on throughput.writable.uncork(), writable._writev().Returns void
Since
uncork
writable.uncork() method flushes all data buffered since cork was called.writable.cork() and writable.uncork() to manage the buffering
+of writes to a stream, defer calls to writable.uncork() usingprocess.nextTick(). Doing so allows batching of allwritable.write() calls that occur within a given Node.js event
+loop phase.
+stream.cork();
stream.write('some ');
stream.write('data ');
process.nextTick(() => stream.uncork());
+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.
+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();
});
+writable.cork().Returns void
Since
add
+
+Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
Parameters
Parameters
Rest ...args: any[]Returns void
Returns this
emit
eventName, in the order they were registered, passing the supplied arguments
+to each.true if the event had listeners, false otherwise.
+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
+Parameters
Returns boolean
Since
Parameters
Returns boolean
Parameters
Returns boolean
Parameters
Returns boolean
Parameters
Returns boolean
Parameters
Returns boolean
Parameters
Returns boolean
Parameters
Returns boolean
Parameters
Returns boolean
Parameters
Returns boolean
Parameters
Returns boolean
Parameters
Rest ...args: any[]Returns boolean
on
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 eventNameand listener will result in the listener being added, and called, multiple
+times.
+server.on('connection', (stream) => {
console.log('someone connected!');
});
+EventEmitter, so that calls can be chained.emitter.prependListener() method can be used as an alternative to add the
+event listener to the beginning of the listeners array.
+const myEE = new EventEmitter();
myEE.on('foo', () => console.log('a'));
myEE.prependListener('foo', () => console.log('b'));
myEE.emit('foo');
// Prints:
// b
// a
+Parameters
Returns void
Returns this
Since
Parameters
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
Parameters
Parameters
Rest ...args: any[]Returns void
Returns this
once
listener function for the event named eventName. The
+next time eventName is triggered, this listener is removed and then invoked.
+server.once('connection', (stream) => {
console.log('Ah, we have our first user!');
});
+EventEmitter, so that calls can be chained.emitter.prependOnceListener() method can be used as an alternative to add the
+event listener to the beginning of the listeners array.
+const myEE = new EventEmitter();
myEE.once('foo', () => console.log('a'));
myEE.prependOnceListener('foo', () => console.log('b'));
myEE.emit('foo');
// Prints:
// b
// a
+Parameters
Returns void
Returns this
Since
Parameters
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
Parameters
Parameters
Rest ...args: any[]Returns void
Returns this
prepend
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 eventNameand listener will result in the listener being added, and called, multiple
+times.
+server.prependListener('connection', (stream) => {
console.log('someone connected!');
});
+EventEmitter, so that calls can be chained.Parameters
Returns void
Returns this
Since
Parameters
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
Parameters
Parameters
Rest ...args: any[]Returns void
Returns this
prepend
listener function for the event named eventName to the beginning of the listeners array. The next time eventName is triggered, this
+listener is removed, and then invoked.
+server.prependOnceListener('connection', (stream) => {
console.log('Ah, we have our first user!');
});
+EventEmitter, so that calls can be chained.Parameters
Returns void
Returns this
Since
Parameters
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
Parameters
Parameters
Rest ...args: any[]Returns void
Returns this
remove
listener from the listener array for the event namedeventName.
+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.removeListener() or removeAllListeners() calls after emitting and before the last listener finishes execution
+will not remove them fromemit() in progress. Subsequent events behave as expected.
+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
+emitter.listeners() method will need to be recreated.removeListener() will remove the most
+recently added instance. In the example the once('ping')listener is removed:
+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');
+EventEmitter, so that calls can be chained.Parameters
Returns void
Returns this
Since
Parameters
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
Parameters
Parameters
Rest ...args: any[]Returns void
Returns this
Class PassThrough
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.Hierarchy (view full)
Index
Constructors
Properties
Methods
Constructors
constructor
Parameters
Optional opts: TransformOptionsReturns PassThrough
Properties
Static Readonly error'error'
+events. Listeners installed using this symbol are called before the regular
+'error' listeners are called.'error' event is emitted, therefore the process will still crash if no
+regular 'error' listener is installed.Static Readonly captureStatic captureStatic defaultReadonly Experimental readable'end'.Since
readable
true if it is safe to call readable.read(), which means
+the stream has not been destroyed or emitted 'error' or 'end'.Since
Readonly Experimental readable'data' has been emitted.Since
Readonly readableencoding of a given Readable stream. The encodingproperty can be set using the readable.setEncoding() method.Since
Readonly readabletrue when 'end' event is emitted.Since
Readonly readableReadable stream as described
+in the Three states section.Since
Readonly readablehighWaterMark passed when creating this Readable.Since
Readonly readablehighWaterMark.Since
Readonly readableobjectMode of a given Readable stream.Since
destroyed
true after readable.destroy() has been called.Since
Readonly writabletrue if it is safe to call writable.write(), which means
+the stream has not been destroyed, errored or ended.Since
Readonly writabletrue after writable.end() has been called. This property
+does not indicate whether the data has been flushed, for this use writable.writableFinished instead.Since
Readonly writabletrue immediately before the 'finish' event is emitted.Since
Readonly writablehighWaterMark passed when creating this Writable.Since
Readonly writablehighWaterMark.Since
Readonly writableobjectMode of a given Writable stream.Since
Readonly writablewritable.uncork() needs to be
+called in order to fully uncork the stream.Since
Readonly writabletrue if the stream's buffer has been full and stream will emit 'drain'.Since
Readonly closedSince
Readonly erroredSince
allow
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.Duplex stream instance, but must be changed before the 'end' event is
+emitted.Since
Methods
Optional [captureStatic oncePromise 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.'error' event
+semantics and does not listen to the 'error' event.
+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();
+'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:
+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
+AbortSignal can be used to cancel waiting for the event:
+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!
+Parameters
Optional options: StaticEventEmitterOptionsReturns Promise<any[]>
Since
Parameters
Optional options: StaticEventEmitterOptionsReturns Promise<any[]>
Static on
+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
})();
+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.AbortSignal can be used to cancel waiting on events:
+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());
+Parameters
Optional options: StaticEventEmitterOptionsReturns AsyncIterableIterator<any>
eventName events emitted by the emitterSince
Static listenereventNameregistered on the given emitter.
+const { EventEmitter, listenerCount } = require('events');
const myEmitter = new EventEmitter();
myEmitter.on('event', () => {});
myEmitter.on('event', () => {});
console.log(listenerCount(myEmitter, 'event'));
// Prints: 2
+Parameters
Returns number
Since
Deprecated
listenerCount instead.Static geteventName.EventEmitters this behaves exactly the same as calling .listeners on
+the emitter.EventTargets this is the only way to get the event listeners for the
+event target. This is useful for debugging and diagnostic purposes.
+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]
}
+Parameters
Returns Function[]
Since
Static getEventEmitters this behaves exactly the same as calling .getMaxListeners on
+the emitter.EventTargets this is the only way to get the max event listeners for the
+event target. If the number of event handlers on a single EventTarget exceeds
+the max set, the EventTarget will print a warning.
+import { getMaxListeners, setMaxListeners, EventEmitter } from 'node:events';
{
const ee = new EventEmitter();
console.log(getMaxListeners(ee)); // 10
setMaxListeners(11, ee);
console.log(getMaxListeners(ee)); // 11
}
{
const et = new EventTarget();
console.log(getMaxListeners(et)); // 10
setMaxListeners(11, et);
console.log(getMaxListeners(et)); // 11
}
+Parameters
Returns number
Since
Static set
+const {
setMaxListeners,
EventEmitter
} = require('events');
const target = new EventTarget();
const emitter = new EventEmitter();
setMaxListeners(5, target, emitter);
+Parameters
Optional n: numberEventTarget event.Rest ...eventTargets: (EventEmitter<DefaultEventMap> | _DOMEventTarget)[]Returns void
Since
Static addExperimental abort event on the provided signal.abort event on abort signals is unsafe and may
+lead to resource leaks since another third party with the signal can
+call e.stopImmediatePropagation(). Unfortunately Node.js cannot change
+this since it would violate the web standard. Additionally, the original
+API makes it easy to forget to remove listeners.AbortSignals in Node.js APIs by solving these
+two issues by listening to the event such that stopImmediatePropagation does
+not prevent the listener from running.
+import { addAbortListener } from 'node:events';
function example(signal) {
let disposable;
try {
signal.addEventListener('abort', (e) => e.stopImmediatePropagation());
disposable = addAbortListener(signal, (e) => {
// Do something when signal is aborted.
});
} finally {
disposable?.[Symbol.dispose]();
}
}
+Parameters
Parameters
Returns void
Returns Disposable
abort listener.Since
off
emitter.removeListener().Type Parameters
Parameters
Parameters
Rest ...args: any[]Returns void
Returns this
Since
remove
eventName.EventEmitter instance was created by some other
+component or module (e.g. sockets or file streams).EventEmitter, so that calls can be chained.Parameters
Optional event: string | symbolReturns this
Since
set
EventEmitters will print a warning if more than 10 listeners are
+added for a particular event. This is a useful default that helps finding
+memory leaks. The emitter.setMaxListeners() method allows the limit to be
+modified for this specific EventEmitter instance. The value can be set toInfinity (or 0) to indicate an unlimited number of listeners.EventEmitter, so that calls can be chained.Parameters
Returns this
Since
get
EventEmitter which is either
+set by emitter.setMaxListeners(n) or defaults to defaultMaxListeners.Returns number
Since
listeners
eventName.
+server.on('connection', (stream) => {
console.log('someone connected!');
});
console.log(util.inspect(server.listeners('connection')));
// Prints: [ [Function] ]
+Type Parameters
Parameters
Returns Function[]
Since
raw
eventName,
+including any wrappers (such as those created by .once()).
+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');
+Type Parameters
Parameters
Returns Function[]
Since
listener
eventName.listener is provided, it will return how many times the listener
+is found in the list of the listeners of the event.Type Parameters
Parameters
Optional listener: FunctionReturns number
Since
event
Symbols.
+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) ]
+Returns (string | symbol)[]
Since
pipe
Type Parameters
Parameters
Optional options: {
end?: boolean;
}Optional end?: booleanReturns T
compose
Type Parameters
Parameters
Optional options: {
signal: AbortSignal;
}signal: AbortSignal
Returns T
Static fromExperimental Readable from a web ReadableStream.Parameters
Optional options: Pick<ReadableOptions, "encoding" | "highWaterMark" | "objectMode" | "signal">Returns Readable
Since
Static isParameters
Returns boolean
Since
Static toExperimental ReadableStream from a Readable.Parameters
Returns ReadableStream<any>
Since
Optional _construct_read
read
readable.read() method reads data out of the internal buffer and
+returns it. If no data is available to be read, null is returned. By default,
+the data is returned as a Buffer object unless an encoding has been
+specified using the readable.setEncoding() method or the stream is operating
+in object mode.size argument specifies a specific number of bytes to read. Ifsize 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.size argument is not specified, all of the data contained in the
+internal buffer will be returned.size argument must be less than or equal to 1 GiB.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.
+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.');
});
+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.readable, it is necessary
+to collect chunks across multiple 'readable' events:
+const chunks = [];
readable.on('readable', () => {
let chunk;
while (null !== (chunk = readable.read())) {
chunks.push(chunk);
}
});
readable.on('end', () => {
const content = chunks.join('');
});
+Readable stream in object mode will always return a single item from
+a call to readable.read(size), regardless of the value of thesize argument.readable.read() method returns a chunk of data, a 'data' event will
+also be emitted.'end' event has
+been emitted will return null. No runtime error will be raised.Parameters
Optional size: numberReturns any
Since
set
readable.setEncoding() method sets the character encoding for
+data read from the Readable stream.Buffer objects. Setting an encoding causes the stream data
+to be returned as strings of the specified encoding rather than as Bufferobjects. For instance, calling readable.setEncoding('utf8') will cause the
+output data to be interpreted as UTF-8 data, and passed as strings. Callingreadable.setEncoding('hex') will cause the data to be encoded in hexadecimal
+string format.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.
+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);
});
+Parameters
Returns this
Since
pause
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.
+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);
});
+readable.pause() method has no effect if there is a 'readable'event listener.Returns this
Since
resume
readable.resume() method causes an explicitly paused Readable stream to
+resume emitting 'data' events, switching the stream into flowing mode.readable.resume() method can be used to fully consume the data from a
+stream without actually processing any of that data:
+getReadableStreamSomehow()
.resume()
.on('end', () => {
console.log('Reached the end, but did not read anything.');
});
+readable.resume() method has no effect if there is a 'readable'event listener.Returns this
Since
is
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.
+const readable = new stream.Readable();
readable.isPaused(); // === false
readable.pause();
readable.isPaused(); // === true
readable.resume();
readable.isPaused(); // === false
+Returns boolean
Since
unpipe
readable.unpipe() method detaches a Writable stream previously attached
+using the pipe method.destination is not specified, then all pipes are detached.destination is specified, but no pipe is set up for it, then
+the method does nothing.
+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);
+Parameters
Optional destination: WritableStreamReturns this
Since
unshift
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.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.stream.unshift(chunk) method cannot be called after the 'end' event
+has been emitted or a runtime error will be thrown.stream.unshift() often should consider switching to
+use of a Transform stream instead. See the API for stream implementers section for more information.
+// 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.includes('\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);
return;
}
// Still reading the header.
header += str;
}
}
}
+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 _read implementation on a
+custom stream). Following the call to readable.unshift() with an immediate 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.Parameters
chunk must be a string, Buffer, Uint8Array or null. For object mode
+streams, chunk may be any JavaScript value.Optional encoding: BufferEncodingBuffer encoding, such as 'utf8' or 'ascii'.Returns void
Since
wrap
stream module API
+as it is currently defined. (See Compatibility for more information.)'data' events and has a pause method that is advisory only, thereadable.wrap() method can be used to create a Readable
+stream that uses
+the old stream as its data source.readable.wrap() but the method has been
+provided as a convenience for interacting with older Node.js applications and
+libraries.
+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.
});
+Parameters
Returns this
Since
push
Parameters
Optional encoding: BufferEncodingReturns boolean
iterator
for await...of loop is exited by return, break, or throw,
+or if the iterator should destroy the stream if the stream emitted an error during iteration.Parameters
Optional options: {
destroyOnReturn?: boolean;
}Optional destroyfalse, calling return on the async iterator,
+or exiting a for await...of iteration using a break, return, or throw will not destroy the stream.
+Default: true.Returns AsyncIterableIterator<any>
Since
map
awaited before being passed to the result stream.Parameters
Parameters
Optional options: Pick<ArrayOptions, "signal">Returns any
Optional options: ArrayOptionsReturns Readable
Since
filter
awaited.Parameters
Parameters
Optional options: Pick<ArrayOptions, "signal">Returns boolean | Promise<boolean>
Optional options: ArrayOptionsReturns Readable
Since
for
awaited.for await...of loops in that it can optionally process chunks concurrently.
+In addition, a forEach iteration can only be stopped by having passed a signal option
+and aborting the related AbortController while for await...of can be stopped with break or return.
+In either case the stream will be destroyed.'data' event in that it uses the readable event
+in the underlying machinary and can limit the number of concurrent fn calls.Parameters
Parameters
Optional options: Pick<ArrayOptions, "signal">Returns void | Promise<void>
Optional options: ArrayOptionsReturns Promise<void>
Since
to
Parameters
Optional options: Pick<ArrayOptions, "signal">Returns Promise<any[]>
Since
some
Array.prototype.some and calls fn on each chunk in the stream
+until the awaited return value is true (or any truthy value). Once an fn call on a chunk
+awaited return value is truthy, the stream is destroyed and the promise is fulfilled with true.
+If none of the fn calls on the chunks return a truthy value, the promise is fulfilled with false.Parameters
Parameters
Optional options: Pick<ArrayOptions, "signal">Returns boolean | Promise<boolean>
Optional options: ArrayOptionsReturns Promise<boolean>
true if fn returned a truthy value for at least one of the chunks.Since
find
Array.prototype.find and calls fn on each chunk in the stream
+to find a chunk with a truthy value for fn. Once an fn call's awaited return value is truthy,
+the stream is destroyed and the promise is fulfilled with value for which fn returned a truthy value.
+If all of the fn calls on the chunks return a falsy value, the promise is fulfilled with undefined.Type Parameters
Parameters
Parameters
Optional options: Pick<ArrayOptions, "signal">Returns data is T
Optional options: ArrayOptionsReturns Promise<T>
undefined if no element was found.Since
Parameters
Parameters
Optional options: Pick<ArrayOptions, "signal">Returns boolean | Promise<boolean>
Optional options: ArrayOptionsReturns Promise<any>
every
Array.prototype.every and calls fn on each chunk in the stream
+to check if all awaited return values are truthy value for fn. Once an fn call on a chunk
+awaited return value is falsy, the stream is destroyed and the promise is fulfilled with false.
+If all of the fn calls on the chunks return a truthy value, the promise is fulfilled with true.Parameters
Parameters
Optional options: Pick<ArrayOptions, "signal">Returns boolean | Promise<boolean>
Optional options: ArrayOptionsReturns Promise<boolean>
true if fn returned a truthy value for every one of the chunks.Since
flat
Parameters
Parameters
Optional options: Pick<ArrayOptions, "signal">Returns any
Optional options: ArrayOptionsReturns Readable
Since
drop
Parameters
Optional options: Pick<ArrayOptions, "signal">Returns Readable
Since
take
Parameters
Optional options: Pick<ArrayOptions, "signal">Returns Readable
Since
as
[index, chunk]. The first index value is 0 and it increases by 1 for each chunk produced.Parameters
Optional options: Pick<ArrayOptions, "signal">Returns Readable
Since
reduce
TypeError with the ERR_INVALID_ARGS code property.readable.map method.Type Parameters
Parameters
Parameters
Optional options: Pick<ArrayOptions, "signal">Returns T
Optional initial: undefinedOptional options: Pick<ArrayOptions, "signal">Returns Promise<T>
Since
Type Parameters
Parameters
Parameters
Optional options: Pick<ArrayOptions, "signal">Returns T
Optional options: Pick<ArrayOptions, "signal">Returns Promise<T>
destroy
'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.destroy() has been called any further calls will be a no-op and no
+further errors except from _destroy() may be emitted as 'error'.readable._destroy().Parameters
Optional error: Error'error' eventReturns this
Since
[async
Returns AsyncIterableIterator<any>
[async
Static from
+
+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 undefinedObject ({ 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.Parameters
Returns Duplex
Since
_write
Parameters
Parameters
Optional error: ErrorReturns void
Returns void
Optional _writevParameters
chunk: any;
encoding: BufferEncoding;
}[]Parameters
Optional error: ErrorReturns void
Returns void
_destroy
_final
write
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.true if the internal buffer is less than thehighWaterMark 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.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.
+Once write() returns false, do not write more chunks
+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.Transform, because the Transform streams are paused
+by default until they are piped or a 'data' or 'readable' event handler
+is added.Readable and use pipe. However, if calling write() is preferred, it is
+possible to respect backpressure and avoid memory issues using the 'drain' event:
+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.');
});
+Writable stream in object mode will always ignore the encoding argument.Parameters
chunk must be a string, Buffer or Uint8Array. For object mode streams, chunk may be any
+JavaScript value other than null.Optional encoding: BufferEncodingOptional cb: ((error) => void)Parameters
Returns void
Returns boolean
false if the stream wishes for the calling code to wait for the 'drain' event to be emitted before continuing to write additional data; otherwise true.Since
Parameters
Optional cb: ((error) => void)Parameters
Returns void
Returns boolean
set
writable.setDefaultEncoding() method sets the default encoding for a Writable stream.Parameters
Returns this
Since
end
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.
+// 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!
+Parameters
Optional cb: (() => void)Returns void
Returns this
Since
Parameters
Optional cb: (() => void)Returns void
Returns this
Parameters
Optional encoding: BufferEncodingOptional cb: (() => void)Returns void
Returns this
cork
writable.cork() method forces all written data to be buffered in memory.
+The buffered data will be flushed when either the uncork or end methods are called.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 implementingwritable._writev() may have an adverse effect on throughput.writable.uncork(), writable._writev().Returns void
Since
uncork
writable.uncork() method flushes all data buffered since cork was called.writable.cork() and writable.uncork() to manage the buffering
+of writes to a stream, defer calls to writable.uncork() usingprocess.nextTick(). Doing so allows batching of allwritable.write() calls that occur within a given Node.js event
+loop phase.
+stream.cork();
stream.write('some ');
stream.write('data ');
process.nextTick(() => stream.uncork());
+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.
+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();
});
+writable.cork().Returns void
Since
add
+
+Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
Parameters
Parameters
Rest ...args: any[]Returns void
Returns this
emit
eventName, in the order they were registered, passing the supplied arguments
+to each.true if the event had listeners, false otherwise.
+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
+Parameters
Returns boolean
Since
Parameters
Returns boolean
Parameters
Returns boolean
Parameters
Returns boolean
Parameters
Returns boolean
Parameters
Returns boolean
Parameters
Returns boolean
Parameters
Returns boolean
Parameters
Returns boolean
Parameters
Returns boolean
Parameters
Returns boolean
Parameters
Rest ...args: any[]Returns boolean
on
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 eventNameand listener will result in the listener being added, and called, multiple
+times.
+server.on('connection', (stream) => {
console.log('someone connected!');
});
+EventEmitter, so that calls can be chained.emitter.prependListener() method can be used as an alternative to add the
+event listener to the beginning of the listeners array.
+const myEE = new EventEmitter();
myEE.on('foo', () => console.log('a'));
myEE.prependListener('foo', () => console.log('b'));
myEE.emit('foo');
// Prints:
// b
// a
+Parameters
Returns void
Returns this
Since
Parameters
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
Parameters
Parameters
Rest ...args: any[]Returns void
Returns this
once
listener function for the event named eventName. The
+next time eventName is triggered, this listener is removed and then invoked.
+server.once('connection', (stream) => {
console.log('Ah, we have our first user!');
});
+EventEmitter, so that calls can be chained.emitter.prependOnceListener() method can be used as an alternative to add the
+event listener to the beginning of the listeners array.
+const myEE = new EventEmitter();
myEE.once('foo', () => console.log('a'));
myEE.prependOnceListener('foo', () => console.log('b'));
myEE.emit('foo');
// Prints:
// b
// a
+Parameters
Returns void
Returns this
Since
Parameters
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
Parameters
Parameters
Rest ...args: any[]Returns void
Returns this
prepend
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 eventNameand listener will result in the listener being added, and called, multiple
+times.
+server.prependListener('connection', (stream) => {
console.log('someone connected!');
});
+EventEmitter, so that calls can be chained.Parameters
Returns void
Returns this
Since
Parameters
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
Parameters
Parameters
Rest ...args: any[]Returns void
Returns this
prepend
listener function for the event named eventName to the beginning of the listeners array. The next time eventName is triggered, this
+listener is removed, and then invoked.
+server.prependOnceListener('connection', (stream) => {
console.log('Ah, we have our first user!');
});
+EventEmitter, so that calls can be chained.Parameters
Returns void
Returns this
Since
Parameters
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
Parameters
Parameters
Rest ...args: any[]Returns void
Returns this
remove
listener from the listener array for the event namedeventName.
+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.removeListener() or removeAllListeners() calls after emitting and before the last listener finishes execution
+will not remove them fromemit() in progress. Subsequent events behave as expected.
+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
+emitter.listeners() method will need to be recreated.removeListener() will remove the most
+recently added instance. In the example the once('ping')listener is removed:
+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');
+EventEmitter, so that calls can be chained.Parameters
Returns void
Returns this
Since
Parameters
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
Parameters
Parameters
Rest ...args: any[]Returns void
Returns this
_transform
Parameters
Returns void
_flush
Parameters
Returns void
Class Transform
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.Transform streams include:
+
+zlib streamscrypto streamsSince
Hierarchy (view full)
Index
Constructors
Properties
Methods
Constructors
constructor
Parameters
Optional opts: TransformOptionsReturns Transform
Properties
Static Readonly error'error'
+events. Listeners installed using this symbol are called before the regular
+'error' listeners are called.'error' event is emitted, therefore the process will still crash if no
+regular 'error' listener is installed.Static Readonly captureStatic captureStatic defaultReadonly Experimental readable'end'.Since
readable
true if it is safe to call readable.read(), which means
+the stream has not been destroyed or emitted 'error' or 'end'.Since
Readonly Experimental readable'data' has been emitted.Since
Readonly readableencoding of a given Readable stream. The encodingproperty can be set using the readable.setEncoding() method.Since
Readonly readabletrue when 'end' event is emitted.Since
Readonly readableReadable stream as described
+in the Three states section.Since
Readonly readablehighWaterMark passed when creating this Readable.Since
Readonly readablehighWaterMark.Since
Readonly readableobjectMode of a given Readable stream.Since
destroyed
true after readable.destroy() has been called.Since
Readonly writabletrue if it is safe to call writable.write(), which means
+the stream has not been destroyed, errored or ended.Since
Readonly writabletrue after writable.end() has been called. This property
+does not indicate whether the data has been flushed, for this use writable.writableFinished instead.Since
Readonly writabletrue immediately before the 'finish' event is emitted.Since
Readonly writablehighWaterMark passed when creating this Writable.Since
Readonly writablehighWaterMark.Since
Readonly writableobjectMode of a given Writable stream.Since
Readonly writablewritable.uncork() needs to be
+called in order to fully uncork the stream.Since
Readonly writabletrue if the stream's buffer has been full and stream will emit 'drain'.Since
Readonly closedSince
Readonly erroredSince
allow
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.Duplex stream instance, but must be changed before the 'end' event is
+emitted.Since
Methods
Optional [captureStatic oncePromise 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.'error' event
+semantics and does not listen to the 'error' event.
+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();
+'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:
+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
+AbortSignal can be used to cancel waiting for the event:
+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!
+Parameters
Optional options: StaticEventEmitterOptionsReturns Promise<any[]>
Since
Parameters
Optional options: StaticEventEmitterOptionsReturns Promise<any[]>
Static on
+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
})();
+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.AbortSignal can be used to cancel waiting on events:
+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());
+Parameters
Optional options: StaticEventEmitterOptionsReturns AsyncIterableIterator<any>
eventName events emitted by the emitterSince
Static listenereventNameregistered on the given emitter.
+const { EventEmitter, listenerCount } = require('events');
const myEmitter = new EventEmitter();
myEmitter.on('event', () => {});
myEmitter.on('event', () => {});
console.log(listenerCount(myEmitter, 'event'));
// Prints: 2
+Parameters
Returns number
Since
Deprecated
listenerCount instead.Static geteventName.EventEmitters this behaves exactly the same as calling .listeners on
+the emitter.EventTargets this is the only way to get the event listeners for the
+event target. This is useful for debugging and diagnostic purposes.
+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]
}
+Parameters
Returns Function[]
Since
Static getEventEmitters this behaves exactly the same as calling .getMaxListeners on
+the emitter.EventTargets this is the only way to get the max event listeners for the
+event target. If the number of event handlers on a single EventTarget exceeds
+the max set, the EventTarget will print a warning.
+import { getMaxListeners, setMaxListeners, EventEmitter } from 'node:events';
{
const ee = new EventEmitter();
console.log(getMaxListeners(ee)); // 10
setMaxListeners(11, ee);
console.log(getMaxListeners(ee)); // 11
}
{
const et = new EventTarget();
console.log(getMaxListeners(et)); // 10
setMaxListeners(11, et);
console.log(getMaxListeners(et)); // 11
}
+Parameters
Returns number
Since
Static set
+const {
setMaxListeners,
EventEmitter
} = require('events');
const target = new EventTarget();
const emitter = new EventEmitter();
setMaxListeners(5, target, emitter);
+Parameters
Optional n: numberEventTarget event.Rest ...eventTargets: (EventEmitter<DefaultEventMap> | _DOMEventTarget)[]Returns void
Since
Static addExperimental abort event on the provided signal.abort event on abort signals is unsafe and may
+lead to resource leaks since another third party with the signal can
+call e.stopImmediatePropagation(). Unfortunately Node.js cannot change
+this since it would violate the web standard. Additionally, the original
+API makes it easy to forget to remove listeners.AbortSignals in Node.js APIs by solving these
+two issues by listening to the event such that stopImmediatePropagation does
+not prevent the listener from running.
+import { addAbortListener } from 'node:events';
function example(signal) {
let disposable;
try {
signal.addEventListener('abort', (e) => e.stopImmediatePropagation());
disposable = addAbortListener(signal, (e) => {
// Do something when signal is aborted.
});
} finally {
disposable?.[Symbol.dispose]();
}
}
+Parameters
Parameters
Returns void
Returns Disposable
abort listener.Since
off
emitter.removeListener().Type Parameters
Parameters
Parameters
Rest ...args: any[]Returns void
Returns this
Since
remove
eventName.EventEmitter instance was created by some other
+component or module (e.g. sockets or file streams).EventEmitter, so that calls can be chained.Parameters
Optional event: string | symbolReturns this
Since
set
EventEmitters will print a warning if more than 10 listeners are
+added for a particular event. This is a useful default that helps finding
+memory leaks. The emitter.setMaxListeners() method allows the limit to be
+modified for this specific EventEmitter instance. The value can be set toInfinity (or 0) to indicate an unlimited number of listeners.EventEmitter, so that calls can be chained.Parameters
Returns this
Since
get
EventEmitter which is either
+set by emitter.setMaxListeners(n) or defaults to defaultMaxListeners.Returns number
Since
listeners
eventName.
+server.on('connection', (stream) => {
console.log('someone connected!');
});
console.log(util.inspect(server.listeners('connection')));
// Prints: [ [Function] ]
+Type Parameters
Parameters
Returns Function[]
Since
raw
eventName,
+including any wrappers (such as those created by .once()).
+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');
+Type Parameters
Parameters
Returns Function[]
Since
listener
eventName.listener is provided, it will return how many times the listener
+is found in the list of the listeners of the event.Type Parameters
Parameters
Optional listener: FunctionReturns number
Since
event
Symbols.
+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) ]
+Returns (string | symbol)[]
Since
pipe
Type Parameters
Parameters
Optional options: {
end?: boolean;
}Optional end?: booleanReturns T
compose
Type Parameters
Parameters
Optional options: {
signal: AbortSignal;
}signal: AbortSignal
Returns T
Static fromExperimental Readable from a web ReadableStream.Parameters
Optional options: Pick<ReadableOptions, "encoding" | "highWaterMark" | "objectMode" | "signal">Returns Readable
Since
Static isParameters
Returns boolean
Since
Static toExperimental ReadableStream from a Readable.Parameters
Returns ReadableStream<any>
Since
Optional _construct_read
read
readable.read() method reads data out of the internal buffer and
+returns it. If no data is available to be read, null is returned. By default,
+the data is returned as a Buffer object unless an encoding has been
+specified using the readable.setEncoding() method or the stream is operating
+in object mode.size argument specifies a specific number of bytes to read. Ifsize 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.size argument is not specified, all of the data contained in the
+internal buffer will be returned.size argument must be less than or equal to 1 GiB.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.
+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.');
});
+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.readable, it is necessary
+to collect chunks across multiple 'readable' events:
+const chunks = [];
readable.on('readable', () => {
let chunk;
while (null !== (chunk = readable.read())) {
chunks.push(chunk);
}
});
readable.on('end', () => {
const content = chunks.join('');
});
+Readable stream in object mode will always return a single item from
+a call to readable.read(size), regardless of the value of thesize argument.readable.read() method returns a chunk of data, a 'data' event will
+also be emitted.'end' event has
+been emitted will return null. No runtime error will be raised.Parameters
Optional size: numberReturns any
Since
set
readable.setEncoding() method sets the character encoding for
+data read from the Readable stream.Buffer objects. Setting an encoding causes the stream data
+to be returned as strings of the specified encoding rather than as Bufferobjects. For instance, calling readable.setEncoding('utf8') will cause the
+output data to be interpreted as UTF-8 data, and passed as strings. Callingreadable.setEncoding('hex') will cause the data to be encoded in hexadecimal
+string format.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.
+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);
});
+Parameters
Returns this
Since
pause
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.
+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);
});
+readable.pause() method has no effect if there is a 'readable'event listener.Returns this
Since
resume
readable.resume() method causes an explicitly paused Readable stream to
+resume emitting 'data' events, switching the stream into flowing mode.readable.resume() method can be used to fully consume the data from a
+stream without actually processing any of that data:
+getReadableStreamSomehow()
.resume()
.on('end', () => {
console.log('Reached the end, but did not read anything.');
});
+readable.resume() method has no effect if there is a 'readable'event listener.Returns this
Since
is
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.
+const readable = new stream.Readable();
readable.isPaused(); // === false
readable.pause();
readable.isPaused(); // === true
readable.resume();
readable.isPaused(); // === false
+Returns boolean
Since
unpipe
readable.unpipe() method detaches a Writable stream previously attached
+using the pipe method.destination is not specified, then all pipes are detached.destination is specified, but no pipe is set up for it, then
+the method does nothing.
+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);
+Parameters
Optional destination: WritableStreamReturns this
Since
unshift
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.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.stream.unshift(chunk) method cannot be called after the 'end' event
+has been emitted or a runtime error will be thrown.stream.unshift() often should consider switching to
+use of a Transform stream instead. See the API for stream implementers section for more information.
+// 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.includes('\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);
return;
}
// Still reading the header.
header += str;
}
}
}
+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 _read implementation on a
+custom stream). Following the call to readable.unshift() with an immediate 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.Parameters
chunk must be a string, Buffer, Uint8Array or null. For object mode
+streams, chunk may be any JavaScript value.Optional encoding: BufferEncodingBuffer encoding, such as 'utf8' or 'ascii'.Returns void
Since
wrap
stream module API
+as it is currently defined. (See Compatibility for more information.)'data' events and has a pause method that is advisory only, thereadable.wrap() method can be used to create a Readable
+stream that uses
+the old stream as its data source.readable.wrap() but the method has been
+provided as a convenience for interacting with older Node.js applications and
+libraries.
+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.
});
+Parameters
Returns this
Since
push
Parameters
Optional encoding: BufferEncodingReturns boolean
iterator
for await...of loop is exited by return, break, or throw,
+or if the iterator should destroy the stream if the stream emitted an error during iteration.Parameters
Optional options: {
destroyOnReturn?: boolean;
}Optional destroyfalse, calling return on the async iterator,
+or exiting a for await...of iteration using a break, return, or throw will not destroy the stream.
+Default: true.Returns AsyncIterableIterator<any>
Since
map
awaited before being passed to the result stream.Parameters
Parameters
Optional options: Pick<ArrayOptions, "signal">Returns any
Optional options: ArrayOptionsReturns Readable
Since
filter
awaited.Parameters
Parameters
Optional options: Pick<ArrayOptions, "signal">Returns boolean | Promise<boolean>
Optional options: ArrayOptionsReturns Readable
Since
for
awaited.for await...of loops in that it can optionally process chunks concurrently.
+In addition, a forEach iteration can only be stopped by having passed a signal option
+and aborting the related AbortController while for await...of can be stopped with break or return.
+In either case the stream will be destroyed.'data' event in that it uses the readable event
+in the underlying machinary and can limit the number of concurrent fn calls.Parameters
Parameters
Optional options: Pick<ArrayOptions, "signal">Returns void | Promise<void>
Optional options: ArrayOptionsReturns Promise<void>
Since
to
Parameters
Optional options: Pick<ArrayOptions, "signal">Returns Promise<any[]>
Since
some
Array.prototype.some and calls fn on each chunk in the stream
+until the awaited return value is true (or any truthy value). Once an fn call on a chunk
+awaited return value is truthy, the stream is destroyed and the promise is fulfilled with true.
+If none of the fn calls on the chunks return a truthy value, the promise is fulfilled with false.Parameters
Parameters
Optional options: Pick<ArrayOptions, "signal">Returns boolean | Promise<boolean>
Optional options: ArrayOptionsReturns Promise<boolean>
true if fn returned a truthy value for at least one of the chunks.Since
find
Array.prototype.find and calls fn on each chunk in the stream
+to find a chunk with a truthy value for fn. Once an fn call's awaited return value is truthy,
+the stream is destroyed and the promise is fulfilled with value for which fn returned a truthy value.
+If all of the fn calls on the chunks return a falsy value, the promise is fulfilled with undefined.Type Parameters
Parameters
Parameters
Optional options: Pick<ArrayOptions, "signal">Returns data is T
Optional options: ArrayOptionsReturns Promise<T>
undefined if no element was found.Since
Parameters
Parameters
Optional options: Pick<ArrayOptions, "signal">Returns boolean | Promise<boolean>
Optional options: ArrayOptionsReturns Promise<any>
every
Array.prototype.every and calls fn on each chunk in the stream
+to check if all awaited return values are truthy value for fn. Once an fn call on a chunk
+awaited return value is falsy, the stream is destroyed and the promise is fulfilled with false.
+If all of the fn calls on the chunks return a truthy value, the promise is fulfilled with true.Parameters
Parameters
Optional options: Pick<ArrayOptions, "signal">Returns boolean | Promise<boolean>
Optional options: ArrayOptionsReturns Promise<boolean>
true if fn returned a truthy value for every one of the chunks.Since
flat
Parameters
Parameters
Optional options: Pick<ArrayOptions, "signal">Returns any
Optional options: ArrayOptionsReturns Readable
Since
drop
Parameters
Optional options: Pick<ArrayOptions, "signal">Returns Readable
Since
take
Parameters
Optional options: Pick<ArrayOptions, "signal">Returns Readable
Since
as
[index, chunk]. The first index value is 0 and it increases by 1 for each chunk produced.Parameters
Optional options: Pick<ArrayOptions, "signal">Returns Readable
Since
reduce
TypeError with the ERR_INVALID_ARGS code property.readable.map method.Type Parameters
Parameters
Parameters
Optional options: Pick<ArrayOptions, "signal">Returns T
Optional initial: undefinedOptional options: Pick<ArrayOptions, "signal">Returns Promise<T>
Since
Type Parameters
Parameters
Parameters
Optional options: Pick<ArrayOptions, "signal">Returns T
Optional options: Pick<ArrayOptions, "signal">Returns Promise<T>
destroy
'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.destroy() has been called any further calls will be a no-op and no
+further errors except from _destroy() may be emitted as 'error'.readable._destroy().Parameters
Optional error: Error'error' eventReturns this
Since
[async
Returns AsyncIterableIterator<any>
[async
Static from
+
+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 undefinedObject ({ 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.Parameters
Returns Duplex
Since
_write
Parameters
Parameters
Optional error: ErrorReturns void
Returns void
Optional _writevParameters
chunk: any;
encoding: BufferEncoding;
}[]Parameters
Optional error: ErrorReturns void
Returns void
_destroy
_final
write
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.true if the internal buffer is less than thehighWaterMark 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.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.
+Once write() returns false, do not write more chunks
+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.Transform, because the Transform streams are paused
+by default until they are piped or a 'data' or 'readable' event handler
+is added.Readable and use pipe. However, if calling write() is preferred, it is
+possible to respect backpressure and avoid memory issues using the 'drain' event:
+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.');
});
+Writable stream in object mode will always ignore the encoding argument.Parameters
chunk must be a string, Buffer or Uint8Array. For object mode streams, chunk may be any
+JavaScript value other than null.Optional encoding: BufferEncodingOptional cb: ((error) => void)Parameters
Returns void
Returns boolean
false if the stream wishes for the calling code to wait for the 'drain' event to be emitted before continuing to write additional data; otherwise true.Since
Parameters
Optional cb: ((error) => void)Parameters
Returns void
Returns boolean
set
writable.setDefaultEncoding() method sets the default encoding for a Writable stream.Parameters
Returns this
Since
end
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.
+// 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!
+Parameters
Optional cb: (() => void)Returns void
Returns this
Since
Parameters
Optional cb: (() => void)Returns void
Returns this
Parameters
Optional encoding: BufferEncodingOptional cb: (() => void)Returns void
Returns this
cork
writable.cork() method forces all written data to be buffered in memory.
+The buffered data will be flushed when either the uncork or end methods are called.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 implementingwritable._writev() may have an adverse effect on throughput.writable.uncork(), writable._writev().Returns void
Since
uncork
writable.uncork() method flushes all data buffered since cork was called.writable.cork() and writable.uncork() to manage the buffering
+of writes to a stream, defer calls to writable.uncork() usingprocess.nextTick(). Doing so allows batching of allwritable.write() calls that occur within a given Node.js event
+loop phase.
+stream.cork();
stream.write('some ');
stream.write('data ');
process.nextTick(() => stream.uncork());
+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.
+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();
});
+writable.cork().Returns void
Since
add
+
+Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
Parameters
Parameters
Rest ...args: any[]Returns void
Returns this
emit
eventName, in the order they were registered, passing the supplied arguments
+to each.true if the event had listeners, false otherwise.
+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
+Parameters
Returns boolean
Since
Parameters
Returns boolean
Parameters
Returns boolean
Parameters
Returns boolean
Parameters
Returns boolean
Parameters
Returns boolean
Parameters
Returns boolean
Parameters
Returns boolean
Parameters
Returns boolean
Parameters
Returns boolean
Parameters
Returns boolean
Parameters
Rest ...args: any[]Returns boolean
on
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 eventNameand listener will result in the listener being added, and called, multiple
+times.
+server.on('connection', (stream) => {
console.log('someone connected!');
});
+EventEmitter, so that calls can be chained.emitter.prependListener() method can be used as an alternative to add the
+event listener to the beginning of the listeners array.
+const myEE = new EventEmitter();
myEE.on('foo', () => console.log('a'));
myEE.prependListener('foo', () => console.log('b'));
myEE.emit('foo');
// Prints:
// b
// a
+Parameters
Returns void
Returns this
Since
Parameters
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
Parameters
Parameters
Rest ...args: any[]Returns void
Returns this
once
listener function for the event named eventName. The
+next time eventName is triggered, this listener is removed and then invoked.
+server.once('connection', (stream) => {
console.log('Ah, we have our first user!');
});
+EventEmitter, so that calls can be chained.emitter.prependOnceListener() method can be used as an alternative to add the
+event listener to the beginning of the listeners array.
+const myEE = new EventEmitter();
myEE.once('foo', () => console.log('a'));
myEE.prependOnceListener('foo', () => console.log('b'));
myEE.emit('foo');
// Prints:
// b
// a
+Parameters
Returns void
Returns this
Since
Parameters
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
Parameters
Parameters
Rest ...args: any[]Returns void
Returns this
prepend
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 eventNameand listener will result in the listener being added, and called, multiple
+times.
+server.prependListener('connection', (stream) => {
console.log('someone connected!');
});
+EventEmitter, so that calls can be chained.Parameters
Returns void
Returns this
Since
Parameters
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
Parameters
Parameters
Rest ...args: any[]Returns void
Returns this
prepend
listener function for the event named eventName to the beginning of the listeners array. The next time eventName is triggered, this
+listener is removed, and then invoked.
+server.prependOnceListener('connection', (stream) => {
console.log('Ah, we have our first user!');
});
+EventEmitter, so that calls can be chained.Parameters
Returns void
Returns this
Since
Parameters
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
Parameters
Parameters
Rest ...args: any[]Returns void
Returns this
remove
listener from the listener array for the event namedeventName.
+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.removeListener() or removeAllListeners() calls after emitting and before the last listener finishes execution
+will not remove them fromemit() in progress. Subsequent events behave as expected.
+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
+emitter.listeners() method will need to be recreated.removeListener() will remove the most
+recently added instance. In the example the once('ping')listener is removed:
+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');
+EventEmitter, so that calls can be chained.Parameters
Returns void
Returns this
Since
Parameters
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Returns void
Returns this
Parameters
Parameters
Returns void
Returns this
Parameters
Parameters
Rest ...args: any[]Returns void
Returns this
_transform
Parameters
Returns void
_flush
Parameters
Returns void
Class internal
EventEmitter class is defined and exposed by the events module:
+const EventEmitter = require('events');
+EventEmitters emit the event 'newListener' when new listeners are
+added and 'removeListener' when existing listeners are removed.Since
Hierarchy (view full)
Index
Constructors
Properties
Methods
Constructors
constructor
Parameters
Optional options: EventEmitterOptionsReturns internal
Properties
Static Readonly error'error'
+events. Listeners installed using this symbol are called before the regular
+'error' listeners are called.'error' event is emitted, therefore the process will still crash if no
+regular 'error' listener is installed.Static Readonly captureStatic captureStatic defaultMethods
Optional [captureStatic oncePromise 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.'error' event
+semantics and does not listen to the 'error' event.
+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();
+'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:
+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
+AbortSignal can be used to cancel waiting for the event:
+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!
+Parameters
Optional options: StaticEventEmitterOptionsReturns Promise<any[]>
Since
Parameters
Optional options: StaticEventEmitterOptionsReturns Promise<any[]>
Static on
+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
})();
+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.AbortSignal can be used to cancel waiting on events:
+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());
+Parameters
Optional options: StaticEventEmitterOptionsReturns AsyncIterableIterator<any>
eventName events emitted by the emitterSince
Static listenereventNameregistered on the given emitter.
+const { EventEmitter, listenerCount } = require('events');
const myEmitter = new EventEmitter();
myEmitter.on('event', () => {});
myEmitter.on('event', () => {});
console.log(listenerCount(myEmitter, 'event'));
// Prints: 2
+Parameters
Returns number
Since
Deprecated
listenerCount instead.Static geteventName.EventEmitters this behaves exactly the same as calling .listeners on
+the emitter.EventTargets this is the only way to get the event listeners for the
+event target. This is useful for debugging and diagnostic purposes.
+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]
}
+Parameters
Returns Function[]
Since
Static getEventEmitters this behaves exactly the same as calling .getMaxListeners on
+the emitter.EventTargets this is the only way to get the max event listeners for the
+event target. If the number of event handlers on a single EventTarget exceeds
+the max set, the EventTarget will print a warning.
+import { getMaxListeners, setMaxListeners, EventEmitter } from 'node:events';
{
const ee = new EventEmitter();
console.log(getMaxListeners(ee)); // 10
setMaxListeners(11, ee);
console.log(getMaxListeners(ee)); // 11
}
{
const et = new EventTarget();
console.log(getMaxListeners(et)); // 10
setMaxListeners(11, et);
console.log(getMaxListeners(et)); // 11
}
+Parameters
Returns number
Since
Static set
+const {
setMaxListeners,
EventEmitter
} = require('events');
const target = new EventTarget();
const emitter = new EventEmitter();
setMaxListeners(5, target, emitter);
+Parameters
Optional n: numberEventTarget event.Rest ...eventTargets: (EventEmitter<DefaultEventMap> | _DOMEventTarget)[]Returns void
Since
Static addExperimental abort event on the provided signal.abort event on abort signals is unsafe and may
+lead to resource leaks since another third party with the signal can
+call e.stopImmediatePropagation(). Unfortunately Node.js cannot change
+this since it would violate the web standard. Additionally, the original
+API makes it easy to forget to remove listeners.AbortSignals in Node.js APIs by solving these
+two issues by listening to the event such that stopImmediatePropagation does
+not prevent the listener from running.
+import { addAbortListener } from 'node:events';
function example(signal) {
let disposable;
try {
signal.addEventListener('abort', (e) => e.stopImmediatePropagation());
disposable = addAbortListener(signal, (e) => {
// Do something when signal is aborted.
});
} finally {
disposable?.[Symbol.dispose]();
}
}
+Parameters
Parameters
Returns void
Returns Disposable
abort listener.Since
add
emitter.on(eventName, listener).Type Parameters
Parameters
Parameters
Rest ...args: any[]Returns void
Returns this
Since
on
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 eventNameand listener will result in the listener being added, and called, multiple
+times.
+server.on('connection', (stream) => {
console.log('someone connected!');
});
+EventEmitter, so that calls can be chained.emitter.prependListener() method can be used as an alternative to add the
+event listener to the beginning of the listeners array.
+const myEE = new EventEmitter();
myEE.on('foo', () => console.log('a'));
myEE.prependListener('foo', () => console.log('b'));
myEE.emit('foo');
// Prints:
// b
// a
+Type Parameters
Parameters
Parameters
Rest ...args: any[]Returns void
Returns this
Since
once
listener function for the event named eventName. The
+next time eventName is triggered, this listener is removed and then invoked.
+server.once('connection', (stream) => {
console.log('Ah, we have our first user!');
});
+EventEmitter, so that calls can be chained.emitter.prependOnceListener() method can be used as an alternative to add the
+event listener to the beginning of the listeners array.
+const myEE = new EventEmitter();
myEE.once('foo', () => console.log('a'));
myEE.prependOnceListener('foo', () => console.log('b'));
myEE.emit('foo');
// Prints:
// b
// a
+Type Parameters
Parameters
Parameters
Rest ...args: any[]Returns void
Returns this
Since
remove
listener from the listener array for the event namedeventName.
+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.removeListener() or removeAllListeners() calls after emitting and before the last listener finishes execution
+will not remove them fromemit() in progress. Subsequent events behave as expected.
+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
+emitter.listeners() method will need to be recreated.removeListener() will remove the most
+recently added instance. In the example the once('ping')listener is removed:
+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');
+EventEmitter, so that calls can be chained.Type Parameters
Parameters
Parameters
Rest ...args: any[]Returns void
Returns this
Since
off
emitter.removeListener().Type Parameters
Parameters
Parameters
Rest ...args: any[]Returns void
Returns this
Since
remove
eventName.EventEmitter instance was created by some other
+component or module (e.g. sockets or file streams).EventEmitter, so that calls can be chained.Parameters
Optional event: string | symbolReturns this
Since
set
EventEmitters will print a warning if more than 10 listeners are
+added for a particular event. This is a useful default that helps finding
+memory leaks. The emitter.setMaxListeners() method allows the limit to be
+modified for this specific EventEmitter instance. The value can be set toInfinity (or 0) to indicate an unlimited number of listeners.EventEmitter, so that calls can be chained.Parameters
Returns this
Since
get
EventEmitter which is either
+set by emitter.setMaxListeners(n) or defaults to defaultMaxListeners.Returns number
Since
listeners
eventName.
+server.on('connection', (stream) => {
console.log('someone connected!');
});
console.log(util.inspect(server.listeners('connection')));
// Prints: [ [Function] ]
+Type Parameters
Parameters
Returns Function[]
Since
raw
eventName,
+including any wrappers (such as those created by .once()).
+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');
+Type Parameters
Parameters
Returns Function[]
Since
emit
eventName, in the order they were registered, passing the supplied arguments
+to each.true if the event had listeners, false otherwise.
+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
+Type Parameters
Parameters
Rest ...args: AnyRestReturns boolean
Since
listener
eventName.listener is provided, it will return how many times the listener
+is found in the list of the listeners of the event.Type Parameters
Parameters
Optional listener: FunctionReturns number
Since
prepend
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 eventNameand listener will result in the listener being added, and called, multiple
+times.
+server.prependListener('connection', (stream) => {
console.log('someone connected!');
});
+EventEmitter, so that calls can be chained.Type Parameters
Parameters
Parameters
Rest ...args: any[]Returns void
Returns this
Since
prepend
listener function for the event named eventName to the beginning of the listeners array. The next time eventName is triggered, this
+listener is removed, and then invoked.
+server.prependOnceListener('connection', (stream) => {
console.log('Ah, we have our first user!');
});
+EventEmitter, so that calls can be chained.Type Parameters
Parameters
Parameters
Rest ...args: any[]Returns void
Returns this
Since
event
Symbols.
+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) ]
+Returns (string | symbol)[]
Since
pipe
Type Parameters
Parameters
Optional options: {
end?: boolean;
}Optional end?: booleanReturns T
compose
Type Parameters
Parameters
Optional options: {
signal: AbortSignal;
}signal: AbortSignal
Returns T
'removeListener' when existing listeners are removed.
It supports the following option:
v0.1.26
-Generated using TypeDoc
Generated using TypeDoc
Generated using TypeDoc
Generated using TypeDoc
Generated using TypeDoc
Optional options: FinishedOptionsGenerated using TypeDoc
Optional options: PipelineOptionsOptional options: PipelineOptionsOptional options: PipelineOptionsOptional options: PipelineOptionsRest ...streams: (WritableStream | ReadWriteStream | PipelineOptions)[]Generated using TypeDoc
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 passedAbortSignal will behave the same way as calling .destroy(new AbortError())on the stream.
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:
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;
}
}
})();
+
+A signal representing possible cancellation
+a stream to attach a signal to
+v15.4.0
+Generated using TypeDoc
Optional options: FinishedOptionsGenerated using TypeDoc
A function to get notified when a stream is no longer readable, writable +or has experienced an error or a premature close event.
+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:
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:
const cleanup = finished(rs, (err) => {
cleanup();
// ...
});
+
+A readable and/or writable stream.
+A callback function that takes an optional error argument.
+Optional err: ErrnoExceptionA cleanup function which removes all registered listeners.
+v10.0.0
+Optional err: ErrnoExceptionGenerated using TypeDoc
Generated using TypeDoc
Returns whether the stream has encountered an error.
+v17.3.0
+Generated using TypeDoc
Returns whether the stream is readable.
+v17.4.0
+Generated using TypeDoc
Optional options: PipelineOptionsOptional options: PipelineOptionsOptional options: PipelineOptionsOptional options: PipelineOptionsRest ...streams: (WritableStream | ReadWriteStream | PipelineOptions)[]Generated using TypeDoc
A module method to pipe between streams and generators forwarding errors and +properly cleaning up and provide a callback when the pipeline is complete.
+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 asignal AbortSignal property. When the signal is aborted,destroy will be called on the underlying pipeline, with
+anAbortError.
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:
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:
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.
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. If the last
+stream is readable, dangling event listeners will be removed so that the last
+stream can be consumed later.
stream.pipeline() closes all the streams when an error is raised.
+The IncomingRequest usage with pipeline could lead to an unexpected behavior
+once it would destroy the socket without sending the expected response.
+See the example below:
const fs = require('fs');
const http = require('http');
const { pipeline } = require('stream');
const server = http.createServer((req, res) => {
const fileStream = fs.createReadStream('./fileNotExist.txt');
pipeline(fileStream, res, (err) => {
if (err) {
console.log(err); // No such file
// this message can't be sent once `pipeline` already destroyed the socket
return res.end('error!!!');
}
});
});
+
+Optional callback: PipelineCallback<B>Called when the pipeline is fully done.
+v10.0.0
+Optional callback: PipelineCallback<B>Optional callback: ((err) => void)Rest ...streams: (WritableStream | ReadWriteStream | ((err) => void))[]Generated using TypeDoc
Generated using TypeDoc
Creates a LogLevelStreamEntry stream that writes to a static file at or above the minimum level
Generated using TypeDoc
Generated using TypeDoc
A
+Blobencapsulates immutable, raw data that can be safely shared across +multiple worker threads.Since
v15.7.0, v14.18.0
+