Fired when the stream is exhausted and the underlying cursor is killed当流耗尽且基础游标被终止时激发
Emitted when a chunk of data is available to be consumed.当数据块可供使用时发出。
Fired when the stream is exhausted (no more data events).当流耗尽时激发(不再有数据事件)。
An error occurred发生错误
Fires when the stream loaded the file document corresponding to the provided id.当流加载与提供的id对应的文件文档时激发。
Is true after 发出'close'
has been emitted.'close'
后为true
。
Is 在调用true
after readable.destroy()
has been called.readable.destroy()
后为true
。
Returns error if the stream has been destroyed with an error.如果流因错误而被销毁,则返回错误。
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'
。
Returns whether the stream was destroyed or errored before emitting 返回流在发出'end'
.'end'
之前是被破坏还是出错。
Returns whether 返回是否已发出'data'
has been emitted.'data'
。
Getter for the property 给定encoding
of a given Readable
stream. Readable
流的属性encoding
的Getter。The 可以使用encoding
property can be set using the readable.setEncoding()
method.readable.setEncoding()
方法设置encoding
属性。
Becomes 当发出true
when 'end'
event is emitted.'end'
事件时变为true
。
This property reflects the current state of a 此属性反映了Readable
stream as described in the Three states
section.Three states
部分中描述的Readable
流的当前状态。
Returns the value of 返回创建此highWaterMark
passed when creating this Readable
.Readable
时传递的highWaterMark
值。
This property contains the number of bytes (or objects) in the queue ready to be read. 此属性包含队列中准备读取的字节数(或对象数)。The value provides introspection data regarding the status of the 该值提供有关highWaterMark
.highWaterMark
状态的内省数据。
Getter for the property 给定objectMode
of a given Readable
stream.Readable
流的属性objectMode
的Getter。
Sets or gets the default captureRejection value for all emitters.设置或获取所有发射器的默认captureRejection值。
This 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'
侦听器,进程仍将崩溃。
Marks 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.将发出“end”事件,然后在成功杀死游标后发出“close”事件。
called when the cursor is successfully closed or an error occurred.当游标成功关闭或发生错误时调用。
Event emitter The defined events on documents including:事件发射器文档上定义的事件包括:
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()
,任何进一步的调用都将是no-op,并且除了_destroy()
之外,其他错误都不会作为'error'
发出。
Implementors should not override this method, but instead implement 实现者不应重写此方法,而应实现readable._destroy()
.readable._destroy()
。
Error which will be passed as payload in 将在'error'
event'error'
事件中作为有效负载传递的错误
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
。
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 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。
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
Returns the number of listeners listening to the event named 返回侦听名为eventName
.eventName
的事件的侦听器数。
The name of the event being listened for正在侦听的事件的名称
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] ]
Alias for emitter.removeListener()
.emitter.removeListener()
的别名。
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()
方法将无效。
Returns a copy of the array of listeners for the event named 返回名为eventName
, including any wrappers (such as those created by .once()
).eventName
的事件的侦听器数组的副本,包括任何包装器(例如由.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');
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 unlessthe 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. readable.read()
方法只应在暂停模式下运行的Readable
流上调用。In flowing mode, 在流动模式下,会自动调用readable.read()
is called automatically until the internal buffer is fully drained.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 argument to specify how much data to read.可选参数,用于指定要读取的数据量。
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
的引用,以便可以链接调用。
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()
方法无效。
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. readable.setEncoding('utf8')
将导致输出数据被解释为UTF-8数据,并作为字符串传递。Calling调用readable.setEncoding('hex')
will cause the data to be encoded in hexadecimal string format.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.
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
的引用,以便可以链接调用。
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('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);
Optional specific stream to unpipe要取消管道的可选特定流
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. readableun.shift()
方法将一块数据推回到内部缓冲区。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.stream.unshift(chunk)
方法无法在发出'end'
事件后调用,否则将引发运行时错误。
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.
// 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;
}
}
}
Unlike push, 与stream.unshift(chunk)
will not end the reading process by resetting the internal reading state of the stream. push
不同,stream.unshift(chunk)
不会通过重置流的内部读取状态来结束读取过程。This can cause unexpected results if 如果在读取过程中调用code>readable.unshift()(即从自定义流的readable.unshift()
is called during a read (i.e. from within a {@link _read} implementation on a custom stream). read
实现中调用),这可能会导致意外结果。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()
的调用将适当地重置读取状态,但最好在执行读取过程中避免调用readable.unhift()
。
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值。
Encoding of string chunks. 字符串块的编码。Must be a valid 必须是有效的Buffer
encoding, such as 'utf8'
or 'ascii'
.Buffer
编码,如'utf8'
或'ascii'
。
Prior to Node.js 0.10, streams did not implement the entire 在Node.js 0.10之前,流没有实现当前定义的整个stream
module API as it is currently defined. (See Compatibility
for more information.)stream
模块API。(有关详细信息,请参阅“兼容性”。)
When using an older Node.js library that emits 当使用一个旧的Node.js库,该库发出'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.'data'
事件,并且有一个暂停方法(仅为建议)时,可以使用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('stream');
const oreader = new OldReader();
const myReader = new Readable().wrap(oreader);
myReader.on('readable', () => {
myReader.read(); // etc.
});
An "old style" readable stream
A utility method for creating Readable Streams out of iterators.用于从迭代器中创建可读流的实用程序方法。
A utility method for creating a 从web Readable
from a web ReadableStream
.ReadableStream
创建Readable
的实用程序方法。
Returns 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
,这与调用emitter
上的.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.这对于调试和诊断非常有用。
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]
}
Returns whether the stream has been read from or cancelled.返回流是否已被读取或取消。
A class method that returns the number of listeners for the given 返回在给定eventName
registered on the given emitter
.emitter
上注册的给定eventName
的侦听器数量的类方法。
const { EventEmitter, listenerCount } = require('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事件名称
const { on, EventEmitter } = require('events');
(async () => {
const ee = new EventEmitter();
// Emit later on
process.nextTick(() => {
ee.emit('foo', 'bar'); ee.emit('foo', 42); });
for await (const event of on(ee, 'foo')) {
// The execution of this inner block is synchronous and it processes one event at a time (even with await). 这个内部块的执行是同步的,它一次处理一个事件(即使有等待)。
// Do not use if concurrent execution is required. 如果需要并发执行,请不要使用。
console.log(event); // prints ['bar'] [42]
}
// Unreachable here此处无法访问 })();
Returns an 返回迭代AsyncIterator
that iterates eventName
events. eventName
事件的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
可用于取消等待事件:
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());
The name of the event being listened for正在侦听的事件的名称
that iterates 迭代eventName
events emitted by the emitter
emitter
发出的eventName
事件
Creates a 创建一个Promise
that is fulfilled when the EventEmitter
emits the given event or that is rejected if the EventEmitter
emits 'error'
while waiting. Promise
,当EventEmitter
发出给定事件时,该Promise
将被满足,或者当EventEmitter
在等待时发出'error'
时,该Promise
被拒绝。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'
。
const { once, EventEmitter } = require('events');
async function run() {
const ee = new EventEmitter();
process.nextTick(() => {
ee.emit('myevent', 42);
});
const [value] = await once(ee, 'myevent');
console.log(value);
const err = new Error('kaboom');
process.nextTick(() => {
ee.emit('error', err);
});
try {
await once(ee, 'myevent');
} catch (err) {
console.log('error happened', err);
}
}
run();
The special handling of the 'error'
event is only used when events.once()
is used to wait for another event. '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'
事件本身,则它将被视为任何其他类型的事件,无需特殊处理:
const { EventEmitter, once } = require('events');
const ee = new EventEmitter();
once(ee, 'error')
.then(([err]) => console.log('ok', err.message))
.catch((err) => console.log('error', err.message));
ee.emit('error', new Error('boom'));
// Prints: ok boom
An AbortSignal
can be used to cancel waiting for the event:AbortSignal
可用于取消等待事件:
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!
const { setMaxListeners, EventEmitter } = require('events');
const target = new EventTarget();
const emitter = new EventEmitter();
setMaxListeners(5, target, emitter);
A non-negative number. 非负数。The maximum number of listeners per 每个EventTarget
event.EventTarget
事件的最大侦听器数。
A utility method for creating a web 从Readable创建web ReadableStream
from a Readable
.ReadableStream
的实用程序方法。
Generated using TypeDoc
A readable stream that enables you to read buffers from GridFS.一个可读的流,使您能够从GridFS读取缓冲区。Do not instantiate this class directly.不要直接实例化这个类。Use请改用openDownloadStream()
instead.openDownloadStream()
。