用于实现流的 API


stream 模块 API 的设计是为了更容易使用 JavaScript 的原型继承模式来实现流。

流的开发者可以声明一个新的 JavaScript 类并继承四个基本流类中之一(stream.Writeablestream.Readablestream.Duplexstream.Transform),且确保调用了对应的父类构造器:

const { Writable } = require('stream');

class MyWritable extends Writable {
  constructor(options) {
    super(options);
    // ...
  }
}

根据所创建的流类型,新的流类必须实现一个或多个特定的方法,如下图所示:

用例需实现的方法
只读流Readable_read
只写流Writable_write, _writev, _final
可读可写流Duplex_read, _write, _writev, _final
对写入的数据进行操作,然后读取结果Transform_transform, _flush, _final

实现流的代码中不应该调用流的公共方法,因为这些方法是给消费者使用的(详见用于消费流的API)。 这样做可能会导致使用流的应用程序代码产生不利的副作用。

The stream module API has been designed to make it possible to easily implement streams using JavaScript's prototypal inheritance model.

First, a stream developer would declare a new JavaScript class that extends one of the four basic stream classes (stream.Writable, stream.Readable, stream.Duplex, or stream.Transform), making sure they call the appropriate parent class constructor:

const { Writable } = require('stream');

class MyWritable extends Writable {
  constructor(options) {
    super(options);
    // ...
  }
}

The new stream class must then implement one or more specific methods, depending on the type of stream being created, as detailed in the chart below:

Use-caseClassMethod(s) to implement
Reading onlyReadable_read
Writing onlyWritable_write, _writev, _final
Reading and writingDuplex_read, _write, _writev, _final
Operate on written data, then read the resultTransform_transform, _flush, _final

The implementation code for a stream should never call the "public" methods of a stream that are intended for use by consumers (as described in the API for Stream Consumers section). Doing so may lead to adverse side effects in application code consuming the stream.