Skip to content

Commit afeaf49

Browse files
committed
OBPIH-6969 Add util for reading csv files
1 parent 5c2543a commit afeaf49

1 file changed

Lines changed: 30 additions & 0 deletions

File tree

src/utils/FileIOUtils.ts

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,36 @@ const readFile = (path: string) => {
1515
}
1616
};
1717

18+
export const readCsvFile = (path: string): Record<string, string>[] => {
19+
try {
20+
const rawdata = fs.readFileSync(path, 'utf8');
21+
const lines = rawdata.trim().split('\n');
22+
23+
if (!lines.length) {
24+
return [];
25+
}
26+
27+
const headers = lines[0].split(',');
28+
return lines.slice(1).map(line => {
29+
const values = line.split(',');
30+
const obj: Record<string, string> = {};
31+
headers.forEach((header, i) => {
32+
obj[header.trim()] = values[i]?.trim() ?? '';
33+
});
34+
35+
return obj;
36+
});
37+
} catch (error) {
38+
if (
39+
error instanceof Error &&
40+
(error as NodeJS.ErrnoException).code === 'ENOENT'
41+
) {
42+
return [];
43+
}
44+
throw error;
45+
}
46+
};
47+
1848
const writeToFile = (path: string, data: unknown) => {
1949
const parsedData = JSON.stringify(data, null, 2);
2050
fs.writeFileSync(path, parsedData, 'utf8');

0 commit comments

Comments
 (0)