Node.js: how to download and extract a ZIP file

Node.js: how to download and extract a ZIP file

Downloading a file via HTTP and decompressing it is a common operation in Node.js programming. In this article, we'll walk you through the steps required to download a ZIP file via HTTP and decompress it using Node.js.<

Downloading a file via HTTP and decompressing it is a common operation in Node.js programming. In this article, we'll walk you through the steps required to download a ZIP file via HTTP and decompress it using Node.js.

The first step is to download the file via HTTP. To do this, we will use the Node.js https module. We will use the get() method of this module to get the file from the server.


'use strict';

const https = require('https');
const fs = require('fs');

const fileUrl = 'https://example.com/myfile.zip';
const fileName = 'myfile.zip';

const file = fs.createWriteStream(fileName);

https.get(fileUrl, response => {
  response.pipe(file);

  file.on('finish', () => {
    file.close();
  });
}).on('error', error => {
  fs.unlink(fileName);
});

In this example, we are downloading the ZIP file from the URL https://example.com/myfile.zip and saving the file as myfile.zip. The get() method calls a function callback with the server's response, which is then sent to the pipe() method for writing the file. When the file has been completely written, the finish event is invoked.

After downloading the file, we can unzip it using the adm-zip module. This module offers a simple interface for manipulating ZIP files in Node.js.


const AdmZip = require('adm-zip');

const zip = new AdmZip('myfile.zip');
zip.extractAllTo('./extractdir', true);

In this example, we are using the adm-zip module to create an instance of the AdmZip class and unzip the ZIP file. The extractAllTo() method takes it as the first parameter the destination path where the files will be extracted, while the second parameter indicates whether existing files should be overwritten.

In conclusion, downloading a file via HTTP and decompressing it with Node.js is a relatively simple operation. Using the https and adm-zip modules, we can download and unzip files in just a few lines of code.