CSVParse for Node.js

IssuesGitHub

Promises usage

Starting with Node.js version 15, the Stream API promise a new "stream/promises" module.

Part of the Stream Promises module is the finished function. The Function plugs into a stream and resolves a promise when it is no longer readable, writable or has experienced an error or a premature close event.

The promises example leverages pipe as well as finished to provide a convenient solution to read a file from the file system and to pipe its output into the parser.

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

import assert from 'node:assert';
import fs from 'node:fs';
import os from 'node:os';
import { parse } from 'csv-parse';
// Note, the `stream/promises` module is only available
// starting with Node.js version 16
import { finished } from 'stream/promises';

// Prepare the dataset
await fs.promises.writeFile(`${os.tmpdir()}/input.csv`, [
  'a,b,c',
  '1,2,3'
].join('\n'));
// Read and process the CSV file
const processFile = async () => {
  const records = [];
  const parser = fs
    .createReadStream(`${os.tmpdir()}/input.csv`)
    .pipe(parse({
    // CSV options if any
    }));
  parser.on('readable', function(){
    let record; while ((record = parser.read()) !== null) {
    // Work with each record
      records.push(record);
    }
  });
  await finished(parser);
  return records;
};
// Parse the CSV content
const records = await processFile();
// Validate the records
assert.deepStrictEqual(records, [
  [ 'a', 'b', 'c' ],
  [ '1', '2', '3' ]
]);

About

The Node.js CSV project is an open source product hosted on GitHub and developed by Adaltas.