Zip archives in node.js

前端 未结 10 1973
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-01 05:09

I want to create a zip archive and unzip it in node.js.

I can\'t find any node implementation.

10条回答
  •  粉色の甜心
    2020-12-01 05:33

    You can use archiver module, it was very helpful for me, here is an example:

    var Archiver = require('archiver'),
        fs = require('fs');
    app.get('download-zip-file', function(req, res){    
        var archive = Archiver('zip');
        archive.on('error', function(err) {
            res.status(500).send({error: err.message});
        });
        //on stream closed we can end the request
        res.on('close', function() {
            console.log('Archive wrote %d bytes', archive.pointer());
            return res.status(200).send('OK').end();
        });
        //set the archive name
        res.attachment('file-txt.zip');
        //this is the streaming magic
        archive.pipe(res);
        archive.append(fs.createReadStream('mydir/file.txt'), {name:'file.txt'});
        //you can add a directory using directory function
        //archive.directory(dirPath, false);
        archive.finalize();
    });
    

提交回复
热议问题