I want to import a CSV file and do some operation on it.
The following is the code I'm using and it is working fine:
return function (req, res) {
var rl = require('readline').createInterface({
input: fs.createReadStream(myFile.csv)
});
var lineNumber = 1;
rl.on('line', function (line) {
// Validate the first line
if (lineNumber === 1) {
if (firstLineIsInvalid()) {
res.send({
status: 'error',
message: 'This file deos not have a proper header'
});
rl.close();
}
lineNumber++;
return;
}
// Validate the 2nd line
if (isSecondLineInvalid()) {
res.send({
status: 'error',
message: '2nd line must be blank'
});
rl.close();
lineNumber++;
return;
}
// Skip 3rd line
if (lineNumber === 3) {
lineNumber++;
return;
}
// Skip the last line, we do not need aggregations
if (line.indexOf('Total') > -1) {
lineNumber++;
return;
}
// Start processing
processLine(line);
lineNumber++;
});
rl.on('close', function () {
if (!res.headersSent) {
fs.rename(myFile.csv, archivedFile.csv, function (err) {
if (err) {
res.send({status: 'error', message: 'Archiving failed, '+ JSON.stringify(err)});
} else {
res.send({status: 'ok'});
}
})
} else {
fs.rename(myFile.csv, rejectedFile.csv)
}
res.end();
});
}
But I am wondering if there is a better approach for:
- Counting the line numbers and validating the lines based on their position in the file.
- Reacting to the errors, especially those I get in the validation of the first and second lines.