在node.js中压缩zip存档

msi*_*ora 45 zip node.js

我想创建一个zip存档并在node.js中解压缩它.我找不到任何节点实现.请帮忙.

Mat*_*rte 27

node-core内置了zip功能:http://nodejs.org/api/zlib.html

使用它们:

var zlib = require('zlib');
var gzip = zlib.createGzip();
var fs = require('fs');
var inp = fs.createReadStream('input.txt');
var out = fs.createWriteStream('input.txt.gz');

inp.pipe(gzip).pipe(out);
Run Code Online (Sandbox Code Playgroud)

  • 但它不是 .zip。我希望他们真的有一个内置于核心的 .zip 归档模块 (3认同)
  • @dopatraman [基本上gzip压缩文件整体而zip压缩每个文件](http://www.differencebetween.net/technology/difference-between-zip-and-gzip/).在不同的情况下,一个优先于另一个. (3认同)

Eli*_*oto 26

我最终这样做(我正在使用Express).我正在创建一个包含给定目录(SCRIPTS_PATH)上所有文件的ZIP.

我只是在Mac OS X Lion上测试了这个,但我想它在安装了Cygwin的Linux和Windows上运行得很好.

    var spawn = require('child_process').spawn;
    app.get('/scripts/archive', function(req, res) {
            // Options -r recursive -j ignore directory info - redirect to stdout
            var zip = spawn('zip', ['-rj', '-', SCRIPTS_PATH]);

            res.contentType('zip');

            // Keep writing stdout to res
            zip.stdout.on('data', function (data) {
                res.write(data);
            });

            zip.stderr.on('data', function (data) {
                // Uncomment to see the files being added
                //console.log('zip stderr: ' + data);
            });

            // End the response on zip exit
            zip.on('exit', function (code) {
                if(code !== 0) {
                    res.statusCode = 500;
                    console.log('zip process exited with code ' + code);
                    res.end();
                } else {
                    res.end();
                }
            });
        });
Run Code Online (Sandbox Code Playgroud)

  • 确认这适用于linux没有问题,节点0.4.9,已安装zip.感谢代码Eliseo,我打赌有时节省了我. (2认同)

小智 9

您可以尝试node-zip npm模块.

它将JSZip移植到节点,压缩/解压缩zip文件.


Rag*_*nar 6

你可以使用archiver模块,这对我很有帮助,这是一个例子:

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();
});
Run Code Online (Sandbox Code Playgroud)


tim*_*ley 0

如果您不想使用/学习库,您可以使用节点通过执行子进程来控制 zip 命令行工具

虽然我建议学习像 Emmerman 提到的那样的图书馆