1.0.1 • Published 6 years ago
salsacsv v1.0.1
A basic, explicit CSV parsing and formatting library for use in node.js. CSV strings are parsed and formatted using a set of column definitions for converting to and from CSV.
API
Table of Contents
salsacsv
Used for converting data to and from CSV.
toCSV
Converts an array of objects to a CSV string.
Parameters
rowsArray<Object> Array of objects to form rows from.columnsArray<Column> An array containing columns.optionsObject Parsing options. (optional, default{})
Examples
toCSV([
{
name: 'Cat Chow',
price: 529
}
], [
{
header: 'Name',
key: 'name'
},
{
header: 'Price',
key: 'price',
converter: (value) => value / 100
}
], {
includeHeader: true
});
// "Name","Price"\n"Cat Chow",5.29Returns String CSV string.
fromCSV
Converts a CSV string into objects.
Parameters
csvStrString CSV string.columnsArray<Column> An array containing columns. (optional, default[])optionsObject Parsing options. (optional, default{})
Examples
fromCSV('"Name","Price"\n"Cat Chow",5.29', [
{
header: 'Name',
key: 'name'
},
{
header: 'Price',
key: 'price',
parser: (value) => Math.round(parseFloat(value) * 100)
}
], {
includeHeader: true
});
// { name: 'Cat Chow', price: 529 }// using no column definitions
// there will be no type conversions if no parser is given, any returned values will be strings
fromCSV('"Cat Chow",5.29');
// { col1: 'Cat Chow', col2: '5.29' }// using no column definitions (use header as keys)
fromCSV('"Name","Price"\n"Cat Chow",5.29', null, {
includeHeader: true
});
// { Name: 'Cat Chow', Price: '5.29' }Returns Array<Object> Array of objects.
cellLabel
Gets the cell label.
Parameters
Examples
cellLabel(0, 3); // A3Returns String Cell label.
Column
An object describing the format of a column.
Type: Object
Properties
headerString? The header to be used for this column.keyString? The object key for this column.requiredBoolean? Indicates whether the value should be defined when getting value from CSV. Throws an error if the resulting value is null, undefined, or an empty string.converterConverter? The function called to convert value to CSV.parserParser? The function called to parse value from CSV. Will not be called unless parseEmpty is set to true.parseEmptyBoolean? Whether to parse empty values or not.
Converter
Function to convert value to raw CSV.
Type: Function
Parameters
valueString? Value from object.detailsConverterDetails? Details of cell.
Returns (String | Number | null | undefined) Value of cell.
ConverterDetails
Converter details
Type: Object
Properties
objObject? Source object.keyString? The key of the value we want to take from the object for this column.rowNumber? Row number.columnNumber? Column number.
Parser
Function to parse value from raw CSV.
Type: Function
Parameters
valueString? Value of cell.detailsParserDetails? Details of cell.
Returns any Parsed value from CSV string.
ParserDetails
Parser details
Type: Object
Properties
License
MIT