Skip to content

Instantly share code, notes, and snippets.

@jhurliman
Last active December 26, 2015 11:29
Show Gist options
  • Save jhurliman/7143914 to your computer and use it in GitHub Desktop.
Save jhurliman/7143914 to your computer and use it in GitHub Desktop.
Asynchronously iterate over a CSV file one line at a time
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