CSVParse for Node.js

IssuesGitHub

Option delimiter

Defines the character(s) used to delimitate the fields inside a record. A single value or an array of values are accepted. A value can be a string or a Buffer. It can not be empty, and it can contain several characters. When not defined, the default value is a comma.

It is not possible to escape a delimiter. A field must be quoted if it contains a delimiter which should not be interpreted as such.

Single value delimiter

In the delimiter example, fields are separated by a two characters delimiter value.

import assert from 'node:assert';
import { parse } from 'csv-parse/sync';

const data = 'a key => a value';
const records = parse(data, {
  delimiter: '=>',
  trim: true
});
assert.deepStrictEqual(records, [
  [ 'a key', 'a value' ]
]);

Array of delimiter values

Delimiter can be made of multiple values when defined as an array:

import assert from 'node:assert';
import { parse } from 'csv-parse/sync';

const input = `color name::red::green::blue
Cyan \t     "0"   :: 255   :: 255
Yellow \t   "255" :: "255" ::"0"
Hot Pink \t "255" :: 105   :: "180"`;

const output = parse(input, {
  delimiter: ['::','\t'],
  trim: true,
  columns: true,
}).map((rec) => {
  let indent = '';
  return Object.entries(rec).map(([key, value]) => {
    const row = `${indent}${key}: <${value}>`;
    indent = (indent.length === 0 ? '    ' : indent);
    return row;
  }).join('\n');
}).join('\n');

assert.equal(output, `
color name: <Cyan>
    red: <0>
    green: <255>
    blue: <255>
color name: <Yellow>
    red: <255>
    green: <255>
    blue: <0>
color name: <Hot Pink>
    red: <255>
    green: <105>
    blue: <180>
`.trim());

About

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