简体   繁体   English

如何在创建可读流之前返回对它的引用?

[英]How do I return a reference to a Readable stream before creating it?

I have a function that needs to return a Readable stream synchronously. 我有一个函数需要同步返回一个Readable流。 I have a function that creates a Readable stream with the data I require, but it's an asynchronous method. 我有一个函数,可以使用所需的数据创建一个Readable流,但这是一个异步方法。 How can I return a reference to the synchronous stream? 如何返回对同步流的引用?

class SomeStreamCreator {
    _requestStream() {
        fetchStream()
            .then(stream => /* stream is a Readable stream with data */)

        return /* somehow need to return the Readable stream here */
    }
}

Well it all depends on if you actually need the same exact stream object or just the same data. 好吧,这取决于您实际上是否需要相同的确切流对象或仅相同的数据。 In the first case as mentioned in comments it's more or less not possible. 如评论中提到的第一种情况,或多或少是不可能的。

If it's only the data you're after the situation is quite simple if you use a simple utility stream called PassThrough available in the built-in stream module: 如果仅使用数据,则使用内置stream模块中提供的称为PassThrough的简单实用程序流,情况就非常简单:

import {PassThrough} from "stream";

class SomeStreamCreator {
    _requestStream() {
        // first prepare an empty stream
        const out = new PassThrough();

        fetchStream() 
            // when the stream is ready pipe it to the empty one
            .then(stream => stream.pipe(out))
            // it's wise to add error handling
            .catch(error => stream.emit("error", e))

        // but immediately simply return the output
        return out;
    }
}

The output will receive all the data from the original stream and there's very little overhead so you don't need to worry about performance that much. 输出将接收原始流中的所有数据,并且开销很小,因此您不必担心性能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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