nodejs stream & buffer 互相转换

stream 转 buffer

function streamToBuffer(stream) {  
  return new Promise((resolve, reject) => {
    let buffers = [];
    stream.on('error', reject);
    stream.on('data', (data) => buffers.push(data))
    stream.on('end', () => resolve(Buffer.concat(buffers))
  });
}

buffer 转 stream

let Duplex = require('stream').Duplex;

function bufferToStream(buffer) {  
  let stream = new Duplex();
  stream.push(buffer);
  stream.push(null);
  return stream;
}

参考

posted @ 2017-07-22 22:48  buzzjan  阅读(9491)  评论(0编辑  收藏  举报