[英]How to download zip folder from node js server
我在一个文件夹中有文件,我想从节点js服务器下载文件夹。 我尝试了一些代码,但是没有用。 我得到了一些有关下载文件夹的示例(“ 下载文件夹” ,“ 如何压缩文件夹” ),但它们对我不起作用或我不理解。
I have folder like:
Allfilefolder
-file1.js
- file2.js
-file3.js
我可以使用以下方法下载每个文件:
app.get("/files/downloads", function(req,res){
const fs = require('fs');
var filepath = './Allfilefolder/file1.js';
res.download(filepath );
});
但是我不知道如何下载文件夹。 有什么帮助吗?
假设您已经安装了一个zip软件并且可以从您的应用程序访问它,一种实现方法是使用Node.js child_process ,这种方式甚至不必使用外部库。
这是一个基本示例,其灵感来自于此简洁有效的答案:
// 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');
});
您还可以查看npm 存储库中的软件包,这些软件包将更可靠地处理文件或目录。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.