Created
September 4, 2023 13:43
-
-
Save c-jacquin/07ce3fc4d39f54473ebc8aa592319df2 to your computer and use it in GitHub Desktop.
parse csv
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
| export async function csvToJsonAsync(path: string) { | |
| const bottles: any[] = []; | |
| const readable = fs.createReadStream(path, { encoding: 'utf-8' }); | |
| const rl = readline.createInterface({ | |
| input: readable, | |
| output: process.stdout, | |
| }); | |
| let isFirstLine = true; | |
| let headers: string[]; | |
| for await (const line of rl) { | |
| if (isFirstLine) { | |
| headers = line.split(','); | |
| isFirstLine = false; | |
| } else { | |
| const rawBottle = line.split(','); | |
| const bottle = rawBottle.reduce((acc, value, index) => { | |
| const prop = headers ? headers[index] : 'default'; | |
| return Object.assign({ | |
| ...acc, | |
| [prop]: value, | |
| }); | |
| }, {} as any); | |
| bottle.name = bottle.name || 'unknown'; | |
| bottles.push(bottle); | |
| } | |
| } | |
| return bottles; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment