1

I would like to send a file to a client using something like res.attachment() in sailsjs.

I do not want to store the file on the server at all, I simply want to generate it constantly and send it to the client.

For example, my controller looks like this

file: function(req, res, next) {
    var name = req.param('name');
    var data = 'Welcome Mr/Mrs ' + name


    res.attachment(data, 'fileName.txt')
    res.send()
},

Couple of problems

1) res.attachment does not seem to accept a file name as a parameter 2) the file that gets sent has the name "data" but there is no content in the file.

Is anyone aware of another function that can be used to do this? I don't require any formatting etc in the file, but it must be generated and sent back to the client with the api endpoint is called?

Ryan de Kock
  • 235
  • 2
  • 5
  • 12

1 Answers1

0

I found a way, by piping the data to res.attachment() I can overcome 1 & 2

var Readable = require('stream').Readable;

module.exports = {

file: function(req, res, next) {

    var s = new Readable();
    s._read = function noop() {}; // redundant? see update below
    s.push("your text here\r\n")
    s.push("next line text\r\n");
    // s.push(null);

    // res.attachment('test.csv');
    // -> response header will contain:
    //   Content-Disposition: attachment
    s.pipe(res.attachment('file.txt'))
    // res.download(data,'fileName.csv');
    res.send()
},
Ryan de Kock
  • 235
  • 2
  • 5
  • 12