How do you use got node module with node createWriteStream to download an image with electron?

I have looked at a couple of other answers, but they did not help me.

node version 16.8.0 windows 10 “got”: “11.8.2”, electron 14.0.0

Here is what I am trying. The code below does download the file but createWriteStream throws error —

Uncaught (in promise) TypeError [ERR_INVALID_RETURN_VALUE]: Expected AsyncIterable or Promise to be returned from the “destination” function but got type undefined.

Code in my render file

module.exports.getTile = async function (url, outputFilePath) {
    const pipeline = promisify(stream.pipeline);

    await pipeline(
        got.stream(url),
        fs.createWriteStream(outputFilePath),
        (err) => {
            if (err) {
                console.error('Pipeline failed', err);
            } else {
                console.log('Pipeline succeeded');
            }
        });


    stream.finished(input, (err) => {
        if (err) {
            console.error('Stream failed', err);
        } else {
            console.log('Stream is done reading');
        }
    });
};

I call the function with await getTile(url, tilePath);

Answer

stream.pipeline(...streams, callback) accepts n stream middlewares and a final callback argument as per documentation.

util.promisify(...args, callback) accepts a function with an error-first callback and wraps it into an async function that throw on errors. (docs)

When the two are combined, util.promisify will consume the final callback argument in stream.pipeline, and return an async function that only accept stream middlewares: util.promisify(stream.pipeline)(...streams).

Consequently, the following snippet

await pipeline(
        got.stream(url),
        fs.createWriteStream(outputFilePath),
        (err) => {
            if (err) {
                console.error('Pipeline failed', err);
            } else {
                console.log('Pipeline succeeded');
            }
        });

Should be rewritten as:

try {
  await pipeline(
    got.stream(url),
    fs.createWriteStream(outputFilePath)
  )
  console.log('Pipeline succeeded');
}
catch( error ){
  console.error('Pipeline failed', err);
}