从一个文件夹创build一个zip档案并用Node.js保存结构

我试图使用Node.js从现有的文件夹创build一个zip文件,并保留该结构。

我希望能有一个简单的模块来允许这样的事情:

archiver.create("../folder", function(zipFile){ console.log('et viola'); }); 

但我找不到这样的东西!

我一直在googlesearch,到目前为止我发现的最好的是zipstream,但据我所知,没有办法做我想要的。 我真的不想打入命令行工具,因为应用程序必须是跨平台的。

任何帮助将不胜感激。

谢谢。

它不完全没有代码,但是可以使用node-native-zip和folder.js 。 用法:

 function zipUpAFolder (dir, callback) { var archive = new zip(); // map all files in the approot thru this function folder.mapAllFiles(dir, function (path, stats, callback) { // prepare for the .addFiles function callback({ name: path.replace(dir, "").substr(1), path: path }); }, function (err, data) { if (err) return callback(err); // add the files to the zip archive.addFiles(data, function (err) { if (err) return callback(err); // write the zip file fs.writeFile(dir + ".zip", archive.toBuffer(), function (err) { if (err) return callback(err); callback(null, dir + ".zip"); }); }); }); } 

这可以使用节点的内置execfile函数更简单的完成。 它产生一个进程,并通过os本地执行zip命令。 一切正常。

 var execFile = require('child_process').execFile; execFile('zip', ['-r', '-j', zipName, pathToFolder], function(err, stdout) { console.log(err); logZipFile(localPath); }); 

如果你正在压缩一个sibdirectory,并且不希望在zip文件中有过多的嵌套,-j标志'junks'文件path。

这里是关于execfile的一些文档 。 这是一个zip的手册页 。

使用Easy-zip , npm install easy-zip ,你可以这样做:

 var zip5 = new EasyZip(); zip5.zipFolder('../easy-zip',function(){ zip5.writeToFile('folderall.zip'); });