Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement a file download with Node.js's fs module and express

Because the file should be generated dynamically, maybe I should use the fs modules's writeStream. But I couldn't find any example codes with my poor googling. Sorry.

More specifically, I want to give a CSV file or a PDF file with my datas in the MongoDB, when someone requests.

Anyone, please give me some hints.

Thanks.

like image 809
Whiteship Avatar asked Jul 07 '11 11:07

Whiteship


People also ask

How do I write and download a file in node JS?

Downloading a file using node js can be done using inbuilt packages or with third party libraries. GET method is used on HTTPS to fetch the file which is to be downloaded. createWriteStream() is a method that is used to create a writable stream and receives only one argument, the location where the file is to be saved.

How do I download a file from node js server?

var path = require('path'); var mime = require('mime'); var fs = require('fs'); app. get('/download', function(req, res){ var file = __dirname + '/upload-folder/dramaticpenguin. MOV'; var filename = path. basename(file); var mimetype = mime.


1 Answers

With the express, I can implement like this.

app.get('/down2', function(req, res){
  var filename = 'data.csv';
  res.attachment(filename);
  res.end('hello,world\nkeesun,hi', 'UTF-8'); //Actually, the data will be loaded form db.
});

How simple is it. Thanks.

like image 105
Whiteship Avatar answered Oct 22 '22 16:10

Whiteship