我需要将可读流通过管道传输到缓冲区(要转换为字符串)和文件中。流来自node-fetch
.
NodeJS 流有两种状态:暂停和流动。据我了解,一旦'data'
附加了侦听器,流就会变为流动模式。我想确保我读取流的方式不会丢失任何字节。
方法1:管道和读取'data'
:
fetch(url).then(
response =>
new Promise(resolve => {
const buffers = []
const dest = fs.createWriteStream(filename)
response.body.pipe(dest)
response.body.on('data', chunk => buffers.push(chunk))
dest.on('close', () => resolve(Buffer.concat(buffers).toString())
})
)
方法2:使用直通流:
const { PassThrough } = require('stream')
fetch(url).then(
response =>
new Promise(resolve => {
const buffers = []
const dest = fs.createWriteStream(filename)
const forFile = new PassThrough()
const forBuffer = new PassThrough()
response.body.pipe(forFile).pipe(dest)
response.body.pipe(forBuffer)
forBuffer.on('data', chunk => buffers.push(chunk))
dest.on('close', () => resolve(Buffer.concat(buffers).toString())
})
)
是否需要第二种方法以免丢失数据?第二种方法是否浪费,因为可以缓冲另外两个流?或者,是否有另一种方法可以同时填充缓冲区和写入流?