{"id":13024,"library":"csv-generate","title":"CSV Generator","description":"The `csv-generate` package, currently at version 4.5.1, is a flexible JavaScript library for generating random CSV strings and JavaScript objects. It implements the Node.js `stream.Readable` API, making it suitable for scalable data generation in both Node.js and browser environments. As a component of the broader `node-csv` project, it benefits from a stable API and active maintenance, with new releases typically aligned with the entire CSV ecosystem. Key differentiators include its adherence to the stream API for efficient memory usage with large datasets, the ability to produce random or pseudo-random data based on a seed for idempotent generation, and support for user-defined value generation across various data types (integers, booleans, dates, etc.). It can output either raw CSV strings or structured JavaScript objects (arrays) depending on configuration.","status":"active","version":"4.5.1","language":"javascript","source_language":"en","source_url":"https://github.com/adaltas/node-csv","tags":["javascript","stream","generate","csv","object","backend","frontend","typescript"],"install":[{"cmd":"npm install csv-generate","lang":"bash","label":"npm"},{"cmd":"yarn add csv-generate","lang":"bash","label":"yarn"},{"cmd":"pnpm add csv-generate","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"The primary named export for creating a CSV generator stream. Prefer ESM import style for modern Node.js and browser environments. The CommonJS equivalent is `const { generate } = require('csv-generate');`.","wrong":"const generate = require('csv-generate');","symbol":"generate","correct":"import { generate } from 'csv-generate';"},{"note":"TypeScript type import for configuring the `generate` function. Provides type safety for the configuration object passed to `generate`.","symbol":"Options","correct":"import type { Options } from 'csv-generate';"},{"note":"Imports all named exports into a namespace object. Useful when accessing multiple utilities from the package or for compatibility with older module patterns.","wrong":"const csvGenerate = require('csv-generate');","symbol":"* as csvGenerate","correct":"import * as csvGenerate from 'csv-generate';"}],"quickstart":{"code":"import { generate } from 'csv-generate';\nimport assert from 'assert';\n\nconst records = [];\n// Initialize the generator with specific options\ngenerate({\n  seed: 1,\n  objectMode: true, // Crucial for getting arrays/objects instead of raw CSV strings\n  columns: 2,\n  length: 2,\n})\n  // Use the readable stream API to consume generated records\n  .on('readable', function () {\n    let record;\n    while ((record = this.read()) !== null) {\n      records.push(record);\n    }\n  })\n  // Catch any errors during generation\n  .on('error', function (err) {\n    console.error('CSV Generation Error:', err);\n  })\n  // Once generation is complete, assert the output\n  .on('end', function () {\n    assert.deepStrictEqual(records, [\n      ['OMH', 'ONKCHhJmjadoA'],\n      ['D', 'GeACHiN'],\n    ]);\n    console.log('CSV generation successful. Records:', records);\n  });\n","lang":"typescript","description":"This example demonstrates how to use `csv-generate` to create a stream that outputs a fixed number of pseudo-random CSV records as JavaScript arrays, handling events for data consumption and errors."},"warnings":[{"fix":"Always include `{ objectMode: true }` in the options object passed to `generate()` if you expect structured data records.","message":"The `objectMode: true` option is critical if you intend to receive parsed JavaScript objects (arrays by default) from the stream. If omitted, the stream will emit raw CSV string chunks (buffers in binary mode), which then require a separate parsing step.","severity":"gotcha","affected_versions":">=3.0"},{"fix":"Always register an error listener on the stream, for example: `.on('error', (err) => console.error(err));`.","message":"Node.js streams, including those created by `csv-generate`, require explicit error handling. Failing to attach an `.on('error', ...)` handler to the stream can lead to unhandled 'error' events, causing the Node.js process to crash.","severity":"gotcha","affected_versions":">=1.0"},{"fix":"When piping streams, Node.js handles backpressure automatically. If consuming manually with `.on('data')` or `.on('readable')`, check `writableStream.write(chunk)` return value and call `readableStream.pause()` when `false`, resuming with `writableStream.once('drain', () => readableStream.resume())`.","message":"When consuming `csv-generate` (a `Readable` stream) with a `Writable` stream (e.g., writing to a file), implement proper backpressure management. If the `Writable` stream cannot keep up, it will signal `false` from `write()`, and the `Readable` stream should be paused to prevent excessive memory usage.","severity":"gotcha","affected_versions":">=1.0"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"Ensure you are using named import syntax: `import { generate } from 'csv-generate';` and call it directly as a function: `generate({...});`.","cause":"The `generate` function is a named export, not a default export or a class constructor. This error typically occurs when attempting to import it incorrectly (e.g., `import generate from 'csv-generate';`) or calling it with `new`.","error":"TypeError: (0 , csv_generate__WEBPACK_IMPORTED_MODULE_0__.generate) is not a function"},{"fix":"Add an error handler to your stream: `generate(...).on('error', (err) => console.error('Stream error:', err));`.","cause":"An error occurred within the stream pipeline, but no `.on('error')` event listener was attached to catch it, leading to a process crash.","error":"Unhandled 'error' event"},{"fix":"Pass `{ objectMode: true }` in the options object when calling `generate()`: `generate({ objectMode: true, ... });`.","cause":"The `objectMode` option was not set to `true` when initializing the generator. By default, `csv-generate` operates in binary mode, emitting raw string/buffer chunks.","error":"Output is a single CSV string or buffer instead of an array of records."}],"ecosystem":"npm","meta_description":null,"install_score":null,"install_tag":null,"quickstart_score":null,"quickstart_tag":null,"pypi_latest":null,"cli_name":""}