双工流示例


【An example duplex stream】

以下示例说明了一个简单的 Duplex 流,它封装了一个假设的底层源对象,数据可以写入该对象,也可以从中读取数据,尽管使用的 API 与 Node.js 流不兼容。 以下示例说明了一个简单的 Duplex 流,它通过 Writable 接口缓冲写入的传入数据,然后通过 Readable 接口读取出来。

【The following illustrates a simple example of a Duplex stream that wraps a hypothetical lower-level source object to which data can be written, and from which data can be read, albeit using an API that is not compatible with Node.js streams. The following illustrates a simple example of a Duplex stream that buffers incoming written data via the Writable interface that is read back out via the Readable interface.】

const { Duplex } = require('node:stream');
const kSource = Symbol('source');

class MyDuplex extends Duplex {
  constructor(source, options) {
    super(options);
    this[kSource] = source;
  }

  _write(chunk, encoding, callback) {
    // The underlying source only deals with strings.
    if (Buffer.isBuffer(chunk))
      chunk = chunk.toString();
    this[kSource].writeSomeData(chunk);
    callback();
  }

  _read(size) {
    this[kSource].fetchSomeData(size, (data, encoding) => {
      this.push(Buffer.from(data, encoding));
    });
  }
} 

Duplex 流最重要的方面是,尽管 ReadableWritable 两个部分共存于同一个对象实例中,但它们仍能彼此独立地操作。

【The most important aspect of a Duplex stream is that the Readable and Writable sides operate independently of one another despite co-existing within a single object instance.】