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