简体   繁体   中英

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. 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM