OH - CSV
Simple and highly configurable CSV/TSV parser and encoder.
Usage
var csv = ;
Parsing CSV
var parser = sep: ',' linesep: '\n' '\r' '\r\n' quote: '"' esc: '\\'; parser; parser;// [1, 'Nicolas Froidure', 'nicolas.froidure@simplifield.com'] parser;
Alternatively, you can specify fields to map them to an object properties:
var parser = fields: 'id' 'name' 'email' // fields are required for this mode sep: ',' linesep: '\n' '\r' '\r\n' quote: '"' esc: '\\'; parser; parser;// {// id: 1,// name: 'Nicolas Froidure',// email: 'nicolas.froidure@simplifield.com'// } parser;
Encoding to CSV
var encoder = fields: 'id' 'name' 'email'; encoder; // Array formencoder;// '1,Nicolas Froidure,nicolas.froidure@simplifield.com' // Object form (you need to specify fields)encoder;// '1,Nicolas Froidure,nicolas.froidure@simplifield.com'
Transforming CSV on the fly
No library needed, DIY !
var fs = ;var parser = ;var encoder = ; var Transform = Transform;var transformer = objectMode: true;transformer { rowname = rowname; this; ;}; fs ;
Excel compatible CSV
We've added a simple wrapper to get a CSV stream compatible with Excel for both OSX and Windows from a csv.encoder instance:
var encoder = csvtsvOpts;csv ;
Predefined options
There are some CSV and TSV predefined objects in order to allow you to choose your format in a simpler manner.
csv.csvOpts
CSV (Comma-Separated Values) as it's commonly found.
csv.tsvOpts
TSV (Tabulation-Separated Values)
csv.csvRFCOpts
The RFC 4180 CSV format.
API
csv.Parser(options:Object)
Create a new CSV Parser transform stream with options
as defined in the
options section.
csv.Encoder(options:Object)
Create a new CSV Encoder transform stream with options
as defined in
the options section.
Options
The options object is meant to be usable either with the Parser and the Encoder.
options.sep:Array
Default: [',']
The strings used for separating values. The first string is used to encode CSV. Separators can have several chars (useless thus essential).
options.linesep:Array
Default: ['\r\n', '\r', '\n']
The strings used for separating lines. The first string is used to encode CSV.
options.quote:Array
Default: ['"']
The strings used for quoting values. The first string is used to encode CSV.
options.toQuote:Array
Default: An array containing options.sep
, options.linesep
strings.
If a field contains any occurrence of the given strings, it must be quoted.
options.esc:Array
Default: ['\\']
The strings used for escaping special chars. The first string is used to encode CSV.
options.toEsc:Array
Default: If options.esc
is empty, an empty array. If options.quote
is empty,
an array containing options.sep
, options.linesep
, options.quote
and
options.esc
strings, otherwise, an array containing options.quote
and
options.esc
.
The strings that must be escaped.