簡體   English   中英

如何從Node JS服務器下載zip文件夾

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

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM