node 怎样把stream 转成buffer对象?

node 怎样把stream 转成buffer对象?

问题太短了 我没太理解,我就按照我自己的想法和你说一下

如果不用piping的话,你需要监听你stream的dataend事件
下面是将一个文件的读流,转成buffer,然后写到别的文件里面去

const readStream = fs.createReadStreampath.join__dirname, xxx.txt
const buffers = [];
readStream.ondata, functionbuffer { buffers.pushbuffer;
};
readStream.onend, function { const data = Buffer.frombuffers; //...do your stuff... // such as write to file: fs.writeFilexxx.txt, data, functionerr { // handle error, return response, etc... };
};
readStream.onerror, functionerror{ console.errorreadStream error:, error.message;
}

不过最好推荐使用pip方式,这样如果读的buffer很大的话,对内存会有压力,pip不会

const readStream = fs.createReadStreampath.join__dirname, ./xxx_read.json
const writeStream = fs.createWriteStreampath.join__dirname, ./xxx_write.json
readStream.pipewriteStream
readStream.onerror, error => { console.logreadStream error, error.message;
}
writeStream.onerror, error => { console.logwriteStream error, error.message;
}

发表评论

电子邮件地址不会被公开。 必填项已用*标注