node.js 中的 Zip 档案
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5754153/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Zip archives in node.js
提问by msikora
I want to create a zip archive and unzip it in node.js. I can't find any node implementation. Please help.
我想创建一个 zip 存档并将其解压缩到 node.js 中。我找不到任何节点实现。请帮忙。
回答by Eliseo Soto
I ended up doing it like this (I'm using Express). I'm creating a ZIP that contains all the files on a given directory (SCRIPTS_PATH).
我最终这样做了(我正在使用 Express)。我正在创建一个 ZIP,其中包含给定目录 (SCRIPTS_PATH) 上的所有文件。
I've only tested this on Mac OS X Lion, but I guess it'll work just fine on Linux and Windows with Cygwin installed.
我只在 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();
}
});
});
回答by MateodelNorte
node-core has built in zip features: http://nodejs.org/api/zlib.html
node-core 内置了 zip 功能:http: //nodejs.org/api/zlib.html
Use them:
使用它们:
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);
回答by daraosn
回答by Ragnar
You can use archivermodule, it was very helpful for me, here is an example:
你可以使用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();
});
回答by Todd Price
I've found it easiest to roll my own wrapper around 7-zip, but you could just as easily use zip or whatever command line zip tool is available in your runtime environment. This particular module just does one thing: zip a directory.
我发现在 7-zip 周围滚动我自己的包装器最容易,但您可以轻松地使用 zip 或运行时环境中可用的任何命令行 zip 工具。这个特定的模块只做一件事:压缩一个目录。
const { spawn } = require('child_process');
const path = require('path');
module.exports = (directory, zipfile, log) => {
return new Promise((resolve, reject) => {
if (!log) log = console;
try {
const zipArgs = ['a', zipfile, path.join(directory, '*')];
log.info('zip args', zipArgs);
const zipProcess = spawn('7z', zipArgs);
zipProcess.stdout.on('data', message => {
// received a message sent from the 7z process
log.info(message.toString());
});
// end the input stream and allow the process to exit
zipProcess.on('error', (err) => {
log.error('err contains: ' + err);
throw err;
});
zipProcess.on('close', (code) => {
log.info('The 7z exit code was: ' + code);
if (code != 0) throw '7zip exited with an error'; // throw and let the handler below log it
else {
log.info('7zip complete');
return resolve();
}
});
}
catch(err) {
return reject(err);
}
});
}
Use it like this, assuming you've saved the above code into zipdir.js. The third logparam is optional. Use it if you have a custom logger. Or delete my obnoxious log statements entirely.
像这样使用它,假设您已将上述代码保存到zipdir.js. 第三个log参数是可选的。如果您有自定义记录器,请使用它。或者完全删除我讨厌的日志语句。
const zipdir = require('./zipdir');
(async () => {
await zipdir('/path/to/my/directory', '/path/to/file.zip');
})();
回答by Elmer
回答by WaughWaugh
I have used 'archiver' for zipping files. Here is one of the Stackoverflow link which shows how to use it, Stackoverflow link for zipping files with archiver
我已经使用“存档器”来压缩文件。这是显示如何使用它的Stackoverflow 链接之一,用于使用存档器压缩文件的 Stackoverflow 链接
回答by Paul Beusterien
If you only need unzip, node-zipfilelooks to be less heavy-weight than node-archive. It definitely has a smaller learning curve.
如果您只需要解压缩,那么node-zipfile看起来没有node-archive 重。它的学习曲线肯定更小。
回答by timoxley
If you don't want to use/learn a library, you could use node to control the zip commandline tools by executing child processes
如果你不想使用/学习一个库,你可以使用 node 通过执行子进程来控制 zip 命令行工具
Though I'd recommend learning a library like the one mentioned by Emmerman
虽然我建议学习一个像 Emmerman 提到的图书馆
回答by Tomasz Janczuk
You can use the edge.jsmodule that supports interop between node.js and .NET in-process, and then call into .NET framework's ZipFile class which allows you to manipulate ZIP archives. Here is a complete example of creating a ZIP package using edge.js. Also check out the unzip example using edge.js.
您可以使用支持 node.js 和 .NET 进程内互操作的edge.js模块,然后调用 .NET 框架的 ZipFile 类,该类允许您操作 ZIP 档案。这是使用 edge.js 创建 ZIP 包的完整示例。还可以查看使用 edge.js的解压缩示例。

