Search code examples
node.jszipzlib

How to download zip and directly extract zip via node?


I was wondering if it is possible to use https.get() from the Node standard library to download a zip and directly extract it into a subfolder.

I have found many solutions that download the zip first and extract it afterwards. But is there a way to do it directly?

This was my attempt:

const zlib = require("node:zlib");
const fs = require("fs");
const { pipeline } = require("node:stream");
const https = require("https");

const DOWNLOAD_URL =
  "https://downloadserver.com/data.zip";
const unzip = zlib.createUnzip();
const output = fs.createWriteStream("folderToExtract");

https.get(DOWNLOAD_URL, (res) => {
  pipeline(res, unzip, output, (error) => {
    if (error) console.log(error);
  });
});

But I get this error:

Error: incorrect header check
at Zlib.zlibOnError [as onerror] (node:zlib:189:17) {
errno: -3,
code: 'Z_DATA_ERROR'
}

I am curious, is this even possible?


Solution

  • Most unzippers start at the end of the zip file, reading the central directory there and using that to find the entries to unzip. This requires having the entire zip file accessible at the start.

    What you'd need is a streaming unzipper, which starts at the beginning of the zip file. You can try unzip-stream and see if it meets your needs.