I want to be able to allow an object to be download as a CSV file. I've converted the object into an suitable format for a CSV but I am having trouble with actually getting it to download. I have tried:
window.open("data:text/csv;charset=utf-8,"+ escape(csvObj));
but I keep getting window is not defined as an error and my work colleague told me it is a bad way of doing it.
this is what I have so far
'Export to CSV': function(msg, done){
var array = [
msg.data.title,
msg.data.description,
msg.data.objectives,
msg.data.outcome,
msg.data.hours
];
var str = '';
for(var i=0; i<array.length; i++){
var line = '';
for(var index in array[i]){
line += array[i][index]+',';
}
line.slice(0,line.length-1);
str += line+ '\r\n';
}
console.log('**************');
console.log(str);
var csvData="data:text/csv;charset=utf-8," + escape(str);
}
as it's part of a workflow it drops through to this function when the user selects the export to csv option so all I really want to do is download csvData now...any ideas on how to do this?
Here is a minimal example of how to serve textual data as a CSV file in Node.js:
// Load the HTTP module
var http = require('http');
// Create a server that will send some data as a CSV file
var server = http.createServer(function (request, response) {
// Send the appropriate HTTP headers
response.writeHead(200, {"Content-Type": "text/csv",
"Content-disposition": "attachment;filename=foobar.csv"});
// Send the actual data
response.end("Foo,42,xxx\nBar,43,yyy\nBaz,44,zzz");
});
// Listen on HTTP port 8000
server.listen(8000);
Note that text/csv
is the standard MIME-type for CSV file but if your clients use old version of Internet Explorer you may have to resort to non-standard MIME types such as application/vnd.ms-excel
. In your server function the user-agent string will be in request.headers['user-agent']
.