Convert Figma logo to code with AI

CyrusNuevoDia logoCSV.js

A simple, blazing-fast CSV parser and encoder. Full RFC 4180 compliance.

1,538
95
1,538
13

Top Related Projects

13,128

Fast and powerful CSV (delimited text) parser that gracefully handles large files and malformed input

1,539

A simple, blazing-fast CSV parser and encoder. Full RFC 4180 compliance.

Full featured CSV parser with simple api and tested against large datasets.

CSV parser and formatter for node

Quick Overview

CSV.js is a lightweight JavaScript library for parsing and manipulating CSV (Comma-Separated Values) data. It provides a simple and efficient way to work with CSV files in both browser and Node.js environments, offering features for reading, writing, and modifying CSV data.

Pros

  • Easy to use with a straightforward API
  • Supports both browser and Node.js environments
  • Handles various CSV formats, including custom delimiters and line endings
  • Small file size, making it suitable for projects where minimizing dependencies is important

Cons

  • Limited advanced features compared to more comprehensive CSV libraries
  • Documentation could be more extensive, with more examples and use cases
  • May not be suitable for extremely large CSV files due to in-memory processing
  • Lacks built-in streaming capabilities for handling very large datasets

Code Examples

  1. Parsing a CSV string:
const CSV = require('csv-js');

const csvString = 'Name,Age,City\nJohn,30,New York\nJane,25,London';
const parsed = CSV.parse(csvString);
console.log(parsed);
  1. Converting an array to CSV:
const CSV = require('csv-js');

const data = [
  ['Name', 'Age', 'City'],
  ['John', 30, 'New York'],
  ['Jane', 25, 'London']
];
const csvString = CSV.stringify(data);
console.log(csvString);
  1. Reading a CSV file (Node.js):
const CSV = require('csv-js');
const fs = require('fs');

const fileContent = fs.readFileSync('data.csv', 'utf8');
const parsed = CSV.parse(fileContent);
console.log(parsed);

Getting Started

To use CSV.js in your project, follow these steps:

  1. Install the library using npm:

    npm install csv-js
    
  2. Import the library in your JavaScript file:

    const CSV = require('csv-js');
    
  3. Use the library to parse or stringify CSV data:

    const csvString = 'Name,Age\nJohn,30\nJane,25';
    const parsed = CSV.parse(csvString);
    console.log(parsed);
    
    const data = [['Name', 'Age'], ['John', 30], ['Jane', 25]];
    const stringified = CSV.stringify(data);
    console.log(stringified);
    

Competitor Comparisons

13,128

Fast and powerful CSV (delimited text) parser that gracefully handles large files and malformed input

Pros of PapaParse

  • More feature-rich, supporting advanced parsing options and configurations
  • Better performance for large CSV files
  • Extensive documentation and community support

Cons of PapaParse

  • Larger file size, which may impact load times for web applications
  • More complex API, potentially steeper learning curve for beginners

Code Comparison

CSV.js:

CSV.parse(csvString, {
  delimiter: ',',
  header: true
});

PapaParse:

Papa.parse(csvString, {
  delimiter: ',',
  header: true,
  dynamicTyping: true,
  skipEmptyLines: true
});

PapaParse offers more configuration options out of the box, allowing for greater control over parsing behavior. CSV.js provides a simpler API but with fewer built-in features.

Both libraries support basic CSV parsing, but PapaParse excels in handling complex scenarios and large datasets. CSV.js might be preferable for simpler use cases or when a smaller file size is crucial.

PapaParse's extensive documentation and active community make it easier to troubleshoot issues and find solutions. However, its larger size and more complex API may be overkill for basic parsing needs, where CSV.js could be a more lightweight alternative.

1,539

A simple, blazing-fast CSV parser and encoder. Full RFC 4180 compliance.

Pros of CSV.js

  • Lightweight and easy to use
  • Supports both parsing and generating CSV data
  • Handles various CSV formats and edge cases

Cons of CSV.js

  • Limited documentation and examples
  • May lack advanced features for complex CSV manipulations
  • No built-in support for streaming large files

Code Comparison

CSV.js:

const CSV = require('csv.js');

const csvData = 'Name,Age\nJohn,30\nJane,25';
const parsed = CSV.parse(csvData);
console.log(parsed);

Both repositories appear to be the same project, as they have the same name and owner. Without access to a different repository for comparison, it's not possible to provide a meaningful code comparison or highlight specific differences between two distinct projects.

Summary

CSV.js is a JavaScript library for working with CSV data. It offers simple parsing and generation capabilities, making it suitable for basic CSV handling tasks. However, it may lack advanced features and comprehensive documentation, which could be limiting for more complex use cases. Users should consider their specific requirements and the level of support needed when choosing this library for their projects.

