1

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?

wzwd
  • 169
  • 2
  • 10
  • You don't zip any file yet, don't you ? – TGrif Sep 25 '18 at 17:29
  • @TGrif yes I didn't zip folder yet. I just want to download folder from node server. For this I think I should have to zip it first. But I don't know how to do it yet. I searched many times but I couldn't find useful things. Could you help me if you have done similar things before. – wzwd Sep 27 '18 at 01:52
  • @TGrif you don't have solution? – wzwd Sep 28 '18 at 06:12

1 Answers1

7

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.

TGrif
  • 5,725
  • 9
  • 31
  • 52