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

Manish Kumar picture Manish Kumar · Oct 25, 2012 · Viewed 37.9k times · Source

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

Answer

joel.bowen picture joel.bowen · Nov 6, 2015

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);

}