notes icon indicating copy to clipboard operation
notes copied to clipboard

get specific size data from a stream of node.js

Open lanlin opened this issue 5 years ago • 0 comments

场景

有时候期望只获取部分流数据,以此来断定文件类型或者处理其他逻辑,而不是直接把整个文件下载下来。

方法 (node.js)

const getFromStream = async (stream, maxSize) => {
  return new Promise((resolve, reject) => {
    let size = 0;
    let bufs = [];

    stream.on('data', (chunk) => {
      if (size > maxSize) {
        stream.destroy();
        return;
      }

      bufs.push(chunk);
      size += chunk.length;
    });

    stream.on('end', () => {
      stream.destroy();
    });

    stream.on('error', (err) => {
      stream.destroy();
      reject(err);
    });

    stream.on('close', () => {
      resolve(Buffer.concat(bufs));
    });
  });
};

使用

const fs = require('fs');

const maxSize = 1024 * 16;  // 16K size

const stream = fs.createReadStream('path/to/test.png');   // target stream

const result = await getFromStream(stream, maxSize);     // buffer result

lanlin avatar Jul 02 '20 09:07 lanlin