Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

@json2csv/node

juanjoDiaz395.2kMIT7.0.6TypeScript support: included

Node.js Transform and Async interface to convert JSON into CSV.

json, to, csv, export, convert, parse

readme

@json2csv/node

npm version npm monthly downloads Node.js CI Coverage Status license

Fast and highly configurable JSON to CSV converter. It fully support conversion following the RFC4180 specification as well as other similar text delimited formats as TSV.

@json2csv/node exposes two modules to integrate json2csv with the Node.js Stream API for stream processing of JSON data.

This package includes two modules:

  • Node Transform: Node.js Transform Stream that ingests JSON and outputs csv. Ideal to process streams (http responses, file contents, ...) in Node.js.
  • Node Async Parser: Wraps the Node Transform to offer a friendly promise-based API.

Features

  • Fast and lightweight
  • Support for standard JSON as well as NDJSON
  • Scalable to infinitely large datasets (using stream processing)
  • Advanced data selection (automatic field discovery, underscore-like selectors, custom data getters, default values for missing fields, ...)
  • Support for custom input data transformation
  • Support for custom csv cell formatting.
  • Highly customizable (supporting custom quotation marks, delimiters, eol values, etc.)
  • Automatic escaping (preserving new lines, quotes, etc.)
  • Optional headers
  • Unicode encoding support
  • Pretty printing in table format to stdout

Other json2csv packages

There are multiple flavours of json2csv:

  • Plainjs: Includes the Parser API and a new StreamParser API which doesn't the conversion in a streaming fashion in pure js.
  • Node: Includes the Node Transform and Node Async Parser APIs for Node users.
  • WHATWG: Includes the WHATWG Transform Stream and WHATWG Async Parser APIs for users of WHATWG streams (browser, Node or Deno).
  • CLI: Includes the CLI interface.

And a couple of libraries that enable additional configurations:

  • Transforms: Includes the built-in transforms for json2csv (unwind and flatten) allowing the using to transform data before is parsed.
  • Formatters: Includes the built-in formatters for json2csv (one for each data type, an excel-specific one, etc.). Formatters convert JSON data types into CSV-compatible strings.

Requirements

  • Node v16+

Installation

NPM

You can install json2csv as a dependency using NPM.

$ npm install --save @json2csv/node

Yarn

You can install json2csv as a dependency using Yarn.

$ yarn add --save @json2csv/node

Node Transform

For Node.js users, the Streaming API is wrapped in a Node.js Stream Transform. This approach ensures a consistent memory footprint and avoids blocking JavaScript's event loop.

The async API takes a second options arguments that is directly passed to the underlying streams and accepts the same options as the standard Node.js streams, plus the options supported by the Stream Parser.

This Transform uses the StreamParser under the hood and support similar events.

Usage

import { createReadStream, createWriteStream } from 'fs';
import { Transform } from '@json2csv/node';

const input = createReadStream(inputPath, { encoding: 'utf8' });
const output = createWriteStream(outputPath, { encoding: 'utf8' });

const opts = {};
const transformOpts = {};
const asyncOpts = {};
const parser = new Transform(opts, asyncOpts, transformOpts);

const processor = input.pipe(parser).pipe(output);

// You can also listen for events on the conversion and see how the header or the lines are coming out.
parser
  .on('header', (header) => console.log(header))
  .on('line', (line) => console.log(line));

Parameters

Options
  • ndjson <Boolean> indicates that the data is in NDJSON format. Only effective when using the streaming API and not in object mode.
  • fields <DataSelector[]> Defaults to toplevel JSON attributes.
  • transforms <Transform[]> Array of transforms to apply to the data. A transform is a function that receives a data recod and returns a transformed record. Transforms are executed in order.
  • formatters <Formatters> Object where the each key is a Javascript data type and its associated value is a formatters for the given type.
  • defaultValue <Any> value to use when missing data. Defaults to <empty> if not specified. (Overridden by fields[].default)
  • delimiter <String> delimiter of columns. Defaults to , if not specified.
  • eol <String> overrides the default OS line ending (i.e. \n on Unix and \r\n on Windows).
  • header <Boolean> determines whether or not CSV file will contain a title column. Defaults to true if not specified.
  • includeEmptyRows <Boolean> includes empty rows. Defaults to false.
  • withBOM <Boolean> with BOM character. Defaults to false.
