Search code examples
javascriptnode.jsexpresszipunzip

Extract zip file to local folder


I have node app with express and im sending request from client like postman and I need to get the file from the req and extract it on my local folder,how I can do that ?

I found the following open source but not sure how to take the req body and extract it in my local folder like "C://Test//extractDest",

The code below is taken from the following open source but if there is other good open source for this I can use it instead https://www.npmjs.com/package/decompress-zip

var DecompressZip = require('decompress-zip');
var unzipper = new DecompressZip(filename)

unzipper.on('error', function (err) {
    console.log('Caught an error');
});

unzipper.on('extract', function (log) {
    console.log('Finished extracting');
});

unzipper.on('progress', function (fileIndex, fileCount) {
    console.log('Extracted file ' + (fileIndex + 1) + ' of ' + fileCount);
});

unzipper.extract({
    path: "C://Test//extractDest",
    filter: function (file) {
        return file.type !== "SymbolicLink";
    }
});

This is how I send the zip file I simply select binary and choose a zip file

enter image description here


Solution

  • I'd recommend you using multer which works with multipart/form-data content-type.

    Here's a basic working example. It assumes we are only uploading a single file, a folder named "uploads" exists at the root of your project and a form field named "singleFileUpload" to hold your data. You can change all those following the multer documentation:

    var path     = require("path");
    var express  = require("express");
    var multer   = require("multer");
    var Unzipper = require("decompress-zip");
    
    
    var app = express();
    
    app.use(multer({dest:'./uploads/'}).single('singleFileUpload'));
    
    
    app.post("/", function(req, res){
    
        if (req.file){
    
            var filepath = path.join(req.file.destination, req.file.filename);
            var unzipper = new Unzipper(filepath);
    
            unzipper.on("extract", function () {
                console.log("Finished extracting");
            });
    
            unzipper.extract({ path: "C://Test//extractDest"});
        }
    
        res.status(204).end();
    });
    
    
    app.listen(3000);
    

    Using postman you can now upload and decompress files with this configuration:

    enter image description here