node 怎样把stream 转成buffer对象?

node 怎样把stream 转成buffer对象?

阅读 10.2k
1 个回答

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

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

const readStream = fs.createReadStream(path.join(__dirname, 'xxx.txt'))
const buffers = [];
readStream.on('data', function(buffer) {
  buffers.push(buffer);
});
readStream.on('end', function() {
  const data = Buffer.from(buffers);
  //...do your stuff...

  // such as write to file:
  fs.writeFile('xxx.txt', data, function(err) {
    // handle error, return response, etc...
  });
});
readStream.on('error', function(error){
  console.error('readStream error:', error.message);
})

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

const readStream = fs.createReadStream(path.join(__dirname, './xxx_read.json'))
const writeStream = fs.createWriteStream(path.join(__dirname, './xxx_write.json'))
readStream.pipe(writeStream)
readStream.on('error', (error) => {
  console.log('readStream error', error.message);
})
writeStream.on('error', (error) => {
  console.log('writeStream error', error.message);
})
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