Full featured CSV parser with simple api and tested against large datasets.

Pros of node-csv

  • More comprehensive and feature-rich CSV parsing and manipulation library
  • Better documentation and examples for various use cases
  • Actively maintained with regular updates and bug fixes

Cons of node-csv

  • Larger package size and potentially more complex setup
  • May have a steeper learning curve for simple CSV operations
  • Requires Node.js environment, not suitable for browser-based applications

Code Comparison

node-csv:

import { parse } from 'csv-parse/sync';
const input = 'a,b,c\n1,2,3';
const records = parse(input, {
  columns: true,
  skip_empty_lines: true
});

CSV.js:

const CSV = require('./CSV.js');
const csv = new CSV('a,b,c\n1,2,3');
const records = csv.parse();

Summary

node-csv offers a more robust and feature-rich solution for CSV handling in Node.js environments, with better documentation and active maintenance. However, it may be overkill for simple use cases and is not suitable for browser-based applications. CSV.js provides a simpler, lightweight alternative that can work in both Node.js and browser environments, but with fewer features and less comprehensive documentation.

CSV parser and formatter for node

Pros of fast-csv

  • More actively maintained with regular updates and bug fixes
  • Extensive documentation and examples available
  • Supports both parsing and writing CSV files

Cons of fast-csv

  • Larger package size and potentially higher memory usage
  • More complex API, which may have a steeper learning curve
  • Slower performance for very large datasets compared to simpler libraries

Code Comparison

CSV.js:

const CSV = require('csv.js');

CSV.parse(data, (err, rows) => {
  if (err) throw err;
  console.log(rows);
});

fast-csv:

const csv = require('fast-csv');

csv.parseString(data)
  .on('error', error => console.error(error))
  .on('data', row => console.log(row))
  .on('end', rowCount => console.log(`Parsed ${rowCount} rows`));

Both libraries offer CSV parsing functionality, but fast-csv provides a more feature-rich API with event-based parsing. CSV.js has a simpler, callback-based approach, which may be easier for beginners or smaller projects. fast-csv's streaming capabilities make it more suitable for handling large files, while CSV.js is more lightweight and straightforward for basic parsing needs.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

CSV.js

Simple, blazing-fast CSV parsing/encoding in JavaScript. Full RFC 4180 compliance.

Compatible with browsers (>IE8), AMD, and NodeJS.

Installation

MASTER is currently under development. As such, csv.src.js and csv.js are both unusable. Make sure you download csv.min.js.

Download csv.min.js and reference to it using your preferred method.

If you use Bower, or npm, install the comma-separated-values package.

Instantiation

Create a CSV instance with var csv = new CSV(data);, where data is a plain-text CSV string. You can supply options with the format var csv = new CSV(data, { option: value });.

Options

  • cast: true to automatically cast numbers and booleans to their JavaScript equivalents. false otherwise. Supply your own array to override autocasting. Defaults to true.
  • lineDelimiter: The string that separates lines from one another. If parsing, defaults to autodetection. If encoding, defaults to '\r\n'.
  • cellDelimiter: A 1-character-long string that separates values from one another. If parsing, defaults to autodetection. If encoding, defaults to ','.
  • header: true if the first row of the CSV contains header values, or supply your own array. Defaults to false.

You can update an option's value any time after instantiation with csv.set(option, value).

Quickstart

For those accustomed to JavaScript, the CSV.js API:

// The instance will set itself up for parsing or encoding on instantiation,
// which means that each instance can only either parse or encode.
// The `options` object is optional
var csv = new CSV(data, [options]);

// If the data you've supplied is an array,
// CSV#encode will return the encoded CSV.
// It will otherwise fail silently.
var encoded = csv.encode();

// If the data you've supplied is a string,
// CSV#parse will return the parsed CSV.
// It will otherwise fail silently.
var parsed = csv.parse();

// The CSV instance can return the record immediately after
// it's been encoded or parsed to prevent storing the results
// in a large array by calling CSV#forEach and passing in a function.
csv.forEach(function(record) {
  // do something with the record
});

// CSV includes some convenience class methods:
CSV.parse(data, options); // identical to `new CSV(data, options).parse()`
CSV.encode(data, options); // identical to `new CSV(data, options).encode()`
CSV.forEach(data, options, callback); // identical to `new CSV(data, options).forEach(callback)`

// For overriding automatic casting, set `options.cast` to an array.
// For `parsing`, valid array values are: 'Number', 'Boolean', and 'String'.
CSV.parse(data, { cast: ['String', 'Number', 'Number', 'Boolean'] });
// For `encoding`, valid array values are 'Array', 'Object', 'String', 'Null', and 'Primitive'.
CSV.encode(data, { cast: ['Primitive', 'Primitive', 'String'] });

