JavaScript Csv file generator, part 2 of 3
This is part 2 of the JavaScript Csv file generator series. If you haven't read the first part, here it is: JavaScript Csv file generator, part 1 of 3
Last week, I set up a few requirements and unit tests for my CSV file generator. Now it is time to start implementing.
First the constructor and the add method:
// Csv Implementation
function Csv(propertyOrder) {
this.propertyOrder = propertyOrder;
this.items = [];
}
Csv.prototype.add = function(item) {
this.items.push(item);
};
There. The first three unit tests are already passing. Next up is the first version of the getFileContents
method.
// getFileContents implementation
Csv.prototype.getFileContents = function(separator, includePropertyNames) {
var textLines = [];
// Add the auto-generated header
if (includePropertyNames) {
textLines.push(this.propertyOrder.join(separator));
}
// We step through every item in the items array
this.items.forEach(function(item) {
// We create one line of text using the propertyOrder
// First create an array of text representations
var values = [];
this.propertyOrder.forEach(function(name) {
values.push(item[name].toString());
});
// Then join the fields together
var lineOfText = values.join(separator);
textLines.push(lineOfText);
}).bind(this);
// Return the complete file
return textLines.join("\r\n");
};
The only thing left to do now is the saveAs
method. Since this requires a functioning window.saveAs
implementation to be available, the method is really simple.
// saveAs implementation
Csv.prototype.saveAs = function(filename, separator, includePropertyNames) {
var fileContents = this.getFileContents(separator, includePropertyNames);
// Create a blob, adding the Unicode BOM to the beginning of the file
var fileAsBlob = new Blob(["\ufeff", fileContents], {type:'text/csv'});
window.saveAs(fileAsBlob, filename);
};
There! It's done! The only thing left to do is some extra text escaping, but I leave that for next part.
The latest version of the code is always available in the GitHub repository.
Articles in this series: