Hapi: Hapi file download does not work as expected

Created on 30 Sep 2015  Â·  5Comments  Â·  Source: hapijs/hapi

Im using hapi 6.5.1 and trying to send csv file to client, on client Im using Angular. but the following code does not work.

function sendCsvFile(data,reply) {

  var filePath = __dirname + '/reports.csv';
  var file = fs.openSync(filePath,'w');

  fs.writeFile(filePath, data,function(err) {

    if(err) {
      reply('Cannot parse csv data');
      return;
    }

    fs.readFile(filePath, function(error, content) {

      if(err) {
        reply('Cannot get csv file');
        return;
      }

      reply.file(filePath)
         .header('Content-Type', 'text/csv')
         .header("Content-Disposition", "attachment; filename=" + 'reports.csv');  

    });

  })

}

What Im doing wrong
non issue

All 5 comments

1st, we don't support hapi 6.x anymore.
2nd, why do you even need to write on a file if you already have the data ?

Can you clarify "does not work"? What does happen...an error, nothing?

As @Marsup mentioned there's no need to write to a file if you already have the data to send. You also don't need to use reply.file. Your code could be simplified down to :

function sendCsvFile (data, reply) {

    reply(data)
        .header('Content-Type', 'text/csv')
        .header('Content-Disposition', 'attachment; filename=reports.csv');
}

@mtharrison let me try what you suggested. Actually Im getting json data on client side, but the file does not download.

@mtharrison according to you

var filePath = __dirname + '/upload-folder/dramaticpenguin.MOV';
  var file = fs.openSync(filePath);
    fs.readFile(filePath, function(err, content) {

      if(err) {
        reply('Cannot get csv file');
      }

      reply(content)
         .header('Content-Type', 'text/csv')
         .header("Content-Disposition", "attachment; filename=" + 'reports.csv');  

    });

This should work, But its not working.
In "express" there is a function

var file = __dirname + '/upload-folder/dramaticpenguin.MOV';
  res.download(file);

is there anything in hapi like this?

Look at the inert module, it provides many ways to do this.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

arb picture arb  Â·  4Comments

DrMabuse23 picture DrMabuse23  Â·  5Comments

AdriVanHoudt picture AdriVanHoudt  Â·  5Comments

hovmand picture hovmand  Â·  3Comments

andkazakov picture andkazakov  Â·  5Comments