Transform Options

See the Duplex stream options for more details.

Async Options

Options used by the underlying parsing library to process the binary or text stream. Not relevant when running in objectMode. Buffering is only relevant if you expect very large strings/numbers in your JSON. See @streamparser/json for more details about buffering.

  • stringBufferSize <number> Size of the buffer used to parse strings. Defaults to 0 which means to don't buffer. Min valid value is 4.
  • numberBufferSize <number> Size of the buffer used to parse numbers. Defaults to 0 to don't buffer.

Complete Documentation

See https://juanjodiaz.github.io/json2csv/#/parsers/node-transform.

Node Async Parser

To facilitate usage, NodeAsyncParser wraps NodeTransform exposing a single parse method similar to the sync API. This method accepts JSON arrays/objects, TypedArrays, strings and readable streams as input and returns a stream that produces the CSV.

NodeAsyncParser also exposes a convenience promise method which turns the stream into a promise that resolves to the whole CSV.

Usage

import { AsyncParser } from '@json2csv/node';

const opts = {};
const transformOpts = {};
const asyncOpts = {};
const parser = new AsyncParser(opts, asyncOpts, transformOpts);

const csv = await parser.parse(data).promise();

// The parse method return the transform stream.
// So data can be passed to a writable stream (a file, http request, etc.)
parser.parse(data).pipe(writableStream);

Parameters

Options
  • ndjson <Boolean> indicates that the data is in NDJSON format. Only effective when using the streaming API and not in object mode.
  • fields <DataSelector[]> Defaults to toplevel JSON attributes.
  • transforms <Transform[]> Array of transforms to apply to the data. A transform is a function that receives a data recod and returns a transformed record. Transforms are executed in order.
  • formatters <Formatters> Object where the each key is a Javascript data type and its associated value is a formatters for the given type.
  • defaultValue <Any> value to use when missing data. Defaults to <empty> if not specified. (Overridden by fields[].default)
  • delimiter <String> delimiter of columns. Defaults to , if not specified.
  • eol <String> overrides the default OS line ending (i.e. \n on Unix and \r\n on Windows).
  • header <Boolean> determines whether or not CSV file will contain a title column. Defaults to true if not specified.
  • includeEmptyRows <Boolean> includes empty rows. Defaults to false.
  • withBOM <Boolean> with BOM character. Defaults to false.
Transform Options

See the Duplex stream options for more details.

Async Options

Options used by the underlying parsing library to process the binary or text stream. Not relevant when running in objectMode. Buffering is only relevant if you expect very large strings/numbers in your JSON. See @streamparser/json for more details about buffering.

  • stringBufferSize <number> Size of the buffer used to parse strings. Defaults to 0 which means to don't buffer. Min valid value is 4.
  • numberBufferSize <number> Size of the buffer used to parse numbers. Defaults to 0 to don't buffer.

Complete Documentation

See https://juanjodiaz.github.io/json2csv/#/parsers/node-async-parser.

License

See LICENSE.md.

changelog

7.0.6 (2024-02-11)

Bug Fixes

  • remove legacy unused settings (bbe451e)

7.0.5 (2024-01-20)

Bug Fixes

  • fix typings of WHATWG AsyncParser (610e292)
  • update streamparser version on CDN build (ab22f53)

Performance Improvements

  • cache regular expresions for string formatters (dcaadcf)

7.0.4 (2023-11-05)

7.0.3 (2023-08-24)

Bug Fixes

  • fix CDN build & set esbuild to use es2019 (d59606e)

7.0.3 (2023-08-24)

