writable.write(chunk[, encoding][, callback])


  • chunk <string> | <Buffer> | <Uint8Array> | <any> 可选的要写入的数据。 对于不在对象模式下操作的流,chunk 必须是字符串、BufferUint8Array。 对于对象模式的流,chunk 可以是除 null 之外的任何 JavaScript 值。
  • encoding <string> | <null> 如果 chunk 为字符串,则为编码。 默认值: 'utf8'
  • callback <Function> 当刷新此数据块时的回调。
  • 返回: <boolean> 如果流希望调用代码在继续写入其他数据之前等待 'drain' 事件被触发,则为 false;否则为 true

writable.write() 方法将一些数据写入流,并在数据完全处理后调用提供的 callback。 如果发生错误,则 callback 将使用错误作为其第一个参数进行调用。 callback 是异步地调用,并且在 'error' 触发之前。

如果在接纳 chunk 后,内部缓冲区小于当创建流时配置的 highWaterMark,则返回值为 true。 如果返回 false,则应停止进一步尝试将数据写入流,直到触发 'drain' 事件。

当流没有排空时,对 write() 的调用将缓冲 chunk,并返回 false。 一旦所有当前缓冲的块都被排空(操作系统接受交付),则将触发 'drain' 事件。 一旦 write() 返回 false,则在 'drain' 事件触发之前不要写入更多块。 虽然允许在未排空的流上调用 write(),但 Node.js 将缓冲所有写入的块,直到出现最大内存使用量,此时它将无条件中止。 即使在它中止之前,高内存使用量也会导致垃圾收集器性能不佳和高 RSS(通常不会释放回系统,即使在不再需要内存之后)。 由于如果远程对等方不读取数据,TCP 套接字可能永远不会排空,因此写入未排空的套接字可能会导致可远程利用的漏洞。

在流未排空时写入数据对于 Transform 来说尤其成问题,因为 Transform 流是默认暂停,直到它们被管道传输、或添加 'data''readable' 事件句柄。

如果要写入的数据可以按需生成或获取,则建议将逻辑封装成 Readable 并且使用 stream.pipe()。 但是,如果首选调用 write(),则可以使用 'drain' 事件遵守背压并避免内存问题:

function write(data, cb) {
  if (!stream.write(data)) {
    stream.once('drain', cb);
  } else {
    process.nextTick(cb);
  }
}

// 在执行任何其他写入之前等待回调被调用。
write('hello', () => {
  console.log('Write completed, do more writes now.');
});

对象模式下的 Writable 流将始终忽略 encoding 参数。

  • chunk <string> | <Buffer> | <Uint8Array> | <any> Optional data to write. For streams not operating in object mode, chunk must be a string, Buffer or Uint8Array. For object mode streams, chunk may be any JavaScript value other than null.
  • encoding <string> | <null> The encoding, if chunk is a string. Default: 'utf8'
  • callback <Function> Callback for when this chunk of data is flushed.
  • 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.

The writable.write() method writes some data to the stream, and calls the supplied callback once the data has been fully handled. If an error occurs, the callback will be called with the error as its first argument. The callback is called asynchronously and before 'error' is emitted.

The return value is true if the internal buffer is less than the highWaterMark configured when the stream was created after admitting chunk. If false is returned, further attempts to write data to the stream should stop until the 'drain' event is emitted.

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. Once write() returns false, do not write more chunks until the 'drain' event is emitted. While calling write() on a stream that is not draining is allowed, Node.js will buffer all written chunks until maximum memory usage occurs, at which point it will abort unconditionally. Even before it aborts, high memory usage will cause poor garbage collector performance and high RSS (which is not typically released back to the system, even after the memory is no longer required). Since TCP sockets may never drain if the remote peer does not read the data, writing a socket that is not draining may lead to a remotely exploitable vulnerability.

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.

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 stream.pipe(). However, if calling write() is preferred, it is possible to respect backpressure and avoid memory issues using the 'drain' event:

function write(data, cb) {
  if (!stream.write(data)) {
    stream.once('drain', cb);
  } else {
    process.nextTick(cb);
  }
}

// Wait for cb to be called before doing any other write.
write('hello', () => {
  console.log('Write completed, do more writes now.');
});

A Writable stream in object mode will always ignore the encoding argument.