new stream.Duplex(options)
options<Object> 传给Writable和Readable构造函数。 还具有以下字段:allowHalfOpen<boolean> 如果设置为false,则流将在可读端结束时自动结束可写端。 默认值:true。readable<boolean> 设置Duplex是否可读。 默认值:true。writable<boolean> 设置Duplex是否可写。 默认值:true。readableObjectMode<boolean> 为流的可读端设置objectMode。 如果objectMode是true,则无效。 默认值:false。writableObjectMode<boolean> 为流的可写端设置objectMode。 如果objectMode是true,则无效。 默认值: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 bothWritableandReadableconstructors. Also has the following fields:allowHalfOpen<boolean> If set tofalse, then the stream will automatically end the writable side when the readable side ends. Default:true.readable<boolean> Sets whether theDuplexshould be readable. Default:true.writable<boolean> Sets whether theDuplexshould be writable. Default:true.readableObjectMode<boolean> SetsobjectModefor readable side of the stream. Has no effect ifobjectModeistrue. Default:false.writableObjectMode<boolean> SetsobjectModefor writable side of the stream. Has no effect ifobjectModeistrue. Default:false.readableHighWaterMark<number> SetshighWaterMarkfor the readable side of the stream. Has no effect ifhighWaterMarkis provided.writableHighWaterMark<number> SetshighWaterMarkfor the writable side of the stream. Has no effect ifhighWaterMarkis 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) {
// ...
}
});