I'm trying to read a CSV file with node.js
using the csv-parser
library.
Since it's a big file, I need to check the header and the first 100
rows and the stop the method and return true
if everything is ok or false
if the data doesn't respect the condition.
How can I achieve this?
This is what I have so far:
const csv = require('csv-parser');
const fs = require('fs');
exports.checkFileFormat = (file) => {
let stream = fs.createReadStream(file.tempFilePath)
.pipe(csv())
.on('headers', (headers) => {
/*...some logic...*/
})
.on('data', (row) => {
if (!typeof (row["USAGE"]) == 'number'
|| !moment(row["START_DATE"], 'YYYYMMDD', true).isValid()
|| !moment(row["END_DATE"], 'YYYYMMDD', true).isValid()) {
stream.unpipe(csv());
return false;
}
})
.on('end', () => {
console.log('CSV file successfully processed');
});
return true;
}
In a previous version I had also declared: var num = 100
and tested it inside .on('data', (row) => {...}
but it didn't work.
Following up from my comment
make the function
checkFileFormat
return a promise. Inside the promise,resolve(false)
instead ofreturn false
andresolve(true)
in the'.on('end')
callback. I'm not completely sure this will work, but that's how I would approach it