实现转换流
【Implementing a transform stream】
Transform 流是一种 Duplex 流,其中输出是通过某种方式从输入计算得出的。示例包括 zlib 流或 加密货币 流,它们用于压缩、加密或解密数据。
【A Transform stream is a Duplex stream where the output is computed
in some way from the input. Examples include zlib streams or crypto
streams that compress, encrypt, or decrypt data.】
输出不要求与输入具有相同的大小、相同数量的块,也不要求同时到达。例如,Hash 流只会有一个输出块,该块在输入结束时提供。zlib 流将生成比输入小得多或大得多的输出。
【There is no requirement that the output be the same size as the input, the same
number of chunks, or arrive at the same time. For example, a Hash stream will
only ever have a single chunk of output which is provided when the input is
ended. A zlib stream will produce output that is either much smaller or much
larger than its input.】
stream.Transform 类被扩展以实现 Transform 流。
【The stream.Transform class is extended to implement a Transform stream.】
stream.Transform 类原型上继承自 stream.Duplex,并且实现了自己的 writable._write() 和 readable._read() 方法。自定义 Transform 实现必须实现 transform._transform() 方法,并且可以实现 transform._flush() 方法。
【The stream.Transform class prototypically inherits from stream.Duplex and
implements its own versions of the writable._write() and
readable._read() methods. Custom Transform implementations must
implement the transform._transform() method and may
also implement the transform._flush() method.】
在使用 Transform 流时必须小心,因为写入流的数据如果未被 Readable 端消费,可能导致流的 Writable 端被暂停。
【Care must be taken when using Transform streams in that data written to the
stream can cause the Writable side of the stream to become paused if the
output on the Readable side is not consumed.】