CSVParse for Node.js

IssuesGitHub

Async iterator

Async iterators provides an elegant method to iterate over each parsed records with the usage of the for await...of construct.

CSV parse rely on and leverages the Node.js stream readable API. It implements the Symbol.asyncIterator or Symbol.iterator iterable protocol.

This is kind of an obscure JS functionnality and we don't have to deal with it. The end result very comprehensive and illustrated with the async iterator example

This example is available with the command node samples/recipe.async.iterator.js.

const parse = require('csv-parse');
const fs = require('fs');
 
const processFile = async () => {
  records = []
  const parser = fs
  .createReadStream(`./input.csv`)
  .pipe(parse({
    // CSV options if any
  }));
  for await (const record of parser) {
    // Work with each record
    records.push(record)
  }
  return records
}

(async () => {
  const records = await processFile()
  console.info(records);
})()