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;
}
参考
- stream to buffer: https://stackoverflow.com/questions/14269233/node-js-how-to-read-a-stream-into-a-buffer
- buffer to stream: http://derpturkey.com/buffer-to-stream-in-node/