如何在不丢失的情况下读取 NodeJS 流的数据?

How to read data of a NodeJS stream without it being lost?

我需要知道我正在使用 detect-character-encoding 模块的节点流的编码。 但问题是我只能读取缓冲区的编码而不是流的编码,因此我必须这样做:

FileStream.on('data', (chunk) => {
  console.log(chunk)
  const charsetMatch = detectCharacterEncoding(chunk)
  console.log(charsetMatch)
})

了解流编码是以丢失一大块数据为代价的,这在代码流的后面是必需的。有没有一种方法可以让我只偷看块知道它的编码而不丢失块和数据?

您可以对 return 流的内容和字符集建立承诺:

const charsetStream = (stream) => new Promise((resolve, reject) => {

  const detectCharacterEncoding = require('detect-character-encoding');
  let chunks = [];

  stream.on('data', (chunk) => {
    chunks.push(chunk);
  })

  stream.on('end', () => {
    chunks = Buffer.concat(chunks);
    resolve({
      content: chunks,
      charset: detectCharacterEncoding(chunks)
    })
  })

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

});

charsetStream(FileStream)
  .then(info => {
    console.log('content', info.content);
    console.log('charset', info.charset);
  })
  .catch(console.log);
  
  // You can use the FileStream outside the method but you can use it once !
  // this is completely different than the "stream" variable
  FileStream.on('data', (chunk) => {
    console.log('FileStream', chunk.toString());
  })