Search code examples
node.jscsvnode-csv-parse

Using csv-parse without a loop


I'm using the csv-parse Node package to parse a CSV string. The documentation suggests that I read the parsed result using something like this:

const output = []
parse(`
  "1","2","3"
  "a","b","c"
`)
.on('readable', function() {
  let record
  while (record = this.read()) {
    output.push(record)
  }
})

This approach angers the linting gods by assigning within a while loop (and having an unnamed function). It also just doesn't make me feel great to begin with; I have a feeling there is a more concise and readable approach somewhere.

How can I populate a parsed result from the csv-parse stream without resorting to a while loop?


Solution

  • Since it's a ReadableStream you can use on('data', () => {}) instead if you prefer.

    .on('data', (record) => output.push(record))
    

    In any case, there's nothing wrong with that code, and it's the recommended approach by the csv-parse developers.