从当前文件夹的Zip应用程序
我有node.js应用程序,我需要压缩所有当前的文件夹与命令从获得根压缩
为此,我想使用archiver npm包但我不明白以下内容:
- 在那里我把目前的文件夹(因为我想压缩所有的应用程序)
- 我应该在哪里放置zip的名称(执行命令时应该创build的zip)
我的应用程序有以下结构
MyApp Node_modules server.js app.js package.json arc.js
在arc.js
我已经把所有的压缩逻辑,所以我想我需要提供zipPath(在我的情况下是'./')和zip名称像myZip …
我尝试了以下没有成功,任何想法?
var fs = require('fs'); var archiver = require('archiver'); // create a file to stream archive data to. var output = fs.createWriteStream(__dirname + '/.'); var archive = archiver('zip', { zlib: { level: 9 } // Sets the compression level. }); // listen for all archive data to be written output.on('close', function() { console.log(archive.pointer() + ' total bytes'); console.log('archiver has been finalized and the output file descriptor has closed.'); }); archive.on('warning', function(err) { if (err.code === 'ENOENT') { // log warning } else { // throw error throw err; } }); // good practice to catch this error explicitly archive.on('error', function(err) { throw err; }); // pipe archive data to the file archive.pipe(output);
当我打开命令行时,我需要这个
folder->myApp->
运行zip arc,并将在当前path下创build压缩文件(这是本例中的根目录….)
您可以使用glob
方法,但一定要排除*.zip
文件。 否则,zip文件本身将成为存档的一部分。 这里是一个例子:
// require modules var fs = require('fs'); var archiver = require('archiver'); // create a file to stream archive data to. var output = fs.createWriteStream(__dirname + '/example.zip'); var archive = archiver('zip', { zlib: { level: 9 } // Sets the compression level. }); // listen for all archive data to be written output.on('close', function () { console.log(archive.pointer() + ' total bytes'); console.log('archiver has been finalized and the output file descriptor has closed.'); }); // good practice to catch warnings (ie stat failures and other non-blocking errors) archive.on('warning', function (err) { if (err.code === 'ENOENT') { // log warning } else { // throw error throw err; } }); // good practice to catch this error explicitly archive.on('error', function (err) { throw err; }); // pipe archive data to the file archive.pipe(output); archive.glob('**/*', { ignore: ['*.zip'] }); archive.finalize();
在node-archiver的github中有一个示例文件夹
在那里我把目前的文件夹(因为我想压缩所有的应用程序)
例如:
var file1 = __dirname + '/fixtures/file1.txt'; var file2 = __dirname + '/fixtures/file2.txt'; archive .append(fs.createReadStream(file1), { name: 'file1.txt' }) .append(fs.createReadStream(file2), { name: 'file2.txt' }) .finalize();
具体关于您的案例和目录,您可以使用归档器的.directory()方法
我应该在哪里放置zip的名称(执行命令时应该创build的zip)
例如:
var output = fs.createWriteStream(__dirname + '/example-output.zip');