3

I have an express/node app which exposes a GET end point via express router something like /api/user. The response is a JSON and i want to download the JSON to a file when i hit localhost:8080/api/user.

I tried with res.download but not sure how to handle the response data with it. This could be a duplicate question but i cannot find an example especially for this use case.

When the end point is invoked in browser it should prompt for download and then should get downloaded to the default location.

router.route('/user')
.get((req, res) => {
MyService.get().then((result) => { // the get method resolves a promise with the data
  // Prompt for download 
}).catch((err) => {
  console.log(err);

  res.status(500).json({
    status: 500,
    data: err
  });
});
});
Sai
  • 1,790
  • 5
  • 29
  • 51

4 Answers4

3

So i was able to do this in one of the 2 ways below,

router.route('/user')
    .get((req, res) => {
        MyService.get().then((result) => {
            res.attachment('users.csv');
            /*or you can use 
              res.setHeader('Content-disposition', 'attachment; filename=users.csv');
              res.set('Content-Type', 'text/csv');*/
            res.status(200).send(result);
        }).catch((err) => {
            console.log(err);
            res.status(500).json({
                status: 500,
                data: err
            });
        });
    });
Dmitry Yudakov
  • 15,364
  • 4
  • 49
  • 53
Sai
  • 1,790
  • 5
  • 29
  • 51
2

If I understand correctly, you want to save the sent data of /api/user to a file that you are sending in a route?

var fs = require('fs')

app.get("/api/user", function(req, res){

    var data = fromDb()
    fs.writeFileSync("/tmp/test", JSON.stringify(data))
    res.send(data)

})
Ozgur
  • 3,738
  • 17
  • 34
  • thank you for your response. All i need is just download the response to a file when i hit the /api/user end point – Sai Aug 30 '17 at 19:11
0

You need to write the JSON response to a file using the node filesystem module. You can check out an example here Writing files in Node.js

johnny_mac
  • 1,801
  • 3
  • 20
  • 48
0

If I got you right then You can try Content-Type and Content-disposition headers like below:

res.writeHead(200, {'Content-Type': 'application/force-download','Content-disposition':attachment; filename={your_file_name}.json});
res.end(data);

NOTE :

  • data in res.end(data) is your json data.

  • {your_file_name}.json is your actual file name , give it any name.

Lalit Goswami
  • 798
  • 1
  • 8
  • 21
  • thank you for your resposne. is there a way to do this natively using express.js? – Sai Aug 30 '17 at 19:12