简体   繁体   English

如何从Node JS服务器下载zip文件夹

[英]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.

相关问题 在下载时加密 zip 文件夹,然后用 Node.js 解密? - Encrypt zip folder on download and then decrypt with Node.js? 如何在Node JS应用程序中以及在zip下载开始后对文件夹进行zip压缩? - How to zip a folder in node js application & after zip downloading start? 如何将 Zip 文件从 s3 存储桶下载到 node.js lambda 函数中的本地目录 - How to download Zip File from an s3 bucket to a local directory within a node.js lambda function 如何压缩本地文件夹并下载? - how to zip local folder and download it? 如何在Node js中下载捆绑成一个zip文件的多个文件? - How to download multiple files bundled into one zip files in Node js? 如何使用 Node Js、Archiver 和 Express 正确下载 a.zip 文件 - How to properly download a .zip file using Node Js, Archiver and Express 从文件夹创建zip存档并使用Node.js保留结构 - Creating a zip archive from a folder and preserving structure with Node.js 如何从 stream 而不是磁盘 Node.js 复制和 zip 文件夹 - How to copy and zip folder from stream rather than disk- Node.js 如何在节点js中下载服务器文件? - how to download server file in node js? 如何通过JavaScript或Node.js强制从文件夹下载PDF到浏览器/用户? - How to force download PDF from folder to browser / user by JavaScript or Node.js?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM