unzip a zip file via fs in javascript

To unzip a zip file in JavaScript using the fs module, you can use the unzip and zlib modules. Here is an example:

const fs = require('fs');
const zlib = require('zlib');
const unzip = require('unzip');

const inputPath = 'path/to/zip/file.zip';
const outputPath = 'path/to/output/directory';

fs.createReadStream(inputPath)
  .pipe(zlib.createGunzip())
  .pipe(unzip.Extract({ path: outputPath }))
  .on('error', (err) => {
    console.error('Error unzipping file:', err);
  })
  .on('close', () => {
    console.log('File unzipped successfully!');
  });
441 chars
17 lines

In this example, we use fs.createReadStream to read the zip file, then pipe it to zlib.createGunzip to unzip it, and finally pipe it to unzip.Extract to extract the files to the specified output directory. The unzip.Extract method takes an options object with a path property specifying the output directory. We also handle errors and log a success message when the extraction is complete.

gistlibby LogSnag