Search code examples
node.jszip

How can I upload a zip file using nodejs and extract it?


I want to upload a zip file into the server using node.So can any one help me to figure it out.


Solution

  • First upload your zip file using Multer:

    var storage = multer.diskStorage({
      destination: function (req, file, cb) {
        cb(null, '/tmp/my-uploads')
      },
      filename: function (req, file, cb) {
        cb(null, file.fieldname + '-' + Date.now())
      }
    })
    
    var upload = multer({ storage: storage })
    

    Then unzip it using unzipper module:

    1) Install unzipper module

    npm i unzipper
    

    2) ExtractZip.js JavaScript

    const unzipper = require('./unzip');
    var fs = require('fs');
    
    
    fs.createReadStream('path/to/archive.zip')
      .pipe(unzipper.Parse())
      .on('entry', function (entry) {
        const fileName = entry.path;
        const type = entry.type; // 'Directory' or 'File'
        const size = entry.vars.uncompressedSize; // There is also compressedSize;
        if (fileName === "this IS the file I'm looking for") {
          entry.pipe(fs.createWriteStream('output/path'));
        } else {
          entry.autodrain();
        }
      });
    

    // Source

    Test:

    c:\Samim>node ExtractZip.js