Parsing

By default CSV.js will return an array of arrays.

var data = '\
1850,20,0,1,1017281\r\n\
1850,20,0,2,1003841\r\n\
...
';
new CSV(data).parse()
/*
Returns:
[
  [1850, 20, 0, 1, 1017281],
  [1850, 20, 0, 2, 1003841]
  ...
]
*/

If the CSV's first row is a header, set header to true, and CSV.js will return an array of objects.

var data = '\
year,age,status,sex,population\r\n\
1850,20,0,1,1017281\r\n\
1850,20,0,2,1003841\r\n\
...
';
new CSV(data, { header: true }).parse();
/*
Returns:
[
  { year: 1850, age: 20, status: 0, sex: 1, population: 1017281 },
  { year: 1850, age: 20, status: 0, sex: 2, population: 1003841 }
  ...
]
*/

You may also supply your own header values, if the text does not contain them, by setting header to an array of field values.

var data = '\
1850,20,0,1,1017281\r\n\
1850,20,0,2,1003841\r\n\
...
';
new CSV(data, {
  header: ['year', 'age', 'status', 'sex', 'population']
}).parse();
/*
Returns:
[
  { year: 1850, age: 20, status: 0, sex: 1, population: 1017281 },
  { year: 1850, age: 20, status: 0, sex: 2, population: 1003841 }
  ...
]
*/

Encoding

CSV.js accepts an array of arrays or an array of objects.

var data = [[1850, 20, 0, 1, 1017281], [1850, 20, 0, 2, 1003841]...];
new CSV(data).encode();
/*
Returns:
1850,20,0,1,1017281\r\n\
1850,20,0,2,1003841\r\n\
...
*/

To add headers to an array of arrays, set header to an array of header field values.

var data = [[1850, 20, 0, 1, 1017281], [1850, 20, 0, 2, 1003841]];
new CSV(data, { header: ["year", "age", "status", "sex", "population"] }).encode();
/*
Returns:
"year","age","status","sex","population"\r\n\
1850,20,0,1,1017281\r\n\
1850,20,0,2,1003841\r\n\
*/

To add headers to an array of objects, just set header to true.

var data = [
  { year: 1850, age: 20, status: 0, sex: 1, population: 1017281 },
  { year: 1850, age: 20, status: 0, sex: 2, population: 1003841 }
];
new CSV(data, { header: true }).encode();
/*
Returns:
"year","age","status","sex","population"\r\n\
1850,20,0,1,1017281\r\n\
1850,20,0,2,1003841\r\n\
*/

Streaming

If the dataset that you've provided is to be parsed, calling CSV.prototype.forEach and supplying a function will call your function and supply it with the parsed record immediately after it's been parsed.

var data = '\
1850,20,0,1,1017281\r\n\
1850,20,0,2,1003841\r\n\
...
';
new CSV(data).forEach(function(array) {
  /*
   * do something with the incoming array
   * array example:
   *   [1850, 20, 0, 1, 1017281]
   */
});

Likewise, if you've requested an array of objects, you can still call CSV.prototype.forEach:

var data = '\
year,age,status,sex,population\r\n\
1850,20,0,1,1017281\r\n\
1850,20,0,2,1003841\r\n\
...
';
new CSV(data, { header: true }).forEach(function(object) {
  /*
   * do something with the incoming object
   * object example:
   *   { year: 1850, age: 20, status: 0, sex: 1, population: 1017281 }
   */
});

If you're dataset is to be encoded, CSV.prototype.forEach will call your function and supply the CSV-encoded line immediately after the line has been encoded:

var data = [[1850, 20, 0, 1, 1017281], [1850, 20, 0, 2, 1003841]];
new CSV(data).forEach(function(line) {
  /*
   * do something with the incoming line
   * line example:
   *   "1850,20,0,1,1017281\r\n\""
   */
});

Casting

// For overriding automatic casting, set `options.cast` to an array.
// For `parsing`, valid array values are: 'Number', 'Boolean', and 'String'.
CSV.parse(data, { cast: ['String', 'Number', 'Number', 'Boolean'] });
// For `encoding`, valid array values are 'Array', 'Object', 'String', 'Null', and 'Primitive'.
CSV.encode(data, { cast: ['Primitive', 'Primitive', 'String'] });

Convenience Methods

CSV.parse(data, options) // identical to `new CSV(data, options).parse()`
CSV.encode(data, options) // identical to `new CSV(data, options).encode()`
CSV.forEach(data, options, callback) // identical to `new CSV(data, options).forEach(callback)`

Special Thanks