CSVStringify for Node.js

IssuesGitHub

Combining a stream with a entire dataset

It leverages the stream transform API but input doesn't have to be an readable stream and output doesn't have to be a writable stream. Input may be a string passed as first argument. Output may be obtained in the callback passed as last argument.

Uses it for convenience in case you are already interacting with a readable stream or a writable stream. It is not scalable because it implies that you either have all your records in memory and wish to pipe the generated CSV into a stream writer or that you have a stream reader generated records and wish to obtain a string representing the full CSV text.

The signature of the output stream example is const stream = stringify(input, [options]). It takes an input string and an options object as arguments and return a readable stream.

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

const data = [];
stringify([
  [ '1', '2', '3', '4' ],
  [ 'a', 'b', 'c', 'd' ]
])
// Use the readable stream api
  .on('readable', function(){
    let row; while ((row = this.read()) !== null) {
      data.push(row);
    }
  })
// When we are done, test that the parsed records matched what expected
  .on('end', function(){
    assert.deepStrictEqual(
      data.join(''),
      '1,2,3,4\na,b,c,d\n'
    );
  });

Inversely, the signature of the input stream example is const stream = stringify([options], callback). It takes an options object and a callback function as arguments and return a writable stream.

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

// Create the parser
const stringifier = stringify({
  delimiter: ':'
}, function(err, data){
  assert.deepStrictEqual(
    data,
    'root:x:0:0:root:/root:/bin/bash\n' +
    'someone:x:1022:1022::/home/someone:/bin/bash\n'
  );
});
// Write records to the stream
stringifier.write([ 'root','x','0','0','root','/root','/bin/bash' ]);
stringifier.write([ 'someone','x','1022','1022','','/home/someone','/bin/bash' ]);
// Close the writable stream
stringifier.end();

About

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