How to zip a folder in node js application & after zip downloading start?

杀马特。学长 韩版系。学妹 提交于 2019-12-23 01:52:08

问题


I tried with npm package adm-zip 0.4.4 because the latest one 0.4.7 doesn't work, adm-zip 0.4.4 works on Windows but not on Mac & Linux. Another problem is that I only want zip_folder to be zipped but it zipps the whole directory structure staring from folder_1. This is the code:

var zip = new admZip();

zip.addLocalFolder("./folder_1/folder_2/folder_3/**zip_folder**");

zip.writeZip("./folder_1/folder_2/folder_3/download_folder/zip_folder.zip");

All this happens on the server side. I have searched a lot and tried many npm packages to zip a folder or directory. Any suggestions or any other good approach to solve my problem?


回答1:


You could also use node-archiver, which was very helpful when I was using it. First you need create an instance of the archiver as follows:

var fs = require('fs');
var archiver = require('archiver');

var archive = archiver.create('zip', {});
var output = fs.createWriteStream(__dirname + '/zip_folder.zip');

This way you tell the archiver to zip the files or folders based on the format you pass along with the method. In this case it's zip. In addition, we create a writeStream which will be piped to the archiver as its output. Also, we use the directory method to append a directory and its files, recursively, given its dirpath:

archive.pipe(output);

archive
  .directory(__dirname + '/folder_1/folder_2/folder_3/download_folder/zip_folder')
  .finalize();

At the end, we need to finalize the instance which prevents further appending to the archive structure.

Another option is to use the bulk method like so:

archive.bulk([{ 
  expand: true, cwd: './folder_1/folder_2/folder_3/download_folder/zip_folder/', 
  src: ['**/*'] 
}]).finalize();

Update 1

A little explanation for the [**/*] syntax: This will recursively include all folders ** and files *.




回答2:


Try to use the system's zip function:

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

    console.log('success');
});

Replace zipName and path with what you need.



来源:https://stackoverflow.com/questions/33364066/how-to-zip-a-folder-in-node-js-application-after-zip-downloading-start

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!