and*_*ais 6 stream node.js node-fetch
我需要将可读流通过管道传输到缓冲区(要转换为字符串)和文件中。流来自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())
})
)
Run Code Online (Sandbox Code Playgroud)
方法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())
})
)
Run Code Online (Sandbox Code Playgroud)
是否需要第二种方法才能不丢失数据?第二种方法是否浪费,因为可以缓冲另外两个流?或者,是否有另一种方法可以同时填充缓冲区和写入流?
您不会错过任何数据,因为.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();
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
15646 次 |
| 最近记录: |