HTML and CSS Reference
In-Depth Information
Now that we have an event handler that is capable of extracting the contents of the file as a
string, the next step is to break this down into an array of lines, this will allow us to process
the lines one at a time. We use the split method supported by JavaScript strings to split the
string each time it encounters a new line character. This returns an array of strings.
function loadFromCSV(event) {
var reader = new FileReader();
reader.onload = function(evt) {
var contents =;
var lines = contents.split('\n');
reader.onerror = function(evt) {
errorLogger('cannot_read_file', 'The file specified cannot be read');
Once we have an array of lines we need to break each line down into a set of tokens, each
of which we know is separated by a comma. This may sound relatively simple, for instance
the following implementation would meet most of our needs:
Unfortunately, CSV files can be more complex than the simple example we have used. For
instance, individual tokens may contain commas; therefore a CSV file can wrap a token
inside double quotes to ensure that these commas are treated literally rather than as token
Whenever you encounter a problem that looks common (such as parsing a line in a CSV
file) it is worth looking for libraries that have already been written. The authors of these
libraries will have thought about most issues that may arise, and any library with a large
number of users is likely to have been tested in a large number of scenarios, and therefore
should prove more stable.
In this scenario we will use this library:
Download the latest version and add it to the scripts folder of the application. I am using
version 0.71.
Search WWH ::

Custom Search