new stream.Readable([options])


  • options <Object>
    • highWaterMark <number> 在停止从底层资源读取之前存储在内部缓冲区中的最大字节数默认值: 16384 (16KB) 或 16 表示 objectMode 流。
    • encoding <string> 如果指定,则缓冲区将使用指定的编码解码为字符串。 默认值: null
    • objectMode <boolean> 此流是否应表现为对象流。 这意味着 stream.read(n) 返回单个值而不是大小为 nBuffer默认值: false
    • emitClose <boolean> 流被销毁后是否应该触发 'close'默认值: true
    • read <Function> stream._read() 方法的实现。
    • destroy <Function> stream._destroy() 方法的实现。
    • autoDestroy <boolean> 此流是否应在结束后自动调用自身的 .destroy()默认值: false
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.
    • emitClose <boolean> Whether or not the stream should emit 'close' after it has been destroyed. Default: true.
    • 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) {
    // ...
  }
});