Syuusuke
6/3/2019 - 4:41 PM

stream和Buffer互相转换

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

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





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

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