Prompt a csv file to download as pop up using node.js and node-csv-parser (node module)


Question

Recently I have started working with node.js. While going through a requirement in one of my projects I am facing an issue where I should be able to write some data to a csv file dynamically and let it prompt as a popup to download for user (with save and cancel options - as we normally see). After googling for some time I decided to use csv npm module https://github.com/wdavidw/node-csv-parser. I am able to write data into a file and save it using this module. I want to prompt a popup for saving this file with/without saving the file.

my code looks something like this:

    // Sample Data 
    var data = [["id", "subject1", "subject2", "subject3"], ["jack", 85, 90, 68], ["sam", 77, 89, 69]]

    // Server Side Code    
    var csv = require('../../node_modules/csv');            
    var fs = require('fs');

    createCSV = function(data, callback) {
        csv().from(data).to(fs.createWriteStream('D:/test.csv')) // writing to a file           
    }

    // Client side call sample
    $("#exportToCSV").click(function() {
        callToServer.createCSV(data);
       return false;
    });

This is working good as far as writing the csv file is concerned.

  • I want to prompt this file immediately to download for users.
  • If this can be done without saving the file, that will be great.
  • How can I set content-type and content-disposition as we do in PHP

Any help is greatly appreciated. -Thanks

1
12
8/28/2013 6:09:44 PM

Accepted Answer

I did it something like this :

http.createServer(function(request, response) {
    response.setHeader('Content-disposition', 'attachment; filename=testing.csv');
    response.writeHead(200, {
        'Content-Type': 'text/csv'
    });

    csv().from(data).to(response)

})
.listen(3000);
15
11/8/2012 7:44:51 AM

Manish Kumar's answer is spot on - just wanted to include a Express 4 syntax variant to accomplish this:

function(req, res) {
  var csv = GET_CSV_DATA // Not including for example.

  res.setHeader('Content-disposition', 'attachment; filename=testing.csv');
  res.set('Content-Type', 'text/csv');
  res.status(200).send(csv);

}

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon