Last active
April 30, 2019 13:08
-
-
Save rationalthinker1/bfa5748f0becfaadefa12691cf5bc0d0 to your computer and use it in GitHub Desktop.
CSVReader for Typescript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import * as csv from 'fast-csv'; | |
import * as fs from 'fs'; | |
interface Row { | |
[s: string]: string; | |
} | |
type RowCallBack = (data: Row, index: number) => object; | |
export class CSVReader { | |
protected file: string; | |
protected csvOptions = { | |
delimiter: ',', | |
headers: true, | |
ignoreEmpty: true, | |
trim: true | |
}; | |
constructor(file: string, csvOptions = {}) { | |
if (!fs.existsSync(file)) { | |
throw new Error(`File ${file} not found.`); | |
} | |
this.file = file; | |
this.csvOptions = Object.assign({}, this.csvOptions, csvOptions); | |
} | |
public read(callback: RowCallBack): Promise < Array < object >> { | |
return new Promise < Array < object >> (resolve => { | |
const readStream = fs.createReadStream(this.file); | |
const results: Array < any > = []; | |
let index = 0; | |
const csvStream = csv.parse(this.csvOptions).on('data', async (data: Row) => { | |
index++; | |
results.push(await callback(data, index)); | |
}).on('error', (err: Error) => { | |
console.error(err.message); | |
throw err; | |
}).on('end', () => { | |
resolve(results); | |
}); | |
readStream.pipe(csvStream); | |
}); | |
} | |
} |
Author
rationalthinker1
commented
Apr 30, 2019
•
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment