Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
N

node-csvtojson

> 编程语言
Open source

Blazing fast and Comprehensive CSV Parser for Node.JS / Browser / Command Line.

2.0K stars0 likes3 views
WebsiteGitHub

About

Blazing fast and Comprehensive CSV Parser for Node.JS / Browser / Command Line.

CSVTOJSON

csvtojson module is a comprehensive nodejs csv parser to convert csv to json or column arrays. It can be used as node.js library / command line tool / or in browser. Below are some features:

  • Strictly follow CSV definition RFC4180
  • Work with millions of lines of CSV data
  • Provide comprehensive parsing parameters
  • Provide out of box CSV parsing tool for Command Line
  • Blazing fast -- Focus on performance
  • Give flexibility to developer with 'pre-defined' helpers
  • Allow async / streaming parsing
  • Provide a csv parser for both Node.JS and browsers
  • Easy to use API

csvtojson online

Here is a free online csv to json convert service utilizing latest csvtojson module.

Upgrade to V2

csvtojson has released version 2.0.0.

  • To upgrade to v2, please follow upgrading guide
  • If you are looking for documentation for v1, open this page

It is still able to use v1 with [email protected]

javascript
// v1
const csvtojsonV1=require("csvtojson/v1");
// v2
const csvtojsonV2=require("csvtojson");
const csvtojsonV2=require("csvtojson/v2");

Menu

  • Quick Start
  • API
  • Browser Usage
  • Contribution

Quick Start

  • As Library
  • As Command Line Tool

Library

Installation

bash
npm i --save csvtojson

From CSV File to JSON Array

javascript
/** csv file
a,b,c
1,2,3
4,5,6
*/
const csvFilePath='<path to csv file>'
const csv=require('csvtojson')
csv()
.fromFile(csvFilePath)
.then((jsonObj)=>{
	console.log(jsonObj);
	/**
	 * [
	 * 	{a:"1", b:"2", c:"3"},
	 * 	{a:"4", b:"5". c:"6"}
	 * ]
	 */ 
})

// Async / await usage
const jsonArray=await csv().fromFile(csvFilePath);

From CSV String to CSV Row

javascript
/**
csvStr:
1,2,3
4,5,6
7,8,9
*/
const csv=require('csvtojson')
csv({
	noheader:true,
	output: "csv"
})
.fromString(csvStr)
.then((csvRow)=>{ 
	console.log(csvRow) // => [["1","2","3"], ["4","5","6"], ["7","8","9"]]
})

Asynchronously process each line from csv url

javascript
const request=require('request')
const csv=require('csvtojson')

csv()
.fromStream(request.get('http://mywebsite.com/mycsvfile.csv'))
.subscribe((json)=>{
	return new Promise((resolve,reject)=>{
		// long operation for each json e.g. transform / write into database.
	})
},onError,onComplete);

Convert to CSV lines

javascript
/**
csvStr:
a,b,c
1,2,3
4,5,6
*/

const csv=require('csvtojson')
csv({output:"line"})
.fromString(csvStr)
.subscribe((csvLine)=>{ 
	// csvLine =>  "1,2,3" and "4,5,6"
})

Use Stream

javascript
const csv=require('csvtojson');

const readStream=require('fs').createReadStream(csvFilePath);

const writeStream=request.put('http://mysite.com/obj.json');

readStream.pipe(csv()).pipe(writeStream);

To find more detailed usage, please see API section

Command Line Usage

Installation

$ npm i -g csvtojson

Usage

$ csvtojson [options] <csv file path>

Example

Convert csv file and save result to json file:

$ csvtojson source.csv > converted.json

Pipe in csv data:

$ cat ./source.csv | csvtojson > converted.json

Print Help:

$ csvtojson

API

  • Parameters
  • Asynchronous Result Process
  • Events
  • Hook / Transform
  • Nested JSON Structure
  • Header Row
  • Column Parser

Parameters

require('csvtojson') returns a constructor function which takes 2 arguments:

  1. Parser parameters
  2. Stream options
javascript
const csv=require('csvtojson')
const converter=csv(parserParameters, streamOptions)

Both arguments are optional.

For Stream Options please read Stream Option from Node.JS

parserParameters is a JSON object like:

javascript
const converter=csv({
	noheader:true,
	trim:true,
})

