Created
July 8, 2010 12:37
-
-
Save jamescarr/467954 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var fs = require('fs') | |
var sys = require('sys') | |
function parseCsvFile(fileName, callback){ | |
var stream = fs.createReadStream(fileName) | |
var iteration = 0, header = [], buffer = "" | |
var pattern = /(?:^|,)("(?:[^"]+)*"|[^,]*)/g | |
stream.addListener('data', function(data){ | |
buffer+=data.toString() | |
var parts = buffer.split('\r\n') | |
parts.forEach(function(d, i){ | |
if(i == parts.length-1) return | |
if(iteration++ == 0 && i == 0){ | |
header = d.split(pattern) | |
}else{ | |
callback(buildRecord(d)) | |
} | |
}) | |
buffer = parts[parts.length-1] | |
}) | |
function buildRecord(str){ | |
var record = {} | |
str.split(pattern).forEach(function(value, index){ | |
if(header[index] != '') | |
record[header[index].toLowerCase()] = value.replace(/"/g, '') | |
}) | |
return record | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment