nodejs stream 创建读写流

时间:2023-12-24 10:03:19
const fs = require("fs");
const { Writable, Readable, Duplex, Transform } = require("stream"); // 双向流
const inoutStream = new Duplex({ // 获取写入的数据
write(chunk, encoding, callback) {
console.log(chunk.toString());
callback();
}, // 一直读直到null为止
read(size) {
this.push(String.fromCharCode(this.currentCharCode++));
if (this.currentCharCode > 90) this.push(null);
},
}); inoutStream.currentCharCode = 65;
process.stdin.pipe(inoutStream).pipe(inoutStream); const sizeStream = new Transform({
readableObjectMode: true,
writableObjectMode: true, // 转换流,可以改变数据
transform(chunk, encoding, callback) {
this.push(chunk.toString() + `\r\n // size(${chunk.length})`);
callback();
},
}); const outStream = new Writable({
write(chunk, encoding, callback) {
console.log(chunk.toString("utf-8"));
callback();
},
}); fs.createReadStream("./x.txt").pipe(sizeStream).pipe(outStream);

See also: