Created
March 3, 2012 03:20
-
-
Save cpsubrian/1964096 to your computer and use it in GitHub Desktop.
Parsing a csv
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
numRead = 0 | |
numImported = 0 | |
doneReading = false | |
csv = require('csv')() | |
csv.fromPath result.filepath, {columns: true} | |
finish = () -> | |
process.stdout.write '\n' | |
log "" | |
log "Imported #{numImported} users".green | |
done() | |
csv.on 'error', (err) -> | |
log "Error parsing csv".red | |
log "#{err}".red | |
done() | |
csv.on 'data', (data) -> | |
numRead++ | |
if numRead > 100 then return | |
process.nextTick () -> | |
user = new app.models.User(data) | |
user.save (err) -> | |
numImported++ | |
process.stdout.write '.' | |
if doneReading and numImported >= numRead | |
finish() | |
csv.on 'end', (rows) -> | |
doneReading = true | |
if numImported >= numRead | |
finish() |
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 csv, doneReading, finish, numImported, numRead; | |
numRead = 0; | |
numImported = 0; | |
doneReading = false; | |
csv = require('csv')(); | |
csv.fromPath(result.filepath, { | |
columns: true | |
}); | |
finish = function() { | |
process.stdout.write('\n'); | |
log(""); | |
log(("Imported " + numImported + " users").green); | |
return done(); | |
}; | |
csv.on('error', function(err) { | |
log("Error parsing csv".red); | |
log(("" + err).red); | |
return done(); | |
}); | |
csv.on('data', function(data) { | |
numRead++; | |
if (numRead > 100) return; | |
return process.nextTick(function() { | |
var user; | |
user = new app.models.User(data); | |
return user.save(function(err) { | |
numImported++; | |
process.stdout.write('.'); | |
if (doneReading && numImported >= numRead) return finish(); | |
}); | |
}); | |
}); | |
csv.on('end', function(rows) { | |
doneReading = true; | |
if (numImported >= numRead) return finish(); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment