-
Notifications
You must be signed in to change notification settings - Fork 0
/
DataReader.js
44 lines (39 loc) · 1.01 KB
/
DataReader.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
/**
* Data reader for CSV files.
*/
const fs = require("fs");
const { parse } = require("csv-parse");
const { finished } = require("stream/promises");
/**
* Reads data from a CSV file.
* @param {string} filePath The path to the CSV file.
* @returns {Promise<Array<Object>>} A promise that resolves with an array of data objects.
*/
async function readData(filePath) {
const records = [];
const parser = fs.createReadStream(filePath).pipe(
parse({
columns: true,
skip_empty_lines: true,
trim: true,
autoParse: true,
header: true,
// Customize error handling to log and skip problematic lines
error: (err, row, rowIndex) => {
console.error(`Error at line ${rowIndex + 1}:`, err);
console.error("Problematic row:", row);
},
})
);
parser.on("readable", function () {
let record;
while ((record = parser.read()) !== null) {
records.push(record);
}
});
await finished(parser);
return records;
}
module.exports = {
readData,
};