2

I am having problems downloading a zip file from the internet. I found countless of examples, but all return the same issue:

I work in NodeJS 12 LTS and Electron 10.

core.js:4197 ERROR Error [ERR_STREAM_CANNOT_PIPE]: Cannot pipe, not readable
    at ClientRequest.pipe (_http_outgoing.js:887)

The examples I found are e.g. this one here:

    import { request } from 'https';
    import * as fs from "fs";

    request("https://nodejs.org/dist/v12.18.4/node-v12.18.4-win-x86.zip")
      .pipe(fs.createWriteStream('/Users/foo/Desktop/bas.zip'))
      .on('close', function () {
        console.log('File written!');
      });

It couldn't be easier than that, but nonetheless, this fails. The order should be like this (here)

readable.pipe(writable);

This error message doesn't make any sense. What am I missing here?

Daniel Stephens
  • 2,371
  • 8
  • 34
  • 86

1 Answers1

12

Per the docs, https.request returns an instance of ClientRequest - a writable stream which you can pipe to in order to send files with your request. Trying to pipe from this writable stream into a file is the source of your error - you need a readable stream of the response instead.

To get the readable stream of the response, you should add a callback and pipe it from the response.

request("https://nodejs.org/dist/v12.18.4/node-v12.18.4-win-x86.zip", res => {
  res.pipe(fs.createWriteStream('/Users/foo/Desktop/bas.zip'))
     .on('close', function () {
       console.log('File written!');
     });
});

The native https api is not very friendly. What you originally wrote would have worked with the now-deprecated request module, and perhaps you got it from a code snippet using the very same. Nowadays, we should use an updated module like got. Here's an example:

import * as got from 'got';
import * as fs from "fs";

got.stream("https://nodejs.org/dist/v12.18.4/node-v12.18.4-win-x86.zip")
  .pipe(fs.createWriteStream('/Users/foo/Desktop/bas.zip'))
  .on('close', function () {
    console.log('File written!');
  });
Klaycon
  • 10,599
  • 18
  • 35
  • An absolutely underrated answer for a thumbs up and just an accept button. Thanks so much!! I just copied it and it works. Diving now into the details :-) – Daniel Stephens Sep 23 '20 at 22:09
  • @Daniel Glad it helped! Not that it's important, but I saw the accept checkmark for a few seconds and it vanished when I ninja-edited to add some details. Not sure what happened there! – Klaycon Sep 23 '20 at 22:14
  • Oh, true, fixed! :-) – Daniel Stephens Sep 23 '20 at 22:28