Bug Fixes

  • fix CDN build & set esbuild to use es2019 (d59606e)

7.0.2 (2023-08-16)

Bug Fixes

  • wrong "main" in formatters package.json affecting eslint (3179a05)

7.0.1 (2023-05-31)

Bug Fixes

  • Maximum call stack size exceeded on whatwg interface (ea44d4e)

Changelog

All notable changes to this project will be documented in this file. See standard-version for commit guidelines.

7.0.0 (2023-05-26)

  • library moved to Typescript.

Bug Fixes

  • fix issue with CLI and node JSON import warnings (d316310)
  • rebase issues (8eeca7d)

Features

  • improve error messaging for invalid inputs (471849f)

6.1.3 (2023-04-02)

Bug Fixes

  • add AsyncParser to whatwg export (81ada93)
  • add transform dependency to CLI (e06961c)

6.1.2 (2022-11-14)

Bug Fixes

  • add cjs built files during prepublish (e895ac3)

6.1.1 (2022-11-08)

Bug Fixes

  • avoid unnecessary exception on flattenReducer (8b7dd1e)

6.1.0 (2022-10-30)

Features

6.0.0 (2022-09-22)

⚠ BREAKING CHANGES

  • library broken into multiple independent npm packages

Bug Fixes

  • handle exceptions in transforms properly in streaming APIs (48eff4a)

6.0.0-alpha.4 (2022-09-11)

Features

  • add error handling to try it life! (950c4e8)

Bug Fixes

  • add inter-package dependencies explicitely (d3b38c1)
  • add js extension to formatters in BaseParser (13ce920)
  • fix package exports adding .js extension wrongly (bb228bc)
  • pull CDN lodash from gh instead of npm so ti supports es6 imports (3e28e55)

6.0.0-alpha.2 (2022-08-21)

Bug Fixes

  • enforce \n EOL for backslashBeforeNewLine tests (149507d)
  • enforce \n EOL for quoteOnlyIfNecessary tests (0af4dcd)
  • fix cache for Windows builds (b4d1a60)
  • fix json packages and ensure consistent order of its fields (0b0ce1e)
  • remove tests about preserving tabs since they are historical and don't make sense anymore (6abb57a)
  • typo in test name (d05c5ae)
  • use correct line endings on windows when using prettyprint, ndjson or transforms (3c27a69)

Performance Improvements

  • bring back v5 perf improvements and add some new ones (288800b)

6.0.0-alpha.1 (2022-02-23)

Features

  • expose JSON2CSVStreamParser (d476707)

