Chris Paterson
Chris Paterson

Reputation: 193

How can I cause a newly created .csv file to be downloaded to the user?

I have created a button on my website, that when clicked will create a .csv file. What I want is for this file to be downloaded to the user immediately after the file has been created. Here is what I have so far:

var data = ...; // stuff
var fields = ...; // stuff
json2csv({ data: data, fields: fields }, function(err, csv) {
    if (err) {
        console.log(err);
    }

    fs.writeFile('test.csv', csv, function(err) {
        if (err) throw err;
       console.log('file saved');
       // now, download this file to the user. How?
    });
});

The .csv file is created, but I want the file to then be immediately downloaded to the user. Ideally, the .csv file would be streamed directly to the user without it ever being saved on my server, but I'm not sure how to do this. Any help would be much appreciated.

Upvotes: 1

Views: 1059

Answers (2)

victorkt
victorkt

Reputation: 14572

If you are using express, you can use sendFile. Assuming your code has access to the response object, you can send the file like this:

var data = ...; // stuff
var fields = ...; // stuff
json2csv({ data: data, fields: fields }, function(err, csv) {
    if (err) {
        console.log(err);
    }

    fs.writeFile('test.csv', csv, function(err) {
        if (err) throw err;
        console.log('file saved');

        var options = {
            root: __dirname
        };

        res.sendFile('test.csv', options, function (err) {
            if (err) {
                console.log(err);
                res.status(err.status).end();
            }
            else {
                console.log('Sent:', fileName);
            }
        });
    });
});

As for sending the file without saving it to your server, you can do that setting the Content-Disposition header:

var data = ...; // stuff
var fields = ...; // stuff
json2csv({ data: data, fields: fields }, function(err, csv) {
    if (err) {
        console.log(err);
    }

    res.set({
        'Content-Disposition': 'attachment; filename=test.csv',
        'Content-Type': 'text/csv'
    });
    res.send(csv);
});

Upvotes: 1

boxmein
boxmein

Reputation: 875

You can construct a HTTP response with the appropriate file type and send it if you are not using Express:

res.writeHead(200, {
  'Content-Type': 'text/csv'
});

res.write(csv); // or csv.pipe(res) if csv is a readable stream
res.end();

Upvotes: 0

Related Questions