Registry / data / csvtojson

csvtojson

JSON →
library0.1.3jsnpmunverified

csvtojson is a robust Node.js library designed for efficiently converting CSV (Comma Separated Values) data into various JSON formats, including JSON arrays of objects or arrays of row arrays. The current stable version is 2.0.14, actively maintained with releases focusing on performance, security, and API enhancements. It distinguishes itself by strictly adhering to the RFC4180 CSV standard, ensuring reliable parsing behavior. The library supports handling millions of lines of CSV data through streaming and asynchronous processing, providing comprehensive configuration options. It's versatile, usable as a Node.js library, a command-line tool, and within web browsers, offering a flexible API for diverse data transformation needs.

npm install csvtojson
INSTALL
IMPORT
SIG · CSVTOJSON
C
csvtojson
datajavascriptv0.1.3
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

csvtojson (V2 API)
import csv from 'csvtojson';
const csv = require('csvtojson/v1');
This imports the V2 API, which is the default for `csvtojson` since version 2.x. For CommonJS, use `const csv = require('csvtojson');`. The default export is a function that creates a converter instance.
csvtojson (V1 API)
import csvtojsonV1 from 'csvtojson/v1';
import csvtojsonV1 from 'csvtojson';
To explicitly use the V1 API when V2 is installed, you must import it from the '/v1' subpath. This is useful for migrating or maintaining older codebases. For CommonJS, use `const csvtojsonV1 = require('csvtojson/v1');`.
fromFile / fromString
import csv from 'csvtojson'; const jsonArray = await csv().fromFile(csvFilePath);
import { fromFile } from 'csvtojson';
Methods like `fromFile`, `fromString`, and `fromStream` are called on an instance created by invoking the default `csvtojson()` function, not directly on the imported module itself. These methods are chainable and return promises or streams.

This quickstart demonstrates how to convert CSV data to JSON from a local file, from a string with specific parsing options, and via Node.js streams. It showcases basic usage of `fromFile`, `fromString`, and piping through `fromStream` (simulated).

import csv from 'csvtojson'; import fs from 'fs'; import path from 'path'; const tempDir = path.join(process.cwd(), 'temp_csv_files'); const csvFilePath = path.join(tempDir, 'data.csv'); async function convertCsvData() { // Create a temporary directory if it doesn't exist if (!fs.existsSync(tempDir)) { fs.mkdirSync(tempDir); } // Example 1: Convert CSV from a file const fileContent = `header1,header2,header3\nvalue1,value2,value3\nvalA,valB,valC`; fs.writeFileSync(csvFilePath, fileContent); console.log('--- Converting from file ---'); try { const jsonFromFile = await csv().fromFile(csvFilePath); console.log(jsonFromFile); // Expected: [{ header1: 'value1', header2: 'value2', header3: 'value3' }, ...] } catch (error) { console.error('Error converting from file:', error); } // Example 2: Convert CSV from a string with custom options (no header, output as array of arrays) const stringContent = `1,2,3\n4,5,6`; console.log('\n--- Converting from string (as CSV rows) ---'); try { const csvRows = await csv({ noheader: true, output: 'csv' // 'csv' for array of arrays, 'json' for array of objects (default) }).fromString(stringContent); console.log(csvRows); // Expected: [['1', '2', '3'], ['4', '5', '6']] } catch (error) { console.error('Error converting from string:', error); } // Example 3: Stream processing (demonstrative, requires more setup for actual http stream) // For a real scenario, replace 'fs.createReadStream' with a network stream like 'request.get()' console.log('\n--- Converting via stream (first two lines) ---'); const results: any[] = []; await new Promise<void>((resolve, reject) => { fs.createReadStream(csvFilePath) .pipe(csv()) .on('data', (data) => { // Each 'data' event emits a single JSON object (one row) results.push(JSON.parse(data.toString())); }) .on('end', () => { console.log(results.slice(0, 2)); // Show first two processed objects resolve(); }) .on('error', (err) => { console.error('Stream error:', err); reject(err); }); }); // Clean up the temporary directory fs.unlinkSync(csvFilePath); fs.rmdirSync(tempDir); } convertCsvData();
csvtojson --version
Debug
Known issues
breakingVersion 2.0 introduced significant API changes and module structure updates compared to version 1.0. Direct upgrades from v1 to v2 without code modification will likely result in `TypeError` or `ReferenceError`.
fix
Consult the official 'Upgrading Guide to V2' in the GitHub repository for detailed migration steps. For applications requiring the V1 API, explicitly `require('csvtojson/v1')` (CommonJS) or `import csvtojsonV1 from 'csvtojson/v1'` (ESM).
affects: >=2.0.0
gotchaThe `csvtojson` parser strictly adheres to RFC4180 for CSV formatting. This can lead to unexpected parsing failures or incorrect results if your input CSV files contain malformed data, such as unescaped delimiters within quoted fields, or inconsistent quoting.
fix
Ensure your CSV data is compliant with RFC4180. If strict parsing is problematic, investigate options within `csvtojson` for custom column definitions, `colParser` functions, or preprocessing hooks that can normalize input before the main parsing stage.
affects: >=1.0.0
gotchaCertain features, such as multi-worker processing (available in older versions or specific configurations), may internally use Node.js's `child_process` module. This can lead to larger bundle sizes and compatibility issues in environments where `child_process` is unavailable or restricted (e.g., web browsers without polyfills, some serverless platforms).
fix
If deploying to environments with `child_process` limitations or if bundle size is critical, avoid using options that enable multi-worker processing. For browser usage, ensure you are using a browser-specific build or configure your bundler to correctly handle Node.js core module shims.
affects: >=1.1.5
Errors
Common errors & fixes
TypeError: csv(...).fromFile is not a function
The `csvtojson` module's default export is a function that must be called to instantiate a converter object before methods like `fromFile()` or `fromString()` can be invoked.
fix
Call the imported `csv` function to create an instance: `csv().fromFile(csvFilePath)` instead of `csv.fromFile(csvFilePath)`.
Error: Cannot find module 'csvtojson/v1'
This error occurs when attempting to `require` or `import` the V1 API via `csvtojson/v1`, but the package installation or bundler configuration does not expose this subpath correctly.
fix
Verify that `csvtojson` is installed correctly. If using a bundler (like Webpack or Rollup), ensure it's configured to handle subpath exports from `node_modules` correctly. In some cases, directly installing a V1 version (`npm install csvtojson@1`) might be necessary if strict V1 API compatibility is paramount.
Output is an array of arrays (e.g., `[['1','2'], ['3','4']]`) instead of an array of objects (e.g., `[{a:'1',b:'2'}, {a:'3',b:'4'}]`).
The `output` option in the converter configuration is set to `'csv'` instead of the default `'json'`, or `noheader` is true without an explicit `headers` array, causing it to infer rows as arrays.
fix
To get an array of JSON objects, ensure `output: 'json'` (which is the default) and that your CSV has a header row that `csvtojson` can parse. If your CSV has no header, you must provide a `headers` array in the options: `csv({ noheader: true, headers: ['col1', 'col2'] }).fromString(...)`.
Upgrade
Version history
0.1.3latest on npm
Audit
Dependencies

No dependency data recorded yet.

Agent activity
11 hits · last 30 days
node
10
OpenAI (training)
1
Resources