File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff 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+
1848const writeToFile = ( path : string , data : unknown ) => {
1949 const parsedData = JSON . stringify ( data , null , 2 ) ;
2050 fs . writeFileSync ( path , parsedData , 'utf8' ) ;
You can’t perform that action at this time.
0 commit comments