使用Electron的net模块,目的是获取资源,并在收到响应后将其通过管道传输到可写流,如下所示:
const stream = await fetchResource('someUrl');
stream.pipe(fs.createWriteStream('./someFilepath'));
fetchResource
的简化实现如下:
import { net } from 'electron';
async function fetchResource(url) {
return new Promise((resolve, reject) => {
const data = [];
const request = net.request(url);
request.on('response', response => {
response.on('data', chunk => {
data.push(chunk);
});
response.on('end', () => {
// Maybe do some other stuff with data...
});
// Return the response to then pipe...
resolve(response);
});
request.end();
});
}
响应最终是IncomingMessage的一个实例,该实例根据节点docs实现了Readable Stream接口,因此应该可以将其通过管道传递给写流。
主要问题是最终导致流中没有数据
答案 0 :(得分:0)
正在回答我自己的问题,但问题是从多个来源读取的:已解决的诺言和'data'
事件。事件侦听器源正在清除所有数据,直到已解决的承诺得以实现。
一种解决方案是将流分叉到新的流中,如果源试图从中流过不止一次,则该流将不与原始流竞争。
import stream from 'stream';
// ...make a request and get a response stream, then fork the stream...
const streamToResolve = response.pipe(new stream.PassThrough());
// Listen to events on response and pipe from it
// ...
// Resolve streamToResolve and separately pipe from it
// ...