简体   繁体   English

管道响应流后没有数据

[英]No data after piping response stream

Using Electron's net module, the aim is to fetch a resource and, once the response is received, to pipe it to a writeable stream like so: 使用Electron的网络模块,目的是获取资源,并在收到响应后,将其传输到可写流,如下所示:

const stream = await fetchResource('someUrl');
stream.pipe(fs.createWriteStream('./someFilepath'));

As simplified implementation of fetchResource is as follows: 由于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();
  });
}

The response ends up being an instance of IncomingMessage, which implements a Readable Stream interface according to the node docs , so it should be able to be piped to a write stream. 响应最终成为IncomingMessage的一个实例,它根据节点文档实现可读流接口,因此它应该能够通过管道传输到写入流。

The primary issue is there ends up being no data in the stream that get's piped through 😕 主要问题是最终流没有数据通过pi传输

Answering my own question, but the issue is reading from multiple sources: the resolved promise and the 'data' event. 回答我自己的问题,但问题是从多个来源阅读:已解决的承诺和'data'事件。 The event listener source was flushing out all the data before the resolved promise could get to it. 事件监听器源在解析的promise可以到达之前刷新所有数据。

A solution is to fork the stream into a new one that won't compete with the original if more than once source tries to pipe from it. 一种解决方案是将流分叉为一个新流,如果不止一次源尝试从中进行管道传输,则不会与原始流竞争。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM