new stream.Duplex(options)


  • options <Object> 同时传给 WritableReadable 的构造函数。  * allowHalfOpen <boolean> 如果设为 false,则当可读端结束时,可写端也会自动结束。 默认为 true

    • readableObjectMode <boolean> 设置流的可读端为 objectMode。 如果 objectModetrue,则不起作用。 默认为 false

    • writableObjectMode <boolean> 设置流的可写端为 objectMode。 如果 objectModetrue,则不起作用。 默认为 false

    • readableHighWaterMark <number> 设置流的可读端的 highWaterMark。 如果已经设置了 highWaterMark,则不起作用。

    • writableHighWaterMark <number> 设置流的可写端的 highWaterMark。 如果已经设置了 highWaterMark,则不起作用。

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

class MyDuplex extends Duplex {
  constructor(options) {
    super(options);
    // ...
  }
}

使用 ES6 之前的语法:

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

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

使用简化的构造函数:

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

const myDuplex = new Duplex({
  read(size) {
    // ...
  },
  write(chunk, encoding, callback) {
    // ...
  }
});
  • options <Object> Passed to both Writable and Readable constructors. Also has the following fields:

    • allowHalfOpen <boolean> If set to false, then the stream will automatically end the writable side when the readable side ends. Default: true.
    • readableObjectMode <boolean> Sets objectMode for readable side of the stream. Has no effect if objectMode is true. Default: false.
    • writableObjectMode <boolean> Sets objectMode for writable side of the stream. Has no effect if objectMode is true. Default: false.
    • readableHighWaterMark <number> Sets highWaterMark for the readable side of the stream. Has no effect if highWaterMark is provided.
    • writableHighWaterMark <number> Sets highWaterMark for the writable side of the stream. Has no effect if highWaterMark is provided.
const { Duplex } = require('stream');

class MyDuplex extends Duplex {
  constructor(options) {
    super(options);
    // ...
  }
}

Or, when using pre-ES6 style constructors:

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

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

Or, using the Simplified Constructor approach:

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

const myDuplex = new Duplex({
  read(size) {
    // ...
  },
  write(chunk, encoding, callback) {
    // ...
  }
});