Bug Fixes

  • fix missing ndjson option to CLI (885e28b)
  • fix some issues in the AsyncParser tests (695f116)
  • reset lockfile due to changes in url patterns for github (b589372)
  • unwind transform issue with nested arrays (#548) (3cb57f3)
  • update engines and volta (98984dd)

6.0.0-alpha.0 (2021-04-14)

⚠ BREAKING CHANGES

  • Drop support for Node < v12
  • AsyncParser API has changed, see the Upgrading from 5.X to 6.X section for details.

  • fix: consolidate the API of AsyncParser and parseAsync

  • feat: simplify AsyncParser

  • chore: drop support for node 11

  • refactor: improve AsyncParser parse method

  • docs: add links to node docs and fix few small issues

  • In the JavaScript modules, formatters are introduced and the quote, escapedQuote and excelStrings options are removed. See the migration notes in the readme. CLI hasn't changed.

Features

  • Introduce formatters (#455) (88ed6ee)
  • use jsonparse for ND-JSON instead of the custom made implementation (#493) (55aa0c7)

Bug Fixes

  • consolidate the API of AsyncParser and parseAsync (#492) (bcce91f)
  • issue with unwind and empty arrays creating an extra column (#497) (3b74735)
  • Performance optimizations (#491) (471f5a7)
  • prevents Parser and AsyncParser from caching the fields option between executions causing issues and inconsistencies (#498) (4d8a81a)
  • simplify stringExcel formatter and support proper escaping (#513) (50062c3)

5.0.3 (2020-09-24)

Bug Fixes

5.0.2 (2020-09-24)

Bug Fixes

  • cli: fix relative paths issue in CLI when not streaming (#488) (06079e8)

5.0.1 (2020-04-28)

Bug Fixes

5.0.0 (2020-03-15)

⚠ BREAKING CHANGES

  • Node 8 and 9 no longer supported, use Node 10 or greater. It might still work, but it has reached End-Of-Life.
  • module no longer takes unwind, unwindBlank, flatten or the flattenSeparator options, instead see the new transforms option. CLI options are unchanged from the callers side, but use the built in transforms under the hood.

  • Add support for transforms

  • Add documentation about transforms

  • remove extra commonjs build, use starting point in package.json main field.
  • Renamed doubleQuote to escapedQuote
  • remove stringify option
  • --fields-config option has been removed, use the new --config option for all configuration, not just fields.
  • Drop node 6 and 7, and add node 11 and 12

Bug Fixes

Features

  • Add support for flattening arrays and change transforms arguments to an object. (#432) (916e448)
  • Add support for transforms (#431) (f1d04d0)
  • Improve async promise to optionally not return (#421) (3e296f6)
  • Improves the unwind transform so it unwinds all unwindable fields if … (#434) (ec1f301)
  • replace fields config by a global config (#338) (d6c1c5f)

4.5.2 (2019-07-05)

Bug Fixes

  • Improve the inference of the header name when using function as value (#395) (590d19a)

4.4.0 (2019-03-25)

Features

  • Performance improvements and new async api (#360) (d59dea1)

4.3.5 (2019-02-22)

Bug Fixes

4.3.4 (2019-02-11)

Bug Fixes

  • issue with fields.value function not receiving correct fields (#353) (851c02f)

4.3.3 (2019-01-11)

Bug Fixes

4.3.2 (2018-12-08)

Bug Fixes

4.3.1 (2018-11-17)

Bug Fixes

4.3.0 (2018-11-05)

Bug Fixes

Features

  • Add support for objectMode in the stream API (#325) (8f0ae55)

4.2.1 (2018-08-06)

Bug Fixes

  • bug that modifies opts after parsing an object/stream (#318) (f0a4830)
  • Clean up the flattening separator feature (#315) (ee3d181)

4.2.0 (2018-07-31)

Features

4.1.6 (2018-07-12)

Bug Fixes

  • Update dependencies and remove cli-table2 dependency (#312) (5981ba3)

4.1.5 (2018-06-26)

Bug Fixes

4.1.4 (2018-06-23)

Bug Fixes

4.1.3 (2018-05-23)

Bug Fixes

4.1.2 (2018-04-16)

Bug Fixes

  • tests: Skip bogus pretty print tests only in old node versions (#290) (0f3b885)

4.1.1 (2018-04-16)

Bug Fixes

  • readme CLI's info (#289) (9fe65b3)
  • Add tests and docs to unwind-blank feature (#287) (e3d4a05)
  • perf: Improve unwind performance and maintainability (#288) (80e496d)

4.1.0 (2018-04-16)

Bug Fixes

  • Avoid redundant deep cloning when unwinding. (#286) (95a6ca9)

Features

  • Add ability to unwind by blanking out instead of repeating data (#285) (61d9808)

4.0.4 (2018-04-10)

Bug Fixes

4.0.3 (2018-04-09)

Bug Fixes

  • error when a field is null and flatten is used (#274) (1349a94)
  • throw error for empty dataset only if fields not specified (0d8534e)

4.0.2 (2018-03-09)

Bug Fixes

4.0.1 (2018-03-05)

Bug Fixes

  • double quote escaping before new line (#268) (fa991cf)

4.0.0 (2018-02-27)

Bug Fixes

  • Replace webpack with rollup packaging (#266) (a9f8020)

Features

4.0.0-alpha.2 (2018-02-25)

Bug Fixes

4.0.0-alpha.1 (2018-02-21)

Bug Fixes

4.0.0-alpha.0 (2018-02-21)

Bug Fixes

Chores

Features

  • add doubleQuote to cli, rename other options to line up with the cli (5e402dc)
  • Add fields config option to CLI (#245) (74ef666)
  • Add streaming API (#235) (01ca93e)
  • Split tests in multiple files (#246) (839de77)

BREAKING CHANGES

  • Replaces field-list with field-config
  • Remove preserveNewLinesInValues option, preserve by default

  • Refactor the entire library to ES6

  • Fix PR issues

  • Add strict mode for node 4.X

  • Remove fieldNames

  • Increase coverage back to 100%

  • callback is no longer available, just return the csv from the json2csv.

  • updated tests

  • updated readme
    • Rename unwindPath to unwind
  • Fix field-list in CLI

  • newLine removed, eol kept.
  • Rename del to delimiter to match the cli flag
  • Rename quotes to quote to match the cli flag

  • Remove unused double quotes comment

  • Fix noHeader in CLI

  • Revert "Remove unused double quotes comment"

This reverts commit 250d3e6ddf3062cbdc1e0174493a37fa21197d8e.

  • Add doubleQuote to CLI
  • Rename hasCSVColumnTitle to noHeader to keep in line with the CLI

3.11.5 (2017-10-23)

Bug Fixes

3.11.4 (2017-10-09)

Bug Fixes

  • security: Update debug to 3.1.0 for security reasons (9c7cfaa)

3.11.3 (2017-10-09)

3.11.2 (2017-09-13)

Bug Fixes

3.11.1 (2017-08-11)

Bug Fixes

  • cli: pass BOM cli option to function (#193) (70cfdfe)

3.11.0 (2017-08-02)

Bug Fixes

  • Handle dates without double-escaping (#189) (ff514ba)
  • unwind parameter in command line mode (#191) (e706c25)

Features

  • Added flag to signal if resulting function value should be stringified or not (#192) (aaa6b05)

3.10.0 (2017-07-24)

Features

3.9.1 (2017-07-14)

3.9.0 (2017-07-11)

Features

3.8.0 (2017-07-03)

Bug Fixes

  • docs: Add a coma in the ReadMe example (#181) (abeb820)

Features

  • Preserve new lines in cells with option preserveNewLinesInValues (#91) (#171) (187b701)

3.7.3 (2016-12-08)

Bug Fixes

3.6.3 / 2016-08-17

  • Fix crashing on EPIPE error #134
  • Add UMD build for browser usage #136
  • Add docs during prepublish

3.6.2 / 2016-07-22

  • Remove debugger, see #132
  • Fix changelog typo

3.6.1 / 2016-07-12

  • Fix auto-fields returning all available fields, even if not available on the first object, see #104

3.6.0 / 2016-07-07

  • Make callback optional
  • Make callback use process.nextTick, so it's not sync

    Thanks @STRML!

3.5.1 / 2016-06-29

  • Revert #114, due to more issues
  • Update npmignore
  • Add a changelog
  • Updatee readme

3.5.0 / 2016-06-21

  • includeEmptyRows options added, see #122 (Thanks @glutentag)
  • -a or --include-empty-rows added for the CLI.

2.2.1 / 2013-11-10

  • mainly for development e.g. adding code format, update readme..

2.2.0 / 2013-11-08

  • not create CSV column title by passing hasCSVColumnTitle: false, into params.
  • if field is not exist in object then the field value in CSV will be empty.
  • fix data in object format - {...}

2.1.0 / 2013-06-11

  • quote titles in the first row

2.0.0 / 2013-03-04

  • err in callback function

1.3.1 / 2013-02-20

  • fix stdin encoding

1.3.0 / 2013-02-20

  • support reading from stdin #9

1.2.0 / 2013-02-20

  • support custom field names #8

1.1.0 / 2013-01-19

  • add optional custom delimiter