简体   繁体   中英

Hapi JS send file

I have the next task:

one request in my server wants to get a csv file with statistic. I have JSON structure. With module https://github.com/wdavidw/node-csv , I create a csv structure from my json. And the question is: how can I send it to user with correct mime type (text/csv)?

var arr = [["date,shop_id,product_id,count"]];
_.each(res, function(date) {
  _.each(date.unknown_products, function(count, product) {
    arr.push([date.date + ',' + id + ',' + product + ',' + count ]);
  });
});

csv()
  .from.array(arr)
  .to(function (data) {
    console.info(data); // => correct csv 
                                //  "date,shop_id,product_id,count"     
                                //  "2013-10-01,1,123,312"
    response += data;
  })
  .on('end', function (count) {
    console.log('Number of lines: ' + count); // => Number of lines: 33878

    //request.reply(new Hapi.response.Obj(response, 'text/csv'));
    request.reply(response);
  });

Ok, I find a solution using Hapi.response.Stream :

var stream = csv().from.array(arr, {
   columns: ["date", "shop_id", "product_id", "count"]
});


var response = new Hapi.response.Stream(stream);

response.type('text/csv');
request.reply(response);

maybe you can tell me the best way to realize it.

I believe at the time of asking this question, the API to return a file might not have been available. However, you can serve static files by using the following methods:

1- The file method on the reply interface.

reply.file('./path/to/file');

2- Directly specifying a file handler:

server.route({
    method: 'GET',
    path: '/picture.jpg',
    handler: {
        file: 'picture.jpg'
    }
});

Have a look at this Hapi tutorial for a detailed explanation.

You could use directory :) After hapi 9.x is no longer integrated with hapi, but you can require and use it.

Check http://hapijs.com/tutorials/serving-files#directory-handler for more information

use this

file="path/to/your/csvFile.csv"
return h.file(file,{mode:'attachment',type:'text/csv'})

Might help people looking to respond with a CSV file stream with Hapi V18.

const stringify = require('csv-stringify')

const stream = stringify(arrayOfObjects, { header: true })
return h.response(stream)
  .type('text/csv')
  .header('Connection', 'keep-alive')
  .header('Cache-Control', 'no-cache')
  .header('Content-Disposition', 'attachment;filename=myfilename.csv')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM