I cannot read a stream using Promise in Node

I have the following scenario:

getStream returns a stream from request

And I want to pass the stream to downloadImage, however I encounter an issue: fulfilling the promise in the 'downloadImage' it doesn't result a stream as I would have expected.

class ImageDownloader {

    private async getStream(imageUrl){
        const result = request(imageUrl);
        // result.pipe(fs.createWriteStream('./image.jpg')); //it is a stream and it works to write it in a file
        return result;
    }

    public async downloadImage(imageUrl) {
        const imageStream = await getStream(imageUrl);
        // imageStream.pipe(fs.createWriteStream('./image.jpg')); 
        //I receive the following error: "imageStream.pipe is not a function"

    }

}

How can I pass my stream asynchronously using Promises? What am I doing wrong?

Note: I simplified the methods for this example

Thank you in advance

1 answer

  • answered 2020-02-12 23:23 Jake Holzinger

    It's not clear why you are marking getStream as async when you do not use await inside the method. You also need to use this when calling class methods (e.g. this.getStream(...)).

    It looks like you're trying to write a method that downloads an image (using the stream API) and returns a promise, this is how I would do it:

    class ImageDownloader {
        private getStream(imageUrl) {
            return request.get(imageUrl);
        }
    
        public downloadImage(imageUrl) {
            return new Promise((resolve, reject) => {
                this.getStream(imageUrl)
                    .pipe(fs.createWriteStream('./image.jpg'))
                    .on('finish', resolve)
                    .on('error', reject);
            });
        }
    }
    

    And then you can consume it:

    const downloader = new ImageDownloader();
    await downloader.downloadImage('http://host.com/image.jpg');
    

    This answer assumes you're using the request module.