new stream.Readable([options])


  • options <Object>

    • highWaterMark <number> 从底层资源读取数据并存储在内部缓冲区中的最大字节数。 默认为 16384 (16kb), 对象模式的流默认为 16
    • encoding <string> 如果指定了,则使用指定的字符编码将 buffer 解码成字符串。 默认为 null
    • objectMode <boolean> 流是否可以是一个对象流。 也就是说 stream.read(n) 会返回对象而不是 Buffer。 默认为 false
    • read <Function>stream._read() 方法的实现。
    • destroy <Function>stream._destroy() 方法的实现。
const { Readable } = require('stream');

class MyReadable extends Readable {
  constructor(options) {
    // 调用 stream.Readable(options) 构造函数。
    super(options);
    // ...
  }
}

使用 ES6 之前的语法:

const { Readable } = require('stream');
const util = require('util');

function MyReadable(options) {
  if (!(this instanceof MyReadable))
    return new MyReadable(options);
  Readable.call(this, options);
}
util.inherits(MyReadable, Readable);

使用简化的构造函数:

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

const myReadable = new Readable({
  read(size) {
    // ...
  }
});
  • options <Object>

    • highWaterMark <number> The maximum number of bytes to store in the internal buffer before ceasing to read from the underlying resource. Default: 16384 (16kb), or 16 for objectMode streams.
    • encoding <string> If specified, then buffers will be decoded to strings using the specified encoding. Default: null.
    • objectMode <boolean> Whether this stream should behave as a stream of objects. Meaning that stream.read(n) returns a single value instead of a Buffer of size n. Default: false.
    • read <Function> Implementation for the stream._read() method.
    • destroy <Function> Implementation for the stream._destroy() method.
    • autoDestroy <boolean> Whether this stream should automatically call .destroy() on itself after ending. Default: false.
const { Readable } = require('stream');

class MyReadable extends Readable {
  constructor(options) {
    // Calls the stream.Readable(options) constructor
    super(options);
    // ...
  }
}

Or, when using pre-ES6 style constructors:

const { Readable } = require('stream');
const util = require('util');

function MyReadable(options) {
  if (!(this instanceof MyReadable))
    return new MyReadable(options);
  Readable.call(this, options);
}
util.inherits(MyReadable, Readable);

Or, using the Simplified Constructor approach:

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

const myReadable = new Readable({
  read(size) {
    // ...
  }
});