gpt4 book ai didi

node.js - 将 NodeJS 流消耗到缓冲区并写入流的正确方法

转载 作者:行者123 更新时间:2023-12-02 02:52:37 24 4
gpt4 key购买 nike

我需要将可读流通过管道传输到缓冲区(要转换为字符串)和文件中。流来自 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())
})
)

是否需要第二种方法才能不丢失数据?第二种方法是否浪费,因为可以缓冲另外两个流?或者,是否有另一种方法可以同时填充缓冲区和写入流?

最佳答案

您不会错过任何数据,因为 .pipe内部电话src.on('data')并将任何块写入目标流。

所以任何写入您的 dest 的块流,也将被发射到 response.body.on('data')你在哪里缓冲块。
无论如何,您应该听听'error'事件并在发生任何错误时拒绝。

虽然您的第二种模式可以工作,但您不需要它。

这是来自 .pipe 的一段代码功能

  src.on('data', ondata);
function ondata(chunk) {
debug('ondata');
var ret = dest.write(chunk);
debug('dest.write', ret);
if (ret === false) {
// If the user unpiped during `dest.write()`, it is possible
// to get stuck in a permanently paused state if that write
// also returned false.
// => Check whether `dest` is still a piping destination.
if (((state.pipesCount === 1 && state.pipes === dest) ||
(state.pipesCount > 1 && state.pipes.indexOf(dest) !== -1)) &&
!cleanedUp) {
debug('false write response, pause', state.awaitDrain);
state.awaitDrain++;
}
src.pause();
}
}

关于node.js - 将 NodeJS 流消耗到缓冲区并写入流的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51371412/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com