Class GridFSBucketWriteStream

A writable stream that enables you to write buffers to GridFS.一个可写流,使您能够将缓冲区写入GridFS。

Do not instantiate this class directly. 不要直接实例化这个类。Use openUploadStream() instead.请改用openUploadStream()

Hierarchy

  • Writable
    • GridFSBucketWriteStream

Properties

bucket: GridFSBucket
bufToStore: Buffer

Space used to store a chunk currently being inserted用于存储当前插入的区块的空间

chunkSizeBytes: number

The number of bytes that each chunk will be limited to每个区块将被限制的字节数

A Collection instance where the file's chunks are stored存储文件块的Collection实例

closed: boolean

Is true after 'close' has been emitted.在发出'close'之后为true

Since

v18.0.0

destroyed: boolean

Is true after writable.destroy() has been called.在调用writable.destroy()后为true

Since

v8.0.0

done: boolean

Indicates the stream is finished uploading指示流已完成上载

errored: null | Error

Returns error if the stream has been destroyed with an error.如果流已被错误破坏,则返回错误。

Since

v18.0.0

filename: string

The name of the file文件的名称

A Collection instance where the file's GridFSFile document is stored存储文件的GridFSFile文档的Collection实例

gridFSFile: null | GridFSFile = null

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

Example

fs.createReadStream('file.txt')
.pipe(bucket.openUploadStream('file.txt'))
.on('finish', function () {
console.log(this.gridFSFile)
})

The ObjectId used for the _id field on the GridFSFile document用于GridFSFile文档上_id字段的ObjectId

length: number

Accumulates the number of bytes inserted as the stream uploads chunks累积流上载块时插入的字节数

n: number

Accumulates the number of chunks inserted as the stream uploads file contents累积流上载文件内容时插入的块数

Options controlling the metadata inserted along with the file控制与文件一起插入的元数据的选项

pos: number

Tracks the current offset into the buffered bytes being uploaded将当前偏移量跟踪到正在上载的缓冲字节中

state: {
    aborted: boolean;
    errored: boolean;
    outstandingRequests: number;
    streamEnd: boolean;
}

Contains a number of properties indicating the current state of the stream包含指示流的当前状态的多个属性

Type declaration

  • aborted: boolean

    If set the stream was intentionally aborted如果设置,流被故意中止

  • errored: boolean

    If set an error occurred during insertion如果设置,则在插入过程中发生错误

  • outstandingRequests: number

    Indicates the number of chunks that still need to be inserted to exhaust the current buffered data指示仍需要插入以耗尽当前缓冲数据的块数

  • streamEnd: boolean

    If set the stream has ended如果设置,则流已结束

writable: boolean

Is true if it is safe to call writable.write(), which means the stream has not been destroyed, errored, or ended.如果调用writable.write()是安全的,则为true,这意味着流没有被破坏、出错或结束。

Since

v11.4.0

writableCorked: number

Number of times writable.uncork() needs to be called in order to fully uncork the stream.为了完全取消对流的标记,需要调用writable.unmark()的次数。

Since

v13.2.0, v12.16.0

writableEnded: boolean

Is true after writable.end() has been called. 在调用writable.end()后为trueThis property does not indicate whether the data has been flushed, for this use writable.writableFinished instead.此属性不指示数据是否已刷新,为此使用writable.writableFinished

Since

v12.9.0

writableFinished: boolean

Is set to true immediately before the 'finish' event is emitted.在发出'finish'事件之前立即设置为true

Since

v12.6.0

writableHighWaterMark: number

Return the value of highWaterMark passed when creating this Writable.返回创建此Writable时传递的highWaterMark的值。

Since

v9.3.0

writableLength: number

This property contains the number of bytes (or objects) in the queue ready to be written. The value provides introspection data regarding the status of the highWaterMark.此属性包含队列中准备写入的字节数(或对象数)。该值提供有关highWaterMark状态的内省数据。

Since

v9.4.0

writableNeedDrain: boolean

Is true if the stream's buffer has been full and stream will emit 'drain'.如果流的缓冲区已满并且流将发出'drain',则为true

