Space used to store a chunk currently being inserted用于存储当前插入的区块的空间
The number of bytes that each chunk will be limited to每个区块将被限制的字节数
A Collection instance where the file's chunks are stored存储文件块的Collection实例
Readonly
closedIs 在发出true
after 'close'
has been emitted.'close'
之后为true
。
v18.0.0
Is 在调用true
after writable.destroy()
has been called.writable.destroy()
后为true
。
v8.0.0
Indicates the stream is finished uploading指示流已完成上载
Readonly
erroredReturns error if the stream has been destroyed with an error.如果流已被错误破坏,则返回错误。
v18.0.0
The name of the file文件的名称
A Collection instance where the file's GridFSFile document is stored存储文件的GridFSFile文档的Collection实例
The document containing information about the inserted file.包含有关插入文件的信息的文档。This property is defined after the finish event has been emitted.此属性是在发出finish事件之后定义的。It will remain 如果发生错误,它将保持为null
if an error occurs.null
。
fs.createReadStream('file.txt')
.pipe(bucket.openUploadStream('file.txt'))
.on('finish', function () {
console.log(this.gridFSFile)
})
The ObjectId used for the 用于GridFSFile文档上_id
field on the GridFSFile document_id
字段的ObjectId
Accumulates the number of bytes inserted as the stream uploads chunks累积流上载块时插入的字节数
Accumulates the number of chunks inserted as the stream uploads file contents累积流上载文件内容时插入的块数
Options controlling the metadata inserted along with the file控制与文件一起插入的元数据的选项
Tracks the current offset into the buffered bytes being uploaded将当前偏移量跟踪到正在上载的缓冲字节中
Contains a number of properties indicating the current state of the stream包含指示流的当前状态的多个属性
If set the stream was intentionally aborted如果设置,流被故意中止
If set an error occurred during insertion如果设置,则在插入过程中发生错误
Indicates the number of chunks that still need to be inserted to exhaust the current buffered data指示仍需要插入以耗尽当前缓冲数据的块数
If set the stream has ended如果设置,则流已结束
Readonly
writableIs 如果调用true
if it is safe to call writable.write()
, which means the stream has not been destroyed, errored, or ended.writable.write()
是安全的,则为true
,这意味着流没有被破坏、出错或结束。
v11.4.0
Readonly
writableNumber of times 为了完全取消对流的标记,需要调用writable.uncork()
needs to be called in order to fully uncork the stream.writable.unmark()
的次数。
v13.2.0, v12.16.0
Readonly
writableIs 在调用true
after writable.end()
has been called. writable.end()
后为true
。This property does not indicate whether the data has been flushed, for this use 此属性不指示数据是否已刷新,为此使用writable.writableFinished
instead.writable.writableFinished
。
v12.9.0
Readonly
writableIs set to 在发出true
immediately before the 'finish'
event is emitted.'finish'
事件之前立即设置为true
。
v12.6.0
Readonly
writableReturn the value of 返回创建此highWaterMark
passed when creating this Writable
.Writable
时传递的highWaterMark
的值。
v9.3.0
Readonly
writableThis property contains the number of bytes (or objects) in the queue ready to be written. The value provides introspection data regarding the status of the 此属性包含队列中准备写入的字节数(或对象数)。该值提供有关highWaterMark
.highWaterMark
状态的内省数据。
v9.4.0
Readonly
writableIs 如果流的缓冲区已满并且流将发出true
if the stream's buffer has been full and stream will emit 'drain'
.'drain'
,则为true
。
v15.2.0, v14.17.0
Readonly
writableGetter for the property 给定可写流的属性objectMode
of a given Writable
stream.objectMode
的Getter
。
v12.3.0
Optional
writeThe write concern setting to be used with every insert operation每次插入操作都要使用的写入关注设置
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
_writevEvent emitter The defined events on documents including:事件发射器文档上定义的事件,包括:
Rest
...args: any[]The writable.cork()
method forces all written data to be buffered in memory.writable.cork()
方法强制将所有写入的数据缓冲在内存中。
The buffered data will be flushed when either the uncork or end methods are called.当调用uncork或end方法时,缓冲的数据将被刷新。
The primary intent of writable.cork()
is to accommodate a situation in which several small chunks are written to the stream in rapid succession. writable.cork()
的主要目的是适应这样一种情况,即几个小块被快速连续地写入流中。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. writable.cock()
不是立即将它们转发到底层目的地,而是缓冲所有块,直到调用writable.uncork()
,这将把它们全部传递给writable._writev()
,如果存在。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._writev()
的情况下使用writable.cork()
_writev()
可能会对吞吐量产生不利影响。
See also: writable.uncork()
, writable._writev()
.
v0.11.2
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 writable stream has ended and subsequent calls to 此调用之后,可写流已结束,随后对write()
or end()
will result in an ERR_STREAM_DESTROYED
error.write()
或end()
的调用将导致ERR_STREAM_DESTROYED
错误。This is a destructive and immediate way to destroy a stream. 这是一种破坏性的、直接的破坏溪流的方法。Previous calls to以前对write()
may not have drained, and may trigger an ERR_STREAM_DESTROYED
error. write()
的调用可能没有耗尽,可能会触发ERR_STREAM_DESTROYED
错误。Use 如果数据应该在关闭前刷新,请使用end()
instead of destroy if data should flush before close, or wait for the 'drain'
event before destroying the stream.end()
而不是destroy,或者在销毁流之前等待'drain'
事件。
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 实现程序不应重写此方法,而应实现writable._destroy()
.writable._destroy()
方法。
Optional
error: ErrorOptional, an error to emit with 可选,一个要与'error'
event.'error'
事件一起发出的错误。
v8.0.0
Rest
...args: any[]Calling the 调用writable.end()
method signals that no more data will be written to the Writable
. writable.end()
方法表示将不再向Writable
写入数据。The optional 可选的chunk
and encoding
arguments allow one final additional chunk of data to be written immediately before closing the stream.chunk
和encoding
参数允许在关闭流之前立即写入最后一个额外的数据chunk。
Calling the write method after calling end will raise an error.在调用end之后调用write方法将引发错误。
// Write 'hello, ' and then end with 'world!'.
const fs = require('node:fs');
const file = fs.createWriteStream('example.txt');
file.write('hello, ');
file.end('world!');
// Writing more now is not allowed!现在不允许写更多!
Optional
cb: (() => void)v0.9.4
Optional
cb: (() => void)Optional
cb: (() => void)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
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[]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
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 writable.setDefaultEncoding()
method sets the default encoding
for a Writable
stream.writable.setDefaultEncoding()
方法为Writable
流设置默认encoding
。
The new default encoding新的默认编码
v0.11.15
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
The writable.uncork()
method flushes all data buffered since cork was called.writable.uncork()
方法刷新自调用cork以来缓冲的所有数据。
When using 当使用writable.cork()
and writable.uncork()
to manage the buffering of writes to a stream, defer calls to writable.uncork()
usingprocess.nextTick()
. writable.cock()
和writable.uncork()
来管理对流的写入缓冲时,请使用process.nextTick()
延迟对writable.uncork()
的调用。Doing so allows batching of all这样做允许对给定Node.js事件循环阶段内发生的所有writable.write()
calls that occur within a given Node.js event loop phase.writable.write()
调用进行批处理。
stream.cork();
stream.write('some ');
stream.write('data ');
process.nextTick(() => stream.uncork());
If the 如果在流上多次调用writable.cork()
method is called multiple times on a stream, the same number of calls to writable.uncork()
must be called to flush the buffered data.writable.cock()
方法,则必须调用相同数量的writable.uncork()
调用来刷新缓冲的数据。
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.在第二次调用uncork()之前,不会刷新数据。
stream.uncork();
});
See also: writable.cork()
.
v0.11.2
The writable.write()
method writes some data to the stream, and calls the supplied callback
once the data has been fully handled. writable.write()
方法将一些数据写入流,并在数据完全处理后调用所提供的callback
。If an error occurs, the 如果发生错误,将调用callback
will be called with the error as its first argument. callback
,并将该错误作为其第一个参数。The callback
is called asynchronously and before 'error'
is emitted.callback
是异步调用的,并且在发出'error'
之前。
The return value is 如果内部缓冲区小于在允许true
if the internal buffer is less than thehighWaterMark
configured when the stream was created after admitting chunk
.chunk
后创建流时配置的highWaterMark
,则返回值为true
。
If 如果返回false
is returned, further attempts to write data to the stream should stop until the 'drain'
event is emitted.false
,则应停止向流写入数据的进一步尝试,直到发出“drain”事件。
While a stream is not draining, calls to 当流没有耗尽时,对write()
will buffer chunk
, and return false. Once all currently buffered chunks are drained (accepted for delivery by the operating system), the 'drain'
event will be emitted.write()
的调用将缓冲chunk
,并返回false
。一旦所有当前缓冲的块都被耗尽(操作系统接受交付),就会发出“耗尽”事件。
Once 一旦write()
returns false, do not write more chunks until the 'drain'
event is emitted. write()
返回false
,在发出'drain'
事件之前不要再写入块。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.write()
,但Node.js将缓冲所有写入的块,直到出现最大内存使用率,此时它将无条件中止。
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). 即使在它中止之前,高内存使用率也会导致垃圾集合器性能差和RSS高(即使在不再需要内存之后,通常也不会将其释放回系统)。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.由于如果远程对等端不读取数据,TCP套接字可能永远不会耗尽,因此写入未耗尽的套接字可能会导致可远程利用的漏洞。
Writing data while the stream is not draining is particularly problematic for a 在流未排出时写入数据对Transform
, because the Transform
streams are paused by default until they are piped or a 'data'
or 'readable'
event handler is added.Transform
来说尤其有问题,因为Transform
流在默认情况下会暂停,直到它们通过管道传输或添加'data'
或'readable'
事件处理程序。
If the data to be written can be generated or fetched on demand, it is recommended to encapsulate the logic into a 如果要写入的数据可以根据需要生成或提取,建议将逻辑封装到Readable
and use pipe. Readable
中并使用pipe。However, if calling 但是,如果首选调用write()
is preferred, it is possible to respect backpressure and avoid memory issues using the 'drain'
event:write()
,则可以使用'drain'
事件来尊重背压并避免内存问题:
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.在执行任何其他写入操作之前,请等待cb被调用。
write('hello', () => {
console.log('Write completed, do more writes now.');
});
A 对象模式下的Writable
stream in object mode will always ignore the encoding
argument.Writable
流将始终忽略encoding
参数。
Optional data to write. 要写入的可选数据。For streams not operating in object mode, 对于不在对象模式下操作的流,chunk
must be a string, Buffer
or Uint8Array
. chunk
必须是字符串、Buffer
或Uint8Array
。For object mode streams, 对于对象模式流,chunk
may be any JavaScript value other than null
.chunk
可以是除null
之外的任何JavaScript值。
Optional
callback: ((error) => void)Callback for when this chunk of data is flushed.刷新此数据块时的回调。
如果流希望调用代码在继续写入附加数据之前等待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
.'drain'
事件的发出,则为false
;否则为true
。
v0.9.4
Optional
callback: ((error) => void)Static
fromExperimental
A utility method for creating a 一种从web Writable
from a web WritableStream
.WritableStream
创建可Writable
的实用方法。
Optional
options: Pick<WritableOptions, "objectMode" | "highWaterMark" | "signal" | "decodeStrings">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
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 返回一个迭代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
可用于取消等待事件:
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 writable stream that enables you to write buffers to GridFS.一个可写流,使您能够将缓冲区写入GridFS。Do not instantiate this class directly.不要直接实例化这个类。Use请改用openUploadStream()
instead.openUploadStream()
。