You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
// 可写流使用constfs=require('fs');constwriteStream=fs.createWriteStream('test.txt');lettimes=1000000;constwrite=()=>{letok=true;while(times>=0&&ok){ok=writeStream.write(`this is text ${times}\n`);times--;}if(!ok){writeStream.once('drain',write);}};write();
// duplex.js constnet=require('net');constsocket=net.connect(3000,'127.0.0.1',()=>{socket.write(Buffer.from(`this is a message from duplex.js`));socket.on('data',chunk=>{console.log(`duplex.js has receive: ${chunk.toString()}`)})});// tcp-server.jsconstnet=require('net');constserver=net.createServer(socket=>{console.log(`tcp-server.js on socket: ${socket.remoteAddress}`);// 这是一个双工流socket.on('data',chunk=>{console.log(`tcp-server.js receive: ${chunk.toString()}`);socket.write(`tcp-server.js has receive: ${chunk.toString()}`);})});server.listen(3000);
transfrom 流基本使用
// transform 举例(实际上是 duplex 流的一种)constzlib=require('zlib');constgzip=zlib.createGzip();// 实现了 readable 相关的接口, 可以输出数据gzip.on('data',chunk=>{console.log(`gzip on data: ${chunk}`);});// 实现了 writable 相关接口, 可以写入输入gzip.write('this is some test string');
对象模式
const{ Writable }=require('stream');constmyWritable=newWritable({write(chunk,encoding,callback){// ...console.log(chunk);},objectMode: true});// 如果不设置 objectMode: true, 会报错 TypeError [ERR_INVALID_ARG_TYPE]: The "chunk" argument must be one of type string or Buffer. Received type objectmyWritable.write({key1: 'value1',key2: 'value2'});// 改变已存在流的对象模式是不安全的