如何在Node JS应用程序和文件夹中压缩文件夹zip下载开始后? [英] How to zip a folder in node js application & after zip downloading start?

查看:307
本文介绍了如何在Node JS应用程序和文件夹中压缩文件夹zip下载开始后?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用npm软件包adm-zip 0.4.4,因为最新的0.4.7不起作用,adm-zip 0.4.4在Windows上有效,但在Mac& Linux.另一个问题是,我只希望压缩zip_folder,但是它压缩了从folder_1开始的整个目录结构.这是代码:

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");

所有这些都发生在服务器端.我已经搜索了很多,并尝试了许多npm软件包来压缩文件夹或目录.有什么建议或其他解决我问题的好方法吗?

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?

推荐答案

您还可以使用 node-archiver ,这在我使用它时非常有帮助.首先,您需要create archiver的实例,如下所示:

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');

通过这种方式,您可以告诉archiver根据您传递的方法压缩文件或文件夹的格式.在这种情况下,它是zip.另外,我们创建一个writeStream,将其通过管道传输到archiver作为其输出.同样,我们使用directory方法递归地添加目录及其文件,并赋予它dirpath:

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();

最后,我们需要finalize该实例,以防止进一步追加到存档结构中.

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

另一种选择是使用bulk方法,如下所示:

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();

更新1

[**/*] syntax的一些解释:它将递归包括所有文件夹**和文件*.

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

这篇关于如何在Node JS应用程序和文件夹中压缩文件夹zip下载开始后?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