{"id":19044561,"url":"https://github.com/brakmic/csv-writer-portable","last_synced_at":"2025-04-23T23:29:33.948Z","repository":{"id":195960753,"uuid":"694118423","full_name":"brakmic/csv-writer-portable","owner":"brakmic","description":"Convert objects/arrays into a CSV string or write them into a file","archived":false,"fork":false,"pushed_at":"2024-07-16T11:51:49.000Z","size":379,"stargazers_count":3,"open_issues_count":0,"forks_count":0,"subscribers_count":2,"default_branch":"main","last_synced_at":"2025-04-18T08:39:31.368Z","etag":null,"topics":["csv","csv-writer","csv-writer-portable","node","nodejs","npm","typescript"],"latest_commit_sha":null,"homepage":"https://www.npmjs.com/package/csv-writer-portable","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/brakmic.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2023-09-20T11:16:56.000Z","updated_at":"2024-11-12T13:08:21.000Z","dependencies_parsed_at":null,"dependency_job_id":"5fbca072-f9a7-40a8-b8d0-af7200698d1c","html_url":"https://github.com/brakmic/csv-writer-portable","commit_stats":null,"previous_names":["brakmic/csv-writer-portable"],"tags_count":15,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/brakmic%2Fcsv-writer-portable","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/brakmic%2Fcsv-writer-portable/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/brakmic%2Fcsv-writer-portable/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/brakmic%2Fcsv-writer-portable/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/brakmic","download_url":"https://codeload.github.com/brakmic/csv-writer-portable/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":250531648,"owners_count":21446031,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["csv","csv-writer","csv-writer-portable","node","nodejs","npm","typescript"],"created_at":"2024-11-08T22:46:42.798Z","updated_at":"2025-04-23T23:29:33.925Z","avatar_url":"https://github.com/brakmic.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"## CSV Writer Portable\n\n![CI/CD Pipeline](https://github.com/brakmic/csv-writer-portable/actions/workflows/main.yml/badge.svg)\n\n### Index\n- [CSV Writer Portable](#csv-writer-portable)\n  - [Index](#index)\n  - [Introduction](#introduction)\n  - [Rationale](#rationale)\n  - [Features](#features)\n  - [Prerequisites](#prerequisites)\n  - [Webpack](#webpack)\n  - [How to Test](#how-to-test)\n  - [Quick Start](#quick-start)\n    - [Writing Records as Array of Objects to a File](#writing-records-as-array-of-objects-to-a-file)\n    - [Using Custom Filter Functions](#using-custom-filter-functions)\n    - [Multiple Writes to the Same File](#multiple-writes-to-the-same-file)\n    - [Writing Large Data Sets](#writing-large-data-sets)\n    - [Skipping Header Line](#skipping-header-line)\n  - [API Documentation](#api-documentation)\n    - [createObjectCsvWriter(params)](#createobjectcsvwriterparams)\n    - [createArrayCsvWriter(params)](#createarraycsvwriterparams)\n    - [createObjectCsvStringifier(params)](#createobjectcsvstringifierparams)\n    - [CsvWriter.writeRecords(records)](#csvwriterwriterecordsrecords)\n- [Contribute](#contribute)\n  - [Guidelines](#guidelines)\n- [Development Setup](#development-setup)\n  - [Requirements](#requirements)\n- [License](#license)\n\n\n### Introduction\n\nThis repository serves as an enhanced version of an existing project, [ryu1kn/csv-writer](https://github.com/ryu1kn/csv-writer).\n\n### Rationale\n\nThe original project appeared to be unmaintained, leaving issues such as TypeScript compilation errors unresolved.\n\n---\n\n### Features\n\nThis library enables the conversion of JavaScript objects and arrays to CSV strings or writes them directly to a file. The generated CSV complies with [RFC 4180](https://tools.ietf.org/html/rfc4180).\n\n### Prerequisites\n\n- Node.js (Version 16 or higher)\n\n### Webpack\n\nCreating browser-compatible JavaScript files is now possible, thanks to the included Webpack configurations.\n\nHere's what you can do with the available NPM scripts:\n\n- `bundle:dev`: It bundles the code and includes source maps.\n- `bundle:prod`: This is for production.\n- `compile`: Compiles TypeScript based on tsconfig.json.\n- `compile-and-bundle`: Compile and bundle sources in one go.\n- `serve`: Starts a basic HTTP server to show files from the `./public` directory at `http://localhost:8080`.\n\n### How to Test\n\n1. To bundle and serve the application, run the following commands in sequence:\n\n   ```bash\n   npm run bundle:dev\n   npm run serve\n   ```\n    Then, navigate to http://localhost:8080.\n\n    ![csv-writer-in-browser](./gifs/csv-writer-in-browser.gif)\n\n2. To compile TypeScript and bundle in one go:\n\n    ```bash\n    npm run compile-and-bundle\n    npm run serve\n    ```\n\n### Quick Start\n\n#### Writing Records as Array of Objects to a File\n\nThe following code snippet demonstrates how to write records, defined as an array of objects, to a file.\n\n```ts\nimport { createObjectCsvWriter } from 'csv-writer-portable';\n\nconst csvWriter = createObjectCsvWriter({\n    path: 'path/to/file.csv',\n    header: [\n        {id: 'name', title: 'NAME'},\n        {id: 'lang', title: 'LANGUAGE'}\n    ]\n});\n\nconst records = [\n    {name: 'Bob',  lang: 'French, English'},\n    {name: 'Mary', lang: 'English'}\n];\n\ncsvWriter.writeRecords(records) // returns a promise\n    .then(() =\u003e {\n        console.log('...Done');\n    });\n```\n\nThe generated CSV file will contain the following:\n\n```csv\nNAME,LANGUAGE\nBob,\"French, English\"\nMary,English\n```\n\n#### Using Custom Filter Functions\n\nYou can pass custom filter functions to manipulate field strings. Here’s an example that removes non-printable characters like `\\r` and `\\n`:\n\n```ts\nimport { createObjectCsvWriter } from 'csv-writer-portable';\n\nconst csvPath = 'test.csv';\nconst csvWriter = createObjectCsvWriter({\n  path: csvPath,\n  header: [\n    { id: 'phone_number', title: 'phone_number' },\n    { id: 'name', title: 'name' }\n  ],\n  filterFunction: (value: any) =\u003e {\n    const str = String(value);\n    // a simple regex to remove \\r and \\n chars\n    return str.replace(/[\\r\\n]/g, '');\n  },\n  alwaysQuote: true\n});\n\nconst data = [\n  { phone_number: 9978789799, name: \"John \\nDoe\\r\" },\n  { phone_number: 8898988989, name: \"Bob Marlin\" }\n];\n\nasync function writeCsv() {\n  await csvWriter.writeRecords(data);\n}\n\nwriteCsv().catch(err =\u003e console.error('Error writing CSV:', err));\n```\n\n#### Multiple Writes to the Same File\n\nTo append more records, simply call `writeRecords` again after the promise from the previous call is fulfilled.\n\n```ts\n// Usage in an async function\nawait csvWriter.writeRecords(records1);\nawait csvWriter.writeRecords(records2);\n```\n\n#### Writing Large Data Sets\n\nFor large data sets, you may want to create a Node.js transform stream and use `CsvStringifier`. This enables you to pipe the stream to a file write stream.\n\n#### Skipping Header Line\n\nTo omit the header line, provide only the field IDs without titles.\n\n```ts\nconst csvWriter = createCsvWriter({\n    path: 'path/to/file.csv',\n    header: ['name', 'lang']\n});\n```\n\nIf each record is defined as an array, use `createArrayCsvWriter` to get a `csvWriter` instance.\n\n```ts\nimport { createArrayCsvWriter } from 'csv-writer-portable';\n\nconst csvWriter = createArrayCsvWriter({\n    header: ['NAME', 'LANGUAGE'],\n    path: 'path/to/file.csv'\n});\n\nconst records = [\n    ['Bob',  'French, English'],\n    ['Mary', 'English']\n];\n\ncsvWriter.writeRecords(records) // returns a promise\n    .then(() =\u003e {\n        console.log('...Done');\n    });\n```\n\nThis will produce a file path/to/file.csv with following contents:\n\n```csv\nNAME,LANGUAGE\nBob,\"French, English\"\nMary,English\n```\n\nIf you just want to get a CSV string but don't want to write into a file, you can use `createObjectCsvStringifier` (or `createArrayCsvStringifier`) to get a `csvStringifier`.\n\n```ts\nimport { createObjectCsvStringifier } from 'csv-writer-portable';\n\nconst csvStringifier = createObjectCsvStringifier({\n    header: [\n        {id: 'name', title: 'NAME'},\n        {id: 'lang', title: 'LANGUAGE'}\n    ]\n});\n\nconst records = [\n    {name: 'Bob',  lang: 'French, English'},\n    {name: 'Mary', lang: 'English'}\n];\n```\n\n```ts\nconsole.log(csvStringifier.getHeaderString());\n// =\u003e 'NAME,LANGUAGE\\n'\n\nconsole.log(csvStringifier.stringifyRecords(records));\n// =\u003e 'Bob,\"French, English\"\\nMary,English\\n'\n```\n\n### API Documentation\n\nThe following tables describe the methods exposed by the CSV Writer Portable library.\n\n#### createObjectCsvWriter(params)\n\n| Description | Link |\n| --- | --- |\n| Creates a CsvWriter instance | [Source Code](https://github.com/brakmic/csv-writer-portable/blob/main/src/lib/csv-writer-factory.ts#L40) |\n\n| Parameter | Type | Description | Default | Allowed |\n| --- | --- | --- | --- | --- |\n| params | Object | Configuration options | - |\n| └─ path | String | File path | - |\n| └─ header | Array\u003c{id, title}\\|string\u003e | Header specification | - |\n| └─ fieldDelimiter | String (Optional) | Field delimiter | `,` | `; \\| \\t` |  \n| └─ recordDelimiter | String (Optional) | Record delimiter | `\\n` |\n| └─ encoding | String (Optional) | File encoding | `utf8` |\n| └─ append | Boolean (Optional) | Append mode | `false` |\n| └─ alwaysQuote | Boolean (Optional) | Always quote field values | `false` |\n| └─ quoteEmptyFields | Boolean (Optional) | Double-quote (\"\") fields with empty values | `false` |\n| └─ filterFunction | Function (Optional) | Custom function to manipulate field strings | (value: any) =\u003e value |\n| └─ useBom | Boolean (Optional) | Add BOM for UTF-8 encoding | `false` |\n\n**Returns**: [CsvWriter](https://github.com/brakmic/csv-writer-portable/blob/main/src/lib/csv-writer.ts#L10) instance\n\n---\n\n#### createArrayCsvWriter(params)\n\n| Description | Link |\n| --- | --- |\n| Creates an ArrayCsvWriter instance | [Source Code](https://github.com/brakmic/csv-writer-portable/blob/main/src/lib/csv-writer-factory.ts#L\n\n56) |\n\n| Parameter | Type | Description | Default | Allowed |\n| --- | --- | --- | --- | --- |\n| params | Object | Configuration options | - |\n| └─ path | String | File path | - |\n| └─ header | Array\u003cstring\u003e | Header specification | - |\n| └─ fieldDelimiter | String (Optional) | Field delimiter | `,` | `; \\| \\t` |  \n| └─ recordDelimiter | String (Optional) | Record delimiter | `\\n` |\n| └─ encoding | String (Optional) | File encoding | `utf8` |\n| └─ append | Boolean (Optional) | Append mode | `false` |\n| └─ alwaysQuote | Boolean (Optional) | Always quote field values | `false` |\n| └─ quoteEmptyFields | Boolean (Optional) | Double-quote (\"\") fields with empty values | `false` |\n| └─ filterFunction | Function (Optional) | Custom function to manipulate field strings | (value: any) =\u003e value |\n| └─ useBom | Boolean (Optional) | Add BOM for UTF-8 encoding | `false` |\n\n**Returns**: [CsvWriter](https://github.com/brakmic/csv-writer-portable/blob/main/src/lib/csv-writer.ts#L10) instance\n\n---\n\n#### createObjectCsvStringifier(params)\n\n| Description | Link |\n| --- | --- |\n| Creates an ObjectCsvStringifier instance | [Source Code](https://github.com/brakmic/csv-writer-portable/blob/main/src/lib/csv-stringifier-factory.ts#L28) |\n\n| Parameter | Type | Description | Default | Allowed |\n| --- | --- | --- | --- | --- |\n| params | Object | Configuration options | - |\n| └─ header | Array\u003c{id, title}\\|string\u003e | Header specification | - |\n| └─ fieldDelimiter | String (Optional) | Field delimiter | `,` | `; \\| \\t` |\n| └─ recordDelimiter | String (Optional) | Record delimiter | `\\n` |\n| └─ headerIdDelimiter | String (Optional) | Header ID delimiter | `_` |\n| └─ alwaysQuote | Boolean (Optional) | Always quote field values | `false` |\n| └─ quoteEmptyFields | Boolean (Optional) | Double-quote (\"\") fields with empty values | `false` |\n| └─ filterFunction | Function (Optional) | Custom function to manipulate field strings | (value: any) =\u003e value |\n\n**Returns**: [ObjectCsvStringifier](https://github.com/brakmic/csv-writer-portable/blob/main/src/lib/csv-stringifiers/object.ts#L6) instance\n\n---\n\n#### CsvWriter.writeRecords(records)\n\n| Description | Link |\n| --- | --- |\n| Writes records to CSV | [Source Code](https://github.com/brakmic/csv-writer-portable/blob/main/src/lib/csv-writer.ts#L24) |\n\n| Parameter | Type | Description |\n| --- | --- | --- |\n| records | Iterable | Collection of objects or arrays |\n\n**Returns**: Promise\u003cvoid\u003e\n\n\n## Contribute\n\nIf you'd like to contribute by either proposing new features or reporting bugs, please visit: [GitHub Issues](https://github.com/brakmic/csv-writer-portable/issues)\n\n### Guidelines\n\n- **Feature Requests**: Context is key. Please provide a detailed explanation of why you need the specific feature and how it could benefit the users.\n  \n- **Bug Reports**: Reproducible code snippets are greatly appreciated.\n\n## Development Setup\n\n### Requirements\n\n- Node.js (Version 16 or higher)\n- Docker\n\n## License\n\nLicensed under the [MIT License](./LICENSE).\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fbrakmic%2Fcsv-writer-portable","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fbrakmic%2Fcsv-writer-portable","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fbrakmic%2Fcsv-writer-portable/lists"}