CSVGenerate for Node.js

IssuesGitHub

CSV Generate API

Introduction

There are multiple APIs available. Under the hood, they share the same implementation. The stream API might not be the most pleasant API to use but is scalable. Use the callback style API or the sync API for simplicity, readability and convenience if you are sure that your datasets fit in memory.

Sync API

The generated output is returned. Like with the callback API, this mode implies that the overall dataset will be stored in memory.

The module to import or require is csv-generate/sync and the signature is const records = generate([options]).

The sync example returns an array of 2 records.

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

const records = generate({
  seed: 1,
  objectMode: true,
  columns: 2,
  length: 2
});
assert.deepEqual(records, [
  [ 'OMH', 'ONKCHhJmjadoA' ],
  [ 'D', 'GeACHiN' ]
]);

Stream API

The main module of this package implements the native Node.js readable stream API. This is the recommended approach if you need a maximum of power. It ensures scalability by treating your data as an input stream. It is however more verbose and harder to use.

The signature is const stream = generate([options]).

The stream example illustrates the various events to listen.

import assert from 'node:assert';
import { generate } from 'csv-generate';

const records = [];
// Initialize the generator
generate({
  seed: 1,
  objectMode: true,
  columns: 2,
  length: 2
})
// Use the readable stream api to consume generated records
  .on('readable', function(){
    let record; while((record = this.read()) !== null){
      records.push(record);
    }
  })
// Catch any error
  .on('error', function(err){
    console.error(err);
  })
// Test that the generated records matched the expected records
  .on('end', function(){
    assert.deepEqual(records, [
      [ 'OMH', 'ONKCHhJmjadoA' ],
      [ 'D', 'GeACHiN' ]
    ]);
  });

Callback API

The generated output is passed to the callback in the second argument. This mode implies that the overall dataset will be stored in memory.

The signature is const stream = generate([options], callback).

The callback example generate a dataset with 2 records.

import assert from 'node:assert';
import { generate } from 'csv-generate';

generate({
  seed: 1,
  objectMode: true,
  columns: 2,
  length: 2
}, function(err, records){
  assert.deepEqual(records, [
    [ 'OMH', 'ONKCHhJmjadoA' ],
    [ 'D', 'GeACHiN' ]
  ]);
});

About

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