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)
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)
你可以使用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)
| 归档时间: |
|
| 查看次数: |
45490 次 |
| 最近记录: |