new stream.Duplex(options)
options<Object> 传递给Writable和Readable构造函数。还有以下字段:allowHalfOpen<boolean> 如果设置为false,当可读端结束时,可写端将自动结束。默认值:true。n *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('node:stream');
class MyDuplex extends Duplex {
constructor(options) {
super(options);
// ...
}
} 或者,当使用 ES6 之前的样式构造函数时:
【Or, when using pre-ES6 style constructors:】
const { Duplex } = require('node:stream');
const util = require('node: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('node:stream');
const myDuplex = new Duplex({
read(size) {
// ...
},
write(chunk, encoding, callback) {
// ...
},
}); 使用管道时:
【When using pipeline:】
const { Transform, pipeline } = require('node:stream');
const fs = require('node:fs');
pipeline(
fs.createReadStream('object.json')
.setEncoding('utf8'),
new Transform({
decodeStrings: false, // Accept string input rather than Buffers
construct(callback) {
this.data = '';
callback();
},
transform(chunk, encoding, callback) {
this.data += chunk;
callback();
},
flush(callback) {
try {
// Make sure is valid json.
JSON.parse(this.data);
this.push(this.data);
callback();
} catch (err) {
callback(err);
}
},
}),
fs.createWriteStream('valid-object.json'),
(err) => {
if (err) {
console.error('failed', err);
} else {
console.log('completed');
}
},
);