Reputation: 169
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?
Upvotes: 1
Views: 9977
Reputation: 5941
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.
Upvotes: 8