[英]How to download zip folder from node js server
I have files inside one folder and i want to download the folder form node js server. 我在一个文件夹中有文件,我想从节点js服务器下载文件夹。 I try some code but it doesn't work.
我尝试了一些代码,但是没有用。 I get some examples about downloading ( Downloading folder , How to zip folder )folder but they doesn't work for me or i did't understand them.
我得到了一些有关下载文件夹的示例(“ 下载文件夹” ,“ 如何压缩文件夹” ),但它们对我不起作用或我不理解。
I have folder like:
Allfilefolder
-file1.js
- file2.js
-file3.js
I can download each file using: 我可以使用以下方法下载每个文件:
app.get("/files/downloads", function(req,res){
const fs = require('fs');
var filepath = './Allfilefolder/file1.js';
res.download(filepath );
});
But i don't know how to download the folder. 但是我不知道如何下载文件夹。 any help please?
有什么帮助吗?
Assuming you already have a zip software installed and accessible from your app, one way to do it is to use Node.js child_process , this way you don't even have to use an external library. 假设您已经安装了一个zip软件并且可以从您的应用程序访问它,一种实现方法是使用Node.js child_process ,这种方式甚至不必使用外部库。
Here is a basic example, inspired by this concise and effective answer: 这是一个基本示例,其灵感来自于此简洁有效的答案:
// requiring child_process native module
const child_process = require('child_process');
const folderpath = './Allfilefolder';
app.get("/files/downloads", (req, res) => {
// we want to use a sync exec to prevent returning response
// before the end of the compression process
child_process.execSync(`zip -r archive *`, {
cwd: folderpath
});
// zip archive of your folder is ready to download
res.download(folderpath + '/archive.zip');
});
You could also have a look at the npm repository for packages that will handle archiving file or directory more robustly. 您还可以查看npm 存储库中的软件包,这些软件包将更可靠地处理文件或目录。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.