writable._write(chunk, encoding, callback)


  • chunk <Buffer> | <string> | <any> 要写入的 Buffer,由传递给 stream.write()string 转换而来。如果流的 decodeStrings 选项为 false 或者流正以对象模式运行,该 chunk 将不会被转换,并且将保持为传递给 stream.write() 的原始内容。
  • encoding <string> 如果块是一个字符串,则 encoding 是该字符串的字符编码。如果块是一个 Buffer,或者流在对象模式下运行,则可能会忽略 encoding
  • callback <Function> 在处理完提供的块后,调用此函数(可选择传入错误参数)。

所有 Writable 流实现都必须提供 writable._write() 和/或 writable._writev() 方法来向底层资源发送数据。

【All Writable stream implementations must provide a writable._write() and/or writable._writev() method to send data to the underlying resource.】

Transform 流提供了它们自己的 writable._write() 实现。

此函数绝对不能被应用代码直接调用。它应由子类实现,并且仅由内部的 Writable 类方法调用。

【This function MUST NOT be called by application code directly. It should be implemented by child classes, and called by the internal Writable class methods only.】

callback 函数必须在 writable._write() 内同步调用,或者异步调用(即不同的事件循环周期),以表示写操作是成功完成还是出现了错误。如果调用失败,传递给 callback 的第一个参数必须是 Error 对象;如果写操作成功,则应为 null

【The callback function must be called synchronously inside of writable._write() or asynchronously (i.e. different tick) to signal either that the write completed successfully or failed with an error. The first argument passed to the callback must be the Error object if the call failed or null if the write succeeded.】

在调用 writable._write() 和回调 callback 之间发生的所有 writable.write() 调用都会导致写入的数据被缓冲。当调用 callback 时,流可能会触发一个 'drain' 事件。如果流的实现能够一次处理多个数据块,则应实现 writable._writev() 方法。

【All calls to writable.write() that occur between the time writable._write() is called and the callback is called will cause the written data to be buffered. When the callback is invoked, the stream might emit a 'drain' event. If a stream implementation is capable of processing multiple chunks of data at once, the writable._writev() method should be implemented.】

如果在构造函数选项中显式将 decodeStrings 属性设置为 false,那么 chunk 将保持传递给 .write() 的相同对象,并且可能是字符串而不是 Buffer。这是为了支持对某些字符串数据编码有优化处理的实现。在这种情况下,encoding 参数将指示字符串的字符编码。否则,可以安全地忽略 encoding 参数。

【If the decodeStrings property is explicitly set to false in the constructor options, then chunk will remain the same object that is passed to .write(), and may be a string rather than a Buffer. This is to support implementations that have an optimized handling for certain string data encodings. In that case, the encoding argument will indicate the character encoding of the string. Otherwise, the encoding argument can be safely ignored.】

writable._write() 方法前面有一个下划线,因为它是定义该方法的类的内部方法,用户程序不应直接调用它。

【The writable._write() method is prefixed with an underscore because it is internal to the class that defines it, and should never be called directly by user programs.】