Since

v15.2.0, v14.17.0

writableObjectMode: boolean

Getter for the property objectMode of a given Writable stream.给定可写流的属性objectModeGetter

Since

v12.3.0

writeConcern?: WriteConcern

The write concern setting to be used with every insert operation每次插入操作都要使用的写入关注设置

captureRejectionSymbol: typeof captureRejectionSymbol
captureRejections: boolean

Sets or gets the default captureRejection value for all emitters.设置或获取所有发射器的默认captureRejection值。

defaultMaxListeners: number
errorMonitor: typeof errorMonitor

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'侦听器,进程仍将崩溃。

Methods

  • Parameters

    • error: null | Error
    • callback: ((error?) => void)
        • (error?): void
        • Parameters

          • Optional error: null | Error

          Returns void

    Returns void

  • Parameters

    • chunks: {
          chunk: any;
          encoding: BufferEncoding;
      }[]
    • callback: ((error?) => void)
        • (error?): void
        • Parameters

          • Optional error: null | Error

          Returns void

    Returns void

  • Places this write stream into an aborted state (all future writes fail) and deletes all chunks that have already been written.将此写入流置于中止状态(所有将来的写入都将失败),并删除所有已写入的块。

    Returns Promise<void>

  • Event emitter The defined events on documents including:事件发射器文档上定义的事件,包括:

    1. close
    2. drain
    3. error
    4. finish
    5. pipe
    6. unpipe

    Parameters

    • event: "close"
    • listener: (() => void)
        • (): void
        • Returns void

    Returns GridFSBucketWriteStream

  • Parameters

    • event: "drain"
    • listener: (() => void)
        • (): void
        • Returns void

    Returns GridFSBucketWriteStream

  • Parameters

    • event: "error"
    • listener: ((err) => void)
        • (err): void
        • Parameters

          • err: Error

          Returns void

    Returns GridFSBucketWriteStream

  • Parameters

    • event: "finish"
    • listener: (() => void)
        • (): void
        • Returns void

    Returns GridFSBucketWriteStream

  • Parameters

    • event: "pipe"
    • listener: ((src) => void)
        • (src): void
        • Parameters

          • src: Readable

          Returns void

    Returns GridFSBucketWriteStream

  • Parameters

    • event: "unpipe"
    • listener: ((src) => void)
        • (src): void
        • Parameters

          • src: Readable

          Returns void

    Returns GridFSBucketWriteStream

  • Parameters

    • event: string | symbol
    • listener: ((...args) => void)
        • (...args): void
        • Parameters

          • Rest ...args: any[]

          Returns void

    Returns GridFSBucketWriteStream

  • 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.当调用uncorkend方法时,缓冲的数据将被刷新。

    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().

    Returns void

    Since

    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 towrite() 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()方法。

    Parameters

    • Optional error: Error

      Optional, an error to emit with 'error' event.可选,一个要与'error'事件一起发出的错误。

    Returns GridFSBucketWriteStream

    Since

    v8.0.0

  • Parameters

    • event: "close"

    Returns boolean

  • Parameters

    • event: "drain"

    Returns boolean

  • Parameters

    • event: "error"
    • err: Error

    Returns boolean

  • Parameters

    • event: "finish"

    Returns boolean

  • Parameters

    • event: "pipe"
    • src: Readable

    Returns boolean

  • Parameters

    • event: "unpipe"
    • src: Readable

    Returns boolean

  • Parameters

    • event: string | symbol
    • Rest ...args: any[]

    Returns boolean

  • 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.可选的chunkencoding参数允许在关闭流之前立即写入最后一个额外的数据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!现在不允许写更多!

    Parameters

    • Optional cb: (() => void)
        • (): void
        • Returns void

    Returns GridFSBucketWriteStream

    Since

    v0.9.4

  • Parameters

    • chunk: any
    • Optional cb: (() => void)
        • (): void
        • Returns void

    Returns GridFSBucketWriteStream

  • Parameters

    • chunk: any
    • encoding: BufferEncoding
    • Optional cb: (() => void)
        • (): void
        • Returns void

    Returns GridFSBucketWriteStream

  • Returns an array listing the events for which the emitter has registered listeners. 返回一个数组,列出发射器已注册侦听器的事件。The values in the array are strings or Symbols.数组中的值是字符串或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) ]

    Returns (string | symbol)[]

    Since

    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

    Returns number

    Since

    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,它将返回在事件的监听器列表中找到监听器的次数。

    Parameters

    • eventName: string | symbol

      The name of the event being listened for正在侦听的事件的名称

    • Optional listener: Function

      The event handler function

    Returns number

    Since

    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] ]

    Parameters

    • eventName: string | symbol

    Returns Function[]

    Since

    v0.1.26

  • Alias for emitter.removeListener().emitter.removeListener()的别名。

    Parameters

    • eventName: string | symbol
    • listener: ((...args) => void)
        • (...args): void
        • Parameters

          • Rest ...args: any[]

          Returns void

    Returns GridFSBucketWriteStream

    Since

    v10.0.0

  • Parameters

    • event: "close"
    • listener: (() => void)
        • (): void
        • Returns void

    Returns GridFSBucketWriteStream

  • Parameters

    • event: "drain"
    • listener: (() => void)
        • (): void
        • Returns void

    Returns GridFSBucketWriteStream

  • Parameters

    • event: "error"
    • listener: ((err) => void)
        • (err): void
        • Parameters

          • err: Error

          Returns void

    Returns GridFSBucketWriteStream

  • Parameters

    • event: "finish"
    • listener: (() => void)
        • (): void
        • Returns void

    Returns GridFSBucketWriteStream

  • Parameters

    • event: "pipe"
    • listener: ((src) => void)
        • (src): void
        • Parameters

          • src: Readable

          Returns void

    Returns GridFSBucketWriteStream

  • Parameters

    • event: "unpipe"
    • listener: ((src) => void)
        • (src): void
        • Parameters

          • src: Readable

          Returns void

    Returns GridFSBucketWriteStream

  • Parameters

    • event: string | symbol
    • listener: ((...args) => void)
        • (...args): void
        • Parameters

          • Rest ...args: any[]

          Returns void

    Returns GridFSBucketWriteStream

  • Parameters

    • event: "close"
    • listener: (() => void)
        • (): void
        • Returns void

    Returns GridFSBucketWriteStream

  • Parameters

    • event: "drain"
    • listener: (() => void)
        • (): void
        • Returns void

    Returns GridFSBucketWriteStream

  • Parameters

    • event: "error"
    • listener: ((err) => void)
        • (err): void
        • Parameters

          • err: Error

          Returns void

    Returns GridFSBucketWriteStream

  • Parameters

    • event: "finish"
    • listener: (() => void)
        • (): void
        • Returns void

    Returns GridFSBucketWriteStream

  • Parameters

    • event: "pipe"
    • listener: ((src) => void)
        • (src): void
        • Parameters

          • src: Readable

          Returns void

    Returns GridFSBucketWriteStream

  • Parameters

    • event: "unpipe"
    • listener: ((src) => void)
        • (src): void
        • Parameters

          • src: Readable

          Returns void

    Returns GridFSBucketWriteStream

  • Parameters

    • event: string | symbol
    • listener: ((...args) => void)
        • (...args): void
        • Parameters

          • Rest ...args: any[]

          Returns void

    Returns GridFSBucketWriteStream

  • Type Parameters

    • T extends WritableStream<T>

    Parameters

    • destination: T
    • Optional options: {
          end?: boolean;
      }
      • Optional end?: boolean

    Returns T

  • Parameters

    • event: "close"
    • listener: (() => void)
        • (): void
        • Returns void

    Returns GridFSBucketWriteStream

  • Parameters

    • event: "drain"
    • listener: (() => void)
        • (): void
        • Returns void

    Returns GridFSBucketWriteStream

  • Parameters

    • event: "error"
    • listener: ((err) => void)
        • (err): void
        • Parameters

          • err: Error

          Returns void

    Returns GridFSBucketWriteStream

  • Parameters

    • event: "finish"
    • listener: (() => void)
        • (): void
        • Returns void

    Returns GridFSBucketWriteStream

  • Parameters

    • event: "pipe"
    • listener: ((src) => void)
        • (src): void
        • Parameters

          • src: Readable

          Returns void

    Returns GridFSBucketWriteStream

  • Parameters

    • event: "unpipe"
    • listener: ((src) => void)
        • (src): void
        • Parameters

          • src: Readable

          Returns void

    Returns GridFSBucketWriteStream

  • Parameters

    • event: string | symbol
    • listener: ((...args) => void)
        • (...args): void
        • Parameters

          • Rest ...args: any[]

          Returns void

    Returns GridFSBucketWriteStream

  • Parameters

    • event: "close"
    • listener: (() => void)
        • (): void
        • Returns void

    Returns GridFSBucketWriteStream

  • Parameters

    • event: "drain"
    • listener: (() => void)
        • (): void
        • Returns void

    Returns GridFSBucketWriteStream

  • Parameters

    • event: "error"
    • listener: ((err) => void)
        • (err): void
        • Parameters

          • err: Error

          Returns void

    Returns GridFSBucketWriteStream

  • Parameters

    • event: "finish"
    • listener: (() => void)
        • (): void
        • Returns void

    Returns GridFSBucketWriteStream

  • Parameters

    • event: "pipe"
    • listener: ((src) => void)
        • (src): void
        • Parameters

          • src: Readable

          Returns void

    Returns GridFSBucketWriteStream

  • Parameters

    • event: "unpipe"
    • listener: ((src) => void)
        • (src): void
        • Parameters

          • src: Readable

          Returns void

    Returns GridFSBucketWriteStream

  • Parameters

    • event: string | symbol
    • listener: ((...args) => void)
        • (...args): void
        • Parameters

          • Rest ...args: any[]

          Returns void

    Returns GridFSBucketWriteStream

  • 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');

    Parameters

    • eventName: string | symbol

    Returns Function[]

    Since

    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的引用,以便可以链接调用。

    Parameters

    • Optional event: string | symbol

    Returns GridFSBucketWriteStream

    Since

    v0.1.26

  • Parameters

    • event: "close"
    • listener: (() => void)
        • (): void
        • Returns void

    Returns GridFSBucketWriteStream

  • Parameters

    • event: "drain"
    • listener: (() => void)
        • (): void
        • Returns void

    Returns GridFSBucketWriteStream

  • Parameters

    • event: "error"
    • listener: ((err) => void)
        • (err): void
        • Parameters

          • err: Error

          Returns void

    Returns GridFSBucketWriteStream

  • Parameters

    • event: "finish"
    • listener: (() => void)
        • (): void
        • Returns void

    Returns GridFSBucketWriteStream

  • Parameters

    • event: "pipe"
    • listener: ((src) => void)
        • (src): void
        • Parameters

          • src: Readable

          Returns void

    Returns GridFSBucketWriteStream

  • Parameters

    • event: "unpipe"
    • listener: ((src) => void)
        • (src): void
        • Parameters

          • src: Readable

          Returns void

    Returns GridFSBucketWriteStream

  • Parameters

    • event: string | symbol
    • listener: ((...args) => void)
        • (...args): void
        • Parameters

          • Rest ...args: any[]

          Returns void

    Returns GridFSBucketWriteStream

  • The writable.setDefaultEncoding() method sets the default encoding for a Writable stream.writable.setDefaultEncoding()方法为Writable流设置默认encoding

    Parameters

    • encoding: BufferEncoding

      The new default encoding新的默认编码

    Returns GridFSBucketWriteStream

    Since

    v0.11.15

  • By default EventEmitters 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 toInfinity (or 0) to indicate an unlimited number of listeners.该值可以设置为Infinity(或0),以表示侦听器的数量不受限制。

    Returns a reference to the EventEmitter, so that calls can be chained.返回对EventEmitter的引用,以便可以链接调用。

    Parameters

    • n: number

    Returns GridFSBucketWriteStream

    Since

    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 allwritable.write() calls that occur within a given Node.js event loop phase.这样做允许对给定Node.js事件循环阶段内发生的所有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().

    Returns void

    Since

    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()方法将一些数据写入流,并在数据完全处理后调用所提供的callbackIf 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中并使用pipeHowever, 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参数。

    Parameters

    • chunk: any

      Optional data to write. 要写入的可选数据。For streams not operating in object mode, chunk must be a string, Buffer or Uint8Array. 对于不在对象模式下操作的流,chunk必须是字符串、BufferUint8ArrayFor 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.刷新此数据块时的回调。

        • (error): void
        • Parameters

          • error: undefined | null | Error

          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.如果流希望调用代码在继续写入附加数据之前等待'drain'事件的发出,则为false;否则为true

    Since

    v0.9.4

  • Parameters

    • chunk: any
    • encoding: BufferEncoding
    • Optional callback: ((error) => void)
        • (error): void
        • Parameters

          • error: undefined | null | Error

          Returns void

    Returns boolean

  • Experimental

    A utility method for creating a Writable from a web WritableStream.一种从web WritableStream创建可Writable的实用方法。

    Parameters

    • writableStream: WritableStream<any>
    • Optional options: Pick<WritableOptions, "objectMode" | "highWaterMark" | "signal" | "decodeStrings">

    Returns Writable

    Since

    v17.0.0

  • Returns a copy of the array of listeners for the event named eventName.返回名为eventName的事件的侦听器数组的副本。

    For EventEmitters this behaves exactly the same as calling .listeners on the emitter.对于EventEmitter,其行为与在发射器上调用.listeners完全相同。

    For EventTargets 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] ]
    }

    Parameters

    • emitter: EventEmitter | _DOMEventTarget
    • name: string | symbol

    Returns Function[]

    Since

    v15.2.0, v14.17.0

  • A class method that returns the number of listeners for the given eventNameregistered 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

    Parameters

    • emitter: EventEmitter

      The emitter to query要查询的发射器

    • eventName: string | symbol

      The event name事件名称

    Returns number

    Since

    v0.9.12

    Deprecated

    Since v3.2.0 - Use listenerCount instead.

  • import { 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事件的AsyncIteratorIt 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());

    Parameters

    • emitter: EventEmitter
    • eventName: string

      The name of the event being listened for正在侦听的事件的名称

    • Optional options: StaticEventEmitterOptions

    Returns AsyncIterableIterator<any>

    that iterates eventName events emitted by the emitter迭代emitter发出的eventName事件

    Since

    v13.6.0, v12.16.0

  • 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,该PromiseEventEmitter发出给定事件时实现,或者如果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'error' event semantics and does not listen to the 'error' event.此方法是有意通用的,可与web平台EventTarget接口配合使用,该接口没有特殊的'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!打印:等待活动已取消!

    Parameters

    • emitter: _NodeEventTarget
    • eventName: string | symbol
    • Optional options: StaticEventEmitterOptions

    Returns Promise<any[]>

    Since

    v11.13.0, v10.16.0

  • Parameters

    • emitter: _DOMEventTarget
    • eventName: string
    • Optional options: StaticEventEmitterOptions

    Returns Promise<any[]>

  • import { setMaxListeners, EventEmitter } from 'node:events';

    const target = new EventTarget();
    const emitter = new EventEmitter();

    setMaxListeners(5, target, emitter);

    Parameters

    • Optional n: number

      A non-negative number. 一个非负数。The maximum number of listeners per EventTarget event.每个EventTarget事件的最大侦听器数。

    • Rest ...eventTargets: (EventEmitter | _DOMEventTarget)[]

    Returns void

    Since

    v15.4.0

  • Experimental

    A utility method for creating a web WritableStream from a Writable.一种从Writable创建webWritableStream的实用方法。

    Parameters

    • streamWritable: Writable

    Returns WritableStream<any>

    Since

    v17.0.0

Generated using TypeDoc