Following parameters are supported:

  • output: The format to be converted to. "json" (default) -- convert csv to json. "csv" -- convert csv to csv row array. "line" -- convert csv to csv line string
  • delimiter: delimiter used for separating columns. Use "auto" if delimiter is unknown in advance, in this case, delimiter will be auto-detected (by best attempt). Use an array to give a list of potential delimiters e.g. [",","|","$"]. default: ","
  • quote: If a column contains delimiter, it is able to use quote character to surround the column content. e.g. "hello, world" won't be split into two columns while parsing. Set to "off" will ignore all quotes. default: " (double quote)
  • trim: Indicate if parser trim off spaces surrounding column content. e.g. " content " will be trimmed to "content". Default: true
  • checkType: This parameter turns on and off whether check field type. Default is false. (The default is true if version < 1.1.4)
  • ignoreEmpty: Ignore the empty value in CSV columns. If a column value is not given, set this to true to skip them. Default: false.
  • fork (experimental): Fork another process to parse the CSV stream. It is effective if many concurrent parsing sessions for large csv files. Default: false
  • noheader:Indicating csv data has no header row and first row is data row. Default is false. See header row
  • headers: An array to specify the headers of CSV data. If --noheader is false, this value will override CSV header row. Default: null. Example: ["my field","name"]. See header row
  • flatKeys: Don't interpret dots (.) and square brackets in header fields as nested object or array identifiers at all (treat them like regular characters for JSON field identifiers). Default: false.
  • maxRowLength: the max character a csv row could have. 0 means infinite. If max number exceeded, parser will emit "error" of "row_exceed". if a possibly corrupted csv data provided, give it a number like 65535 so the parser won't consume memory. default: 0
  • checkColumn: whether check column number of a row is the same as headers. If column number mismatched headers number, an error of "mismatched_column" will be emitted.. default: false
  • eol: End of line character. If omitted, parser will attempt to retrieve it from the first chunks of CSV data.
  • escape: escape character used in quoted column. Default is double quote (") according to RFC4108. Change to back slash (\) or other chars for your own case.
  • includeColumns: This parameter instructs the parser to include only those columns as specified by the regular expression. Example: /(name|age)/ will parse and include columns whose header contains "name" or "age"
  • ignoreColumns: This parameter instructs the parser to ignore columns as specified by the regular expression. Example: /(name|age)/ will ignore columns whose header contains "name" or "age"
  • colParser: Allows override parsing logic for a specific column. It accepts a JSON object with fields like: headName: <String | Function | ColParser> . e.g. {field1:'number'} will use built-in number parser to convert value of the field1 column to number. For more information See details below
  • alwaysSplitAtEOL: Always interpret each line (as defined by eol like \n) as a row. This will prevent eol characters from being used within a row (even inside a quoted field). Default is false. Change to true if you are confident no inline line breaks (like line break in a cell which has multi line text).
  • nullObject: How to parse if a csv cell contains "null". Default false will keep "null" as string. Change to true if a null object is needed.
  • downstreamFormat: Option to set what JSON array format is needed by downstream. "line" is also called ndjson format. This format will write lines of JSON (without square brackets and commas) to downstream. "array" will write complete JSON array string to downstream (suitable for file writable stream etc). Default "line"
  • needEmitAll: Parser will build JSON result if .then is called (or await is used). If this is not desired, set this to false. Default is true. All parameters can be used in Command Line tool.

Asynchronous Result Process

Since v2.0.0, asynchronous processing has been fully supported.

e.g. Process each JSON result asynchronously.

javascript
csv().fromFile(csvFile)
.subscribe((json)=>{
	return new Promise((resolve,reject)=>{
		// Async operation on the json
		// don't forget to call resolve and reject
	})
})

For more details please read:

  • Add Promise and Async / Await support
  • Add asynchronous line by line processing support
  • Async Hooks Support

Events

Converter class defined a series of events.

header

header event is emitted for each CSV file once. It passes an array object which contains the names of the header row.

javascript
const csv=require('csvtojson')
csv()
.on('header',(header)=>{
	//header=> [header1, header2, header3]
})

header is always an array of strings without types.

data

data event is emitted for each parsed CSV line. It passes buffer of stringified JSON in ndjson format unless objectMode is set true in stream option.

javascript
const csv=require('csvtojson')
csv()
.on('data',(data)=>{
	//data is a buffer object
	const jsonStr= data.toString('utf8')
})

error

error event is emitted if any errors happened during parsing.

javascript
const csv=require('csvtojson')
csv()
.on('error',(err)=>{
	console.log(err)
})

Note that if error being emitted, the process will stop as node.js will automatically unpipe() upper-stream and chained down-stream1. This will cause end event never being emitted because end event is only emitted when all data being consumed 2. If need to know when parsing finished, use done event instead of end.

  1. Node.JS Readable Stream
  2. Writable end Event

done

done event is emitted either after parsing successfully finished or any error happens. This indicates the processor has stopped.

javascript
const csv=require('csvtojson')
csv()
.on('done',(error)=>{
	//do some stuff
})

if any error during parsing, it will be passed in callback.

Hook & Transform

Raw CSV Data Hook

the hook -- preRawData will be called with csv string passed to parser.

javascript
const csv=require('csvtojson')
// synchronous
csv()
.preRawData((csvRawData)=>{
	var newData=csvRawData.replace('some value','another value');
	return newData;
})

// asynchronous
csv()
.preRawData((csvRawData)=>{
	return new Promise((resolve,reject)=>{
		var newData=csvRawData.replace('some value','another value');
		resolve(newData);
	})
	
})

CSV File Line Hook

The function is called each time a file line has been parsed in csv stream. The lineIdx is the file line number in the file starting with 0.

javascript
const csv=require('csvtojson')
// synchronous
csv()
.preFileLine((fileLineString, lineIdx)=>{
	if (lineIdx === 2){
		return fileLineString.replace('some value','another value')
	}
	return fileLineString
})

// asynchronous
csv()
.preFileLine((fileLineString, lineIdx)=>{
	return new Promise((resolve,reject)=>{
			// async function pr

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

TypeScriptcsvcsv-columnscsv-datacsv-row

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category编程语言
PricingOpen source

> Related tools

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言