app.get('/download', function(req, res){
const file = `${__dirname}/upload-folder/dramaticpenguin.MOV`;
res.download(file); // Set disposition and send it.
});
Asked
Active
Viewed 36 times
1

Sebastian Kaczmarek
- 8,120
- 4
- 20
- 38

sgupta
- 21
- 2
-
2Does this answer your question? [How to download a file with Node.js (without using third-party libraries)?](https://stackoverflow.com/questions/11944932/how-to-download-a-file-with-node-js-without-using-third-party-libraries) – Sebastian Kaczmarek Sep 11 '20 at 06:28
-
@Sebastian Kaczmarek. No actually I want to provide a way to user to download file when he clicks at link in html page. this code downloads the file for me – sgupta Sep 11 '20 at 06:45
1 Answers
0
Here's a super simple example that should give you a start on how to implement this without express:
const http = require('http');
const fs = require('fs');
const path = require('path');
const httpServer = http.createServer(requestResponseHandler);
function requestResponseHandler(req, res) {
if (req.url === '/download') {
const file = `${__dirname}/sample-video.mov`;
res.writeHead(200, {
'Content-Type': 'video/quicktime',
'Content-Disposition': 'attachment; filename="sample.mov',
});
fs.createReadStream(file).pipe(res);
}
}
httpServer.listen(3000, () => {
console.log('server is listening on port 3000');
});
Basically all it does is to set the correct content-type
and content-disposition
headers and the create a read-stream from the mov
-file and pipe this stream into the response-object.

eol
- 23,236
- 5
- 46
- 64