{"id":13031,"library":"csvtojson","title":"csvtojson: CSV to JSON Converter","description":"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.","status":"active","version":"2.0.14","language":"javascript","source_language":"en","source_url":"https://github.com/Keyang/node-csvtojson","tags":["javascript","csv","csv parser","parse csv","csvtojson","json","csv to json","csv convert","tojson","typescript"],"install":[{"cmd":"npm install csvtojson","lang":"bash","label":"npm"},{"cmd":"yarn add csvtojson","lang":"bash","label":"yarn"},{"cmd":"pnpm add csvtojson","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"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.","wrong":"const csv = require('csvtojson/v1');","symbol":"csvtojson (V2 API)","correct":"import csv from 'csvtojson';"},{"note":"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');`.","wrong":"import csvtojsonV1 from 'csvtojson';","symbol":"csvtojson (V1 API)","correct":"import csvtojsonV1 from 'csvtojson/v1';"},{"note":"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.","wrong":"import { fromFile } from 'csvtojson';","symbol":"fromFile / fromString","correct":"import csv from 'csvtojson';\nconst jsonArray = await csv().fromFile(csvFilePath);"}],"quickstart":{"code":"import csv from 'csvtojson';\nimport fs from 'fs';\nimport path from 'path';\n\nconst tempDir = path.join(process.cwd(), 'temp_csv_files');\nconst csvFilePath = path.join(tempDir, 'data.csv');\n\nasync function convertCsvData() {\n  // Create a temporary directory if it doesn't exist\n  if (!fs.existsSync(tempDir)) {\n    fs.mkdirSync(tempDir);\n  }\n\n  // Example 1: Convert CSV from a file\n  const fileContent = `header1,header2,header3\\nvalue1,value2,value3\\nvalA,valB,valC`;\n  fs.writeFileSync(csvFilePath, fileContent);\n\n  console.log('--- Converting from file ---');\n  try {\n    const jsonFromFile = await csv().fromFile(csvFilePath);\n    console.log(jsonFromFile);\n    // Expected: [{ header1: 'value1', header2: 'value2', header3: 'value3' }, ...]\n  } catch (error) {\n    console.error('Error converting from file:', error);\n  }\n\n  // Example 2: Convert CSV from a string with custom options (no header, output as array of arrays)\n  const stringContent = `1,2,3\\n4,5,6`;\n  console.log('\\n--- Converting from string (as CSV rows) ---');\n  try {\n    const csvRows = await csv({\n      noheader: true,\n      output: 'csv' // 'csv' for array of arrays, 'json' for array of objects (default)\n    }).fromString(stringContent);\n    console.log(csvRows);\n    // Expected: [['1', '2', '3'], ['4', '5', '6']]\n  } catch (error) {\n    console.error('Error converting from string:', error);\n  }\n\n  // Example 3: Stream processing (demonstrative, requires more setup for actual http stream)\n  // For a real scenario, replace 'fs.createReadStream' with a network stream like 'request.get()'\n  console.log('\\n--- Converting via stream (first two lines) ---');\n  const results: any[] = [];\n  await new Promise<void>((resolve, reject) => {\n    fs.createReadStream(csvFilePath)\n      .pipe(csv())\n      .on('data', (data) => {\n        // Each 'data' event emits a single JSON object (one row)\n        results.push(JSON.parse(data.toString()));\n      })\n      .on('end', () => {\n        console.log(results.slice(0, 2)); // Show first two processed objects\n        resolve();\n      })\n      .on('error', (err) => {\n        console.error('Stream error:', err);\n        reject(err);\n      });\n  });\n\n  // Clean up the temporary directory\n  fs.unlinkSync(csvFilePath);\n  fs.rmdirSync(tempDir);\n}\n\nconvertCsvData();","lang":"typescript","description":"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)."},"warnings":[{"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).","message":"Version 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`.","severity":"breaking","affected_versions":">=2.0.0"},{"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.","message":"The `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.","severity":"gotcha","affected_versions":">=1.0.0"},{"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.","message":"Certain 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).","severity":"gotcha","affected_versions":">=1.1.5"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"Call the imported `csv` function to create an instance: `csv().fromFile(csvFilePath)` instead of `csv.fromFile(csvFilePath)`.","cause":"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.","error":"TypeError: csv(...).fromFile is not a function"},{"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.","cause":"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.","error":"Error: Cannot find module 'csvtojson/v1'"},{"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(...)`.","cause":"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.","error":"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'}]`)."}],"ecosystem":"npm","meta_description":null,"install_score":null,"install_tag":null,"quickstart_score":null,"quickstart_tag":null,"pypi_latest":null,"cli_name":"csvtojson"}