Readonly
closedIs 在发出true
after 'close'
has been emitted.'close'
之后为true
。
v18.0.0
Is 在调用true
after readable.destroy()
has been called.readable.destroy()
后为true
。
v8.0.0
Readonly
erroredReturns error if the stream has been destroyed with an error.如果流已被错误破坏,则返回错误。
v18.0.0
Is 如果调用true
if it is safe to call readable.read()
, which means the stream has not been destroyed or emitted 'error'
or 'end'
.readable.read()
是安全的,则为true
,这意味着流没有被破坏或发出'error'
或'end'
。
v11.4.0
Readonly
Experimental
readableReturns whether the stream was destroyed or errored before emitting 返回流在发出'end'
.'end'
之前是被破坏还是出错。
v16.8.0
Readonly
Experimental
readableReturns whether 返回是否已发出'data'
has been emitted.'data'
。
v16.7.0, v14.18.0
Readonly
readableGetter for the property 给定encoding
of a given Readable
stream. Readable
流的属性encoding
的Getter。The encoding
property can be set using the readable.setEncoding()
method.encoding
属性可以使用readable.setEncoding()
方法设置。
v12.7.0
Readonly
readableBecomes 在发出true
when 'end'
event is emitted.'end'
事件时变为true
。
v12.9.0
Readonly
readableThis property reflects the current state of a 此属性反映Readable
stream as described in the Three states
section.Readable
取流的当前状态,如Three states
部分所述。
v9.4.0
Readonly
readableReturns the value of 返回创建此highWaterMark
passed when creating this Readable
.Readable
时传递的highWaterMark
的值。
v9.3.0
Readonly
readableThis property contains the number of bytes (or objects) in the queue ready to be read. The value provides introspection data regarding the status of the 此属性包含队列中准备读取的字节数(或对象数)。该值提供有关highWaterMark
.highWaterMark
状态的内省数据。
v9.4.0
Readonly
readableGetter for the property 给定objectMode
of a given Readable
stream.Readable
流的属性objectMode
的Getter。
v12.3.0
Static
Readonly
FILEFires when the stream loaded the file document corresponding to the provided id.当流加载与所提供的id相对应的文件文档时激发。
Static
Readonly
captureStatic
captureSets or gets the default captureRejection value for all emitters.设置或获取所有发射器的默认captureRejection值。
Static
defaultStatic
Readonly
errorThis symbol shall be used to install a listener for only monitoring 此符号应用于安装仅用于监视'error'
events. 'error'
事件的侦听器。Listeners installed using this symbol are called before the regular 在调用常规'error'
listeners are called.'error'
侦听器之前,将调用使用此符号安装的侦听器。
Installing a listener using this symbol does not change the behavior once an 一旦发出'error'
event is emitted, therefore the process will still crash if no regular 'error'
listener is installed.'error'
事件,使用此符号安装侦听器不会改变行为,因此,如果未安装常规的'error'
侦听器,进程仍将崩溃。
Optional
_constructMarks this stream as aborted (will never push another 将此流标记为中止(永远不会推送另一个data
event) and kills the underlying cursor. Will emit the 'end' event, and then the 'close' event once the cursor is successfully killed.data
事件),并杀死底层游标。一旦成功杀死游标,将发出'end'
事件,然后发出'close'
事件。
Event emitter The defined events on documents including:事件发射器文档上定义的事件,包括:
Rest
...args: any[]Destroy the stream. Optionally emit an 破坏流。(可选)发出'error'
event, and emit a 'close'
event (unless emitClose
is set to false
). 'error'
事件,并发出'close'
事件(除非emitClose设置为false
)。After this call, the readable stream will release any internal resources and subsequent calls to 在这个调用之后,可读流将释放任何内部资源,随后对push()
will be ignored.push()
的调用将被忽略。
Once 一旦destroy()
has been called any further calls will be a no-op and no further errors except from _destroy()
may be emitted as 'error'
.destroy()
被调用,任何进一步的调用都将是无操作的,除_destroy()
之外的任何其他错误都可能作为'error'
发出。
Implementors should not override this method, but instead implement 实现程序不应重写此方法,而应实现readable._destroy()
.readable._destroy()
。
Optional
error: ErrorError which will be passed as payload in 将在'error'
event'error'
事件中作为有效负载传递的错误
v8.0.0
Rest
...args: any[]Sets the 0-based offset in bytes to start streaming from. 设置以字节为单位的从0开始的偏移量。Throws an error if this stream has entered flowing mode (e.g. if you've already called 如果此流已进入流动模式(例如,如果您已调用on('data')
)on('data')
),则抛出错误
Offset in bytes to stop reading at停止读取的偏移量(以字节为单位)
Returns an array listing the events for which the emitter has registered listeners. 返回一个数组,列出发射器已注册侦听器的事件。The values in the array are strings or 数组中的值是字符串或Symbol
s.Symbol
。
import { EventEmitter } from 'node:events';
const myEE = new EventEmitter();
myEE.on('foo', () => {});
myEE.on('bar', () => {});
const sym = Symbol('symbol');
myEE.on(sym, () => {});
console.log(myEE.eventNames());
// Prints: [ 'foo', 'bar', Symbol(symbol) ]
v6.0.0
Returns the current max listener value for the 返回EventEmitter
which is either set by emitter.setMaxListeners(n)
or defaults to defaultMaxListeners.EventEmitter
的当前最大侦听器值,该值由emitter.setMaxListeners(n)
设置或默认为defaultMaxListeners。
v1.0.0
The readable.isPaused()
method returns the current operating state of theReadable
. readable.isPaused()
方法返回Readable
的当前操作状态。This is used primarily by the mechanism that underlies the这主要由readable.pipe()
method. readable.pipe()
方法的基础机制使用。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
v0.11.14
Returns the number of listeners listening for the event named 返回侦听名为eventName
.eventName
的事件的侦听器数。
If 如果提供了listener
is provided, it will return how many times the listener is found in the list of the listeners of the event.listener
,它将返回在事件的监听器列表中找到监听器的次数。
The name of the event being listened for正在侦听的事件的名称
Optional
listener: FunctionThe event handler function事件处理程序函数
v3.2.0
Returns a copy of the array of listeners for the event named 返回名为eventName
.eventName
的事件的侦听器数组的副本。
server.on('connection', (stream) => {
console.log('someone connected!');
});
console.log(util.inspect(server.listeners('connection')));
// Prints: [ [Function] ]
v0.1.26
Alias for emitter.removeListener()
.emitter.removeListener()
的别名。
Rest
...args: any[]v10.0.0
Rest
...args: any[]Rest
...args: any[]The readable.pause()
method will cause a stream in flowing mode to stop emitting 'data'
events, switching out of flowing mode. readable.pause()
方法将导致处于流动模式的流停止发出'data'
事件,从而切换出流动模式。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);
});
The 如果存在readable.pause()
method has no effect if there is a 'readable'
event listener.'readable'
事件侦听器,则readable.pause()
方法无效。
v0.9.4
Rest
...args: any[]Rest
...args: any[]Returns a copy of the array of listeners for the event named 返回名为eventName
, including any wrappers (such as those created by .once()
).eventName
的事件的侦听器数组的副本,包括任何包装器(如.once()
创建的包装器)。
import { EventEmitter } from 'node:events';
const emitter = new EventEmitter();
emitter.once('log', () => console.log('log once'));
// Returns a new Array with a function `onceWrapper` which has a property `listener` which contains the original listener bound above返回一个具有函数“onceWrapper”的新数组,该函数具有包含上面绑定的原始侦听器的属性“listener”
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将返回一个带有单个函数的新数组,该函数由上面的“on()”绑定
const newListeners = emitter.rawListeners('log');
// Logs "log persistently" twice记录两次“持久日志”
newListeners[0]();
emitter.emit('log');
v9.4.0
The readable.read()
method reads data out of the internal buffer and returns it. readable.read()
方法从内部缓冲区中读取数据并返回。If no data is available to be read, 如果没有可供读取的数据,则返回null
is returned. null
。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.readable.setEncoding()
方法指定了编码,或者流在对象模式下运行,否则数据将作为Buffer对象返回。
The optional 可选的size
argument specifies a specific number of bytes to read. size
参数指定要读取的特定字节数。If 如果size
bytes are not available to be read, null
will be returned _unless_the stream has ended, in which case all of the data remaining in the internal buffer will be returned.size
字节无法读取,则返回null
除非流已结束,在这种情况下,将返回内部缓冲区中剩余的所有数据。
If the 如果未指定size
argument is not specified, all of the data contained in the internal buffer will be returned.size
参数,则将返回内部缓冲区中包含的所有数据。
The size
argument must be less than or equal to 1 GiB.size
参数必须小于或等于1 GiB。
The readable.read()
method should only be called on Readable
streams operating in paused mode. In flowing mode, readable.read()
is called automatically until the internal buffer is fully drained.readable.read()
方法只应在以暂停模式运行的Readable
流上调用。在流动模式下,会自动调用readable.read()
,直到内部缓冲区完全耗尽。
const readable = getReadableStreamSomehow();
// 'readable' may be triggered multiple times as data is buffered in当数据缓冲在
readable.on('readable', () => {
let chunk;
console.log('Stream is readable (new data received in buffer)');
// Use a loop to make sure we read all currently available data使用循环确保读取所有当前可用的数据
while (null !== (chunk = readable.read())) {
console.log(`Read ${chunk.length} bytes of data...`);
}
});
// 'end' will be triggered once when there is no more data available当没有更多可用数据时,将触发一次“结束”
readable.on('end', () => {
console.log('Reached end of stream.');
});
Each call to 对readable.read()
returns a chunk of data, or null
. readable.read()
的每次调用都会返回一块数据,或者为null
。The chunks are not concatenated. 块没有连接。A while
loop is necessary to consume all data currently in the buffer. while
循环是消耗缓冲区中当前所有数据所必需的。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. .read()
可能会返回null
,因为到目前为止已经消耗了所有缓冲的内容,但还有更多的数据尚未缓冲。In this case a new 在这种情况下,当缓冲区中有更多数据时,将发出一个新的'readable'
event will be emitted when there is more data in the buffer. 'readable'
事件。Finally the 最后,当没有更多数据时,将发出'end'
event will be emitted when there is no more data to come.'end'
事件。
Therefore to read a file's whole contents from a 因此,要从readable
, it is necessary to collect chunks across multiple 'readable'
events:readable
文件中读取文件的全部内容,有必要跨多个'readable'
事件集合块:
const chunks = [];
readable.on('readable', () => {
let chunk;
while (null !== (chunk = readable.read())) {
chunks.push(chunk);
}
});
readable.on('end', () => {
const content = chunks.join('');
});
A 对象模式下的Readable
stream in object mode will always return a single item from a call to readable.read(size)
, regardless of the value of thesize
argument.Readable
流将始终从对readable.read(size)
的调用中返回单个项,而与size
参数的值无关。
If the 如果readable.read()
method returns a chunk of data, a 'data'
event will also be emitted.readable.read()
方法返回一个数据块,则还会发出一个'data'
事件。
Calling read after the 在发出'end'
event has been emitted will return null
. 'end'
事件后调用read将返回null
。No runtime error will be raised.不会引发运行时错误。
Optional
size: numberOptional argument to specify how much data to read.可选参数,用于指定要读取的数据量。
v0.9.4
Removes all listeners, or those of the specified 删除所有侦听器,或指定eventName
.eventName
的侦听器。
It is bad practice to remove listeners added elsewhere in the code, particularly when the 删除代码中其他地方添加的侦听器是一种糟糕的做法,尤其是当EventEmitter
instance was created by some other component or module (e.g. sockets or file streams).EventEmitter
实例是由其他组件或模块(例如套接字或文件流)创建时。
Returns a reference to the 返回对EventEmitter
, so that calls can be chained.EventEmitter
的引用,以便可以链接调用。
Optional
event: string | symbolv0.1.26
Rest
...args: any[]The readable.resume()
method causes an explicitly paused Readable
stream to resume emitting 'data'
events, switching the stream into flowing mode.readable.resume()
方法使显式暂停的Readable
流恢复发出'data'
事件,将流切换到流动模式。
The readable.resume()
method can be used to fully consume the data from a stream without actually processing any of that data:readable.resume()
方法可以用于完全消耗流中的数据,而无需实际处理任何数据:
getReadableStreamSomehow()
.resume()
.on('end', () => {
console.log('Reached the end, but did not read anything.');
});
The 如果存在readable.resume()
method has no effect if there is a 'readable'
event listener.'readable'
事件侦听器,则readable.resume()
方法无效。
v0.9.4
The readable.setEncoding()
method sets the character encoding for data read from the Readable
stream.readable.setEncoding()
方法为从Readable
流中读取的数据设置字符编码。
By default, no encoding is assigned and stream data will be returned as默认情况下,不分配任何编码,流数据将作为Buffer
objects. Buffer
对象返回。Setting an encoding causes the stream data to be returned as strings of the specified encoding rather than as 设置编码会导致流数据作为指定编码的字符串而不是作为Buffer
objects. Buffer
对象返回。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.setEncoding('utf8')
将导致输出数据被解释为UTF-8数据,并作为字符串传递。调用readable.setEncoding('hex')
将导致数据以十六进制字符串格式进行编码。
The Readable
stream will properly handle multi-byte characters delivered through the stream that would otherwise become improperly decoded if simply pulled from the stream as Buffer
objects.Readable
流将正确处理通过流传递的多字节字符,如果只是作为Buffer
对象从流中提取,这些字符将被错误解码。
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);
});
The encoding to use.要使用的编码。
v0.9.4
By default 默认情况下,如果为特定事件添加了超过EventEmitter
s will print a warning if more than 10
listeners are added for a particular event. 10
个侦听器,EventEmitter
将打印警告。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. emitter.setMaxListeners()
方法允许修改此特定EventEmitter
实例的限制。The value can be set to该值可以设置为Infinity
(or 0
) to indicate an unlimited number of listeners.Infinity
(或0
),以表示侦听器的数量不受限制。
Returns a reference to the 返回对EventEmitter
, so that calls can be chained.EventEmitter
的引用,以便可以链接调用。
v0.3.5
Sets the 0-based offset in bytes to start streaming from. 设置以字节为单位的从0开始的偏移量。Throws an error if this stream has entered flowing mode (e.g. if you've already called 如果此流已进入流动模式(例如,如果您已调用on('data')
)on('data')
),则抛出错误
0-based offset in bytes to start streaming from从0开始流传输的偏移量(以字节为单位)
The readable.unpipe()
method detaches a Writable
stream previously attached using the pipe method.readable.unpipe()
方法分离以前使用pipe
方法附加的Writable
。
If the 如果未指定destination
is not specified, then all pipes are detached.destination
,则会分离所有管道。
If the 如果指定了destination
is specified, but no pipe is set up for it, then the method does nothing.destination
,但没有为其设置管道,则该方法不执行任何操作。
const fs = require('node: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中的所有数据都会进入“filetxt”,但仅限于前一秒。
readable.pipe(writable);
setTimeout(() => {
console.log('Stop writing to file.txt.');
readable.unpipe(writable);
console.log('Manually close the file stream.');
writable.end();
}, 1000);
Optional
destination: WritableStreamOptional specific stream to unpipe要取消管道的可选特定流
v0.9.4
Passing 将chunk
as null
signals the end of the stream (EOF) and behaves the same as readable.push(null)
, after which no more data can be written. chunk
作为null
传递表示流(EOF)的结束,其行为与readable.push(null)
相同,之后不能再写入数据。The EOF signal is put at the end of the buffer and any buffered data will still be flushed.EOF信号被放在缓冲器的末尾,并且任何缓冲的数据仍将被刷新。
The readable.unshift()
method pushes a chunk of data back into the internal buffer. readable.unshift()
方法将一块数据推回内部缓冲区。This is useful in certain situations where a stream is being consumed by code that needs to "un-consume" some amount of data that it has optimistically pulled out of the source, so that the data can be passed on to some other party.这在某些情况下很有用,因为代码正在消耗流,需要“取消消耗”它乐观地从源中提取的一定数量的数据,以便将数据传递给其他方。
The 在发出stream.unshift(chunk)
method cannot be called after the 'end'
event has been emitted or a runtime error will be thrown.'end'
事件后,无法调用stream.unshift(chunk)
方法,或者将引发运行时错误。
Developers using 使用stream.unshift()
often should consider switching to use of a Transform
stream instead. stream.unshift()
的开发人员通常应该考虑改用Transform
流。See the 有关更多信息,请参阅API中的流实现器部分。API for stream implementers
section for more information.
// Pull off a header delimited by \n\n.提取由\n\n分隔的标头。
// Use unshift() if we get too much.如果我们得到太多,请使用unshift()。
// Call the callback with (error, header, stream).使用(error, header, stream)调用回调。
const { StringDecoder } = require('node: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.在取消提升之前删除“readable”侦听器。
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;
}
}
}
Unlike push, 与push不同,stream.unshift(chunk)
will not end the reading process by resetting the internal reading state of the stream.stream.unshift(chunk)
不会通过重置流的内部读取状态来结束读取过程。
This can cause unexpected results if 如果在读取期间(即从自定义流的_read实现中)调用readable.unshift()
is called during a read (i.e. from within a _read implementation on a custom stream). readable.unshift()
,这可能会导致意外结果。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.readable.unshift()
后立即push将适当地重置读取状态,但最好在执行读取过程中避免调用readable.unshift()
。
Chunk of data to unshift onto the read queue. For streams not operating in object mode, 要取消提升到读取队列的数据块。对于不在对象模式下操作的流,chunk
must be a string, Buffer
, Uint8Array
, or null
. chunk
必须是字符串、Buffer
、Uint8Array
或null
。For object mode streams, 对于对象模式流,chunk
may be any JavaScript value.chunk
可以是任何JavaScript值。
Optional
encoding: BufferEncodingEncoding of string chunks. 字符串块的编码。Must be a valid 必须是有效的Buffer
encoding, such as 'utf8'
or 'ascii'
.Buffer
编码,如'utf8'
或'ascii'
。
v0.9.11
Prior to Node.js 0.10, streams did not implement the entire 在Node.js 0.10之前,流没有实现当前定义的整个node:stream
module API as it is currently defined. node:stream
模块API。(See (有关详细信息,请参阅Compatibility
for more information.)Compatibility
。)
When using an older Node.js library that emits 当使用旧的Node.js库时,该库会发出'data'
events and has a pause method that is advisory only, the readable.wrap()
method can be used to create a Readable
stream that uses the old stream as its data source.'data'
事件,并且有一个仅为咨询的pause方法,readable.wrap()
方法可用于创建一个使用旧流作为数据源的Readable
流。
It will rarely be necessary to use 很少需要使用readable.wrap()
but the method has been provided as a convenience for interacting with older Node.js applications and libraries.readable.wrap()
,但提供该方法是为了方便与旧的Node.js应用程序和库交互。
const { OldReader } = require('./old-api-module.js');
const { Readable } = require('node:stream');
const oreader = new OldReader();
const myReader = new Readable().wrap(oreader);
myReader.on('readable', () => {
myReader.read(); // etc.
});
An "old style" readable stream“旧式”可读流
v0.9.4
Static
fromStatic
fromExperimental
A utility method for creating a 一种从web Readable
from a web ReadableStream
.ReadableStream
创建Readable
的实用方法。
Optional
options: Pick<ReadableOptions, "objectMode" | "highWaterMark" | "signal" | "encoding">v17.0.0
Static
getReturns a copy of the array of listeners for the event named 返回名为eventName
.eventName
的事件的侦听器数组的副本。
For 对于EventEmitter
s this behaves exactly the same as calling .listeners
on the emitter.EventEmitter
,其行为与在发射器上调用.listeners
完全相同。
For 对于EventTarget
s this is the only way to get the event listeners for the event target. EventTarget
,这是获取事件目标的事件侦听器的唯一方法。This is useful for debugging and diagnostic purposes.这对于调试和诊断非常有用。
import { getEventListeners, EventEmitter } from 'node:events';
{
const ee = new EventEmitter();
const listener = () => console.log('Events are fun');
ee.on('foo', listener);
console.log(getEventListeners(ee, 'foo')); // [ [Function: listener] ]
}
{
const et = new EventTarget();
const listener = () => console.log('Events are fun');
et.addEventListener('foo', listener);
console.log(getEventListeners(et, 'foo')); // [ [Function: listener] ]
}
v15.2.0, v14.17.0
Static
isStatic
listenerA class method that returns the number of listeners for the given 一个类方法,用于返回在给定eventName
registered on the given emitter
.emitter
上注册的给定eventName
的侦听器数。
import { EventEmitter, listenerCount } from 'node:events';
const myEmitter = new EventEmitter();
myEmitter.on('event', () => {});
myEmitter.on('event', () => {});
console.log(listenerCount(myEmitter, 'event'));
// Prints: 2
The emitter to query要查询的发射器
The event name事件名称
v0.9.12
Since v3.2.0 - Use listenerCount
instead.
Static
onimport { on, EventEmitter } from 'node:events';
import process from 'node:process';
const ee = new EventEmitter();
// Emit later on稍后发射
process.nextTick(() => {
ee.emit('foo', 'bar');
ee.emit('foo', 42);
});
for await (const event of on(ee, 'foo')) {
// The execution of this inner block is synchronous and it processes one event at a time (even with await). 这个内部块的执行是同步的,它一次处理一个事件(即使有等待)。
// Do not use if concurrent execution is required.如果需要并发执行,请不要使用。
console.log(event); // prints ['bar'] [42]
}
// Unreachable here此处无法访问
Returns an 返回一个迭代eventName事件的AsyncIterator
that iterates eventName
events. AsyncIterator
。It will throw if the 如果EventEmitter
emits 'error'
. EventEmitter
发出'error'
,它将抛出。It removes all listeners when exiting the loop. 它在退出循环时删除所有侦听器。The 每次迭代返回的value
returned by each iteration is an array composed of the emitted event arguments.value
是一个由发出的事件参数组成的数组。
An AbortSignal
can be used to cancel waiting on events:AbortSignal
可用于取消等待事件:
import { on, EventEmitter } from 'node:events';
import process from 'node:process';
const ac = new AbortController();
(async () => {
const ee = new EventEmitter();
// Emit later on稍后发射
process.nextTick(() => {
ee.emit('foo', 'bar');
ee.emit('foo', 42);
});
for await (const event of on(ee, 'foo', { signal: ac.signal })) {
// The execution of this inner block is synchronous and it processes one event at a time (even with await). 这个内部块的执行是同步的,它一次处理一个事件(即使有等待)。
// Do not use if concurrent execution is required.如果需要并发执行,请不要使用。
console.log(event); // prints ['bar'] [42]
}
// Unreachable here此处无法访问
})();
process.nextTick(() => ac.abort());
The name of the event being listened for正在侦听的事件的名称
Optional
options: StaticEventEmitterOptionsthat iterates 迭代eventName
events emitted by the emitter
emitter
发出的eventName
事件
v13.6.0, v12.16.0
Static
onceCreates a 创建一个Promise
that is fulfilled when the EventEmitter
emits the given event or that is rejected if the EventEmitter
emits 'error'
while waiting.Promise
,该Promise
在EventEmitter
发出给定事件时实现,或者如果EventEmitter
在等待时发出'error'
则被拒绝。
The Promise
will resolve with an array of all the arguments emitted to the given event.Promise
将通过向给定事件发出的所有参数的数组进行解析。
This method is intentionally generic and works with the web platform EventTarget interface, which has no special此方法是有意通用的,可与web平台EventTarget接口配合使用,该接口没有特殊的'error'
event semantics and does not listen to the 'error'
event.'error'
事件语义,也不侦听'error'
消息。
import { once, EventEmitter } from 'node:events';
import process from 'node:process';
const ee = new EventEmitter();
process.nextTick(() => {
ee.emit('myevent', 42);
});
const [value] = await once(ee, 'myevent');
console.log(value);
const err = new Error('kaboom');
process.nextTick(() => {
ee.emit('error', err);
});
try {
await once(ee, 'myevent');
} catch (err) {
console.error('error happened', err);
}
The special handling of the 'error'
event is only used when events.once()
is used to wait for another event. 'error'
事件的特殊处理仅在events.once()
用于等待另一个事件时使用。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:events.once()
用于等待error'
事件本身,那么它将被视为任何其他类型的事件,而无需特殊处理:
import { EventEmitter, once } from 'node:events';
const ee = new EventEmitter();
once(ee, 'error')
.then(([err]) => console.log('ok', err.message))
.catch((err) => console.error('error', err.message));
ee.emit('error', new Error('boom'));
// Prints: ok boom
An AbortSignal
can be used to cancel waiting for the event:AbortSignal
可用于取消等待事件:
import { EventEmitter, once } from 'node:events';
const ee = new EventEmitter();
const ac = new AbortController();
async function foo(emitter, event, signal) {
try {
await once(emitter, event, { signal });
console.log('event emitted!');
} catch (error) {
if (error.name === 'AbortError') {
console.error('Waiting for the event was canceled!');
} else {
console.error('There was an error', error.message);
}
}
}
foo(ee, 'foo', ac.signal);
ac.abort(); // Abort waiting for the event中止等待事件
ee.emit('foo'); // Prints: Waiting for the event was canceled!打印:等待活动已取消!
Optional
options: StaticEventEmitterOptionsv11.13.0, v10.16.0
Optional
options: StaticEventEmitterOptionsStatic
setimport { setMaxListeners, EventEmitter } from 'node:events';
const target = new EventTarget();
const emitter = new EventEmitter();
setMaxListeners(5, target, emitter);
Optional
n: numberA non-negative number. 一个非负数。The maximum number of listeners per 每个EventTarget
event.EventTarget
事件的最大侦听器数。
Rest
...eventTargets: (EventEmitter | _DOMEventTarget)[]v15.4.0
Static
toGenerated using TypeDoc
A readable stream that enables you to read buffers from GridFS.一个可读流,使您能够从GridFS中读取缓冲区。Do not instantiate this class directly. Use不要直接实例化这个类。请改用openDownloadStream()
instead.openDownloadStream()
。