Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save TomHumphries/7f5dcdb89644e4dd74be0dd6602e2921 to your computer and use it in GitHub Desktop.
Save TomHumphries/7f5dcdb89644e4dd74be0dd6602e2921 to your computer and use it in GitHub Desktop.
CSV to object array
async function ReadCSVFile(filepath) {
let lines = (await fs.promises.readFile(filepath))
.toString()
.split(/\r?\n/) // split into lines
.filter(x => x != ''); // remove empty lines
let items = [];
let header = lines.shift();
const headerCells = header.split(',');
for (let iL = 0; iL < lines.length; iL++) {
const cells = lines[iL].split(',');
const item = {};
for (let iH = 0; iH < headerCells.length; iH++) {
const prop = headerCells[iH];
const cell = cells[iH]
item[prop] = cell;
}
items.push(item)
}
return items;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment