开发者

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

开发者 https://www.devze.com 2023-03-18 10:06 出处:网络
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.

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 PD开发者_Go百科F file with my datas in the MongoDB, when someone requests.

Anyone, please give me some hints.

Thanks.


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.


you don't need fs, just stream your data from db in request handler

you can set file metadata using Content-Disposition header

Content-Type: image/jpeg
Content-Disposition: attachment; filename=genome.jpeg; 
  modification-date="Wed, 12 Feb 1997 16:29:51 -0500";
Content-Description: a complete map of the human genome
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号