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
muslnode 18–226 runs
build_error
glibcnode 18–226 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
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.
fixCall 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.
fixVerify 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.
fixTo 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(...)`. Audit
Dependencies
No dependency data recorded yet.