Skip to content

Instantly share code, notes, and snippets.

@c-jacquin
Created September 4, 2023 13:43
Show Gist options
  • Select an option

  • Save c-jacquin/07ce3fc4d39f54473ebc8aa592319df2 to your computer and use it in GitHub Desktop.

Select an option

Save c-jacquin/07ce3fc4d39f54473ebc8aa592319df2 to your computer and use it in GitHub Desktop.
parse csv
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