[英]No data after piping response stream
使用Electron的網絡模塊,目的是獲取資源,並在收到響應后,將其傳輸到可寫流,如下所示:
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的一個實例,它根據節點文檔實現可讀流接口,因此它應該能夠通過管道傳輸到寫入流。
主要問題是最終流中沒有數據通過pi傳輸
回答我自己的問題,但問題是從多個來源閱讀:已解決的承諾和'data'
事件。 事件監聽器源在解析的promise可以到達之前刷新所有數據。
一種解決方案是將流分叉為一個新流,如果不止一次源嘗試從中進行管道傳輸,則不會與原始流競爭。
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
// ...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.