How to export a CSV with correct charset in nodeJS
One of the most annoying thing I dealt with: how to export a CVS with correct charset in NodeJS, to show properly data containing unicode characters and that’s very often in apps with the Spanish language available.
I was trying several charsets, getting crazy because no one worked until I found this post. Thank God.
Yes, a CSV with correct charset in NodeJS
Install the text recoding module called Iconv:
npm install iconv
And the solution in my NodeJS controller using ExpressJS was something like this:
var Iconv = require("iconv").Iconv;
var iconv = new Iconv('utf8', 'utf16le');
function yourController(req, res) {
var rawData = [
{ name: 'David' },
{ name: 'Ángel' },
{ name: 'María' },
{ name: 'Núñez' }
];
var header = "#"+"\t"+"Name"+"\n";
var content = header;
for (var i=0, total=rawData.length; i<;total; i++) {
content += (i+1)+"\t"+rawData[i].name+"\n";
}
res.setHeader('Content-Type', 'application/vnd.openxmlformats');
res.setHeader("Content-Disposition", 'attachment; filename=itworks.xls');
res.write(new Buffer([0xff, 0xfe]));
res.write(iconv.convert(content));
res.end();
}
In this example, the controller serves automatically a CSV file (Excel compatible) with a header and a few rows containing Spanish names.
Note: To use the CSV file into Excel or similar tools, note that with \t
creates a column and \n
a new row.
Feel free to post a comment with your problem, suggestion or experience with it 🙂