Last active
December 26, 2015 11:29
-
-
Save jhurliman/7143914 to your computer and use it in GitHub Desktop.
Asynchronously iterate over a CSV file one line at a time
This file contains hidden or 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
function readCSV(filename, eachCallback, doneCallback) { | |
var error; | |
var reader = require('readline').createInterface({ | |
input: require('fs').createReadStream(filename), | |
output: null, | |
terminal: false | |
}); | |
reader.on('line', function(line) { | |
if (!line) return; | |
var self = this; | |
this.pause(); | |
var parts; | |
if (line[0] === '"') { | |
line = line.substr(1, line.length - 2); | |
parts = line.split('","'); | |
} else { | |
parts = line.split(','); | |
} | |
// Unescape quotes | |
for (var i = 0; i < parts.length; i++) | |
parts[i] = parts[i].replace(/\\"/g, '"'); | |
eachCallback(parts, function(err) { | |
if (err) { | |
error = err; | |
return self.close(); | |
} | |
self.resume(); | |
}); | |
}); | |
reader.on('error', doneCallback); | |
reader.on('close', function() { | |
doneCallback(error); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment