Skip to content

Commit ef75a7c

Browse files
committed
add browser api
1 parent f4ccdb4 commit ef75a7c

12 files changed

Lines changed: 808 additions & 34 deletions

README.md

Lines changed: 169 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,11 @@
88
[![Downloads](https://img.shields.io/npm/dm/convert-csv-to-json.svg)](https://npmjs.org/package/convert-csv-to-json)
99
[![NPM total downloads](https://img.shields.io/npm/dt/convert-csv-to-json.svg?style=flat)](https://npmjs.org/package/convert-csv-to-json)
1010

11-
![TypeScript](https://img.shields.io/badge/typescript-%23007ACC.svg?style=for-the-badge&logo=typescript&logoColor=white)
11+
12+
![NodeJS](https://img.shields.io/badge/node.js-6DA55F?style=for-the-badge&logo=node.js&logoColor=white)
13+
![Browser Support](https://img.shields.io/badge/browser-supported-brightgreen.svg?style=for-the-badge&logo=google-chrome&logoColor=white)
1214
![JavaScript](https://img.shields.io/badge/javascript-%23323330.svg?style=for-the-badge&logo=javascript&logoColor=%23F7DF1E)
15+
![TypeScript](https://img.shields.io/badge/typescript-%23007ACC.svg?style=for-the-badge&logo=typescript&logoColor=white)
1316

1417
**This project is not dependent on others packages or libraries, and supports both synchronous and Promise-based asynchronous APIs.**
1518

@@ -23,10 +26,9 @@ show your :heart: and support.
2326
<!-- toc -->
2427

2528
- [Description](#description)
26-
- [Support for JS & TS](#support-for-js--ts)
29+
- [Support for NodeJS, Browser, JS, TS](#support-for-nodejs-browser-js-ts)
2730
- [Prerequisites](#prerequisites)
2831
- [Install npm *convert-csv-to-json package*](#install-npm-convert-csv-to-json-package)
29-
* [Install](#install)
3032
* [Sync API Usage](#sync-api-usage)
3133
+ [Generate JSON file](#generate-json-file)
3234
+ [Generate Array of Object in JSON format](#generate-array-of-object-in-json-format)
@@ -38,17 +40,38 @@ show your :heart: and support.
3840
+ [Index header](#index-header)
3941
+ [Empty rows](#empty-rows)
4042
+ [Format property value by type](#format-property-value-by-type)
41-
- [Number](#number)
43+
- [Numbers](#numbers)
4244
- [Boolean](#boolean)
45+
- [Complete Example](#complete-example)
4346
+ [Encoding](#encoding)
4447
+ [Working with CSV strings directly](#working-with-csv-strings-directly)
45-
* [Async API Usage](#async-api-usage)
46-
+ [Basic Async Operations](#basic-async-operations)
47-
+ [Working with Raw CSV Data](#working-with-raw-csv-data)
48-
+ [Processing Large Files](#processing-large-files)
49-
+ [Error Handling and Retries](#error-handling-and-retries)
50-
+ [Batch Processing](#batch-processing)
51-
* [Chaining Pattern](#chaining-pattern)
48+
* [Sync API (TypeScript)](#sync-api-typescript)
49+
- [Browser API Usage](#browser-api-usage)
50+
* [Basic Browser Operations](#basic-browser-operations)
51+
* [Parsing File/Blob](#parsing-fileblob)
52+
* [Browser API Notes](#browser-api-notes)
53+
* [Browser API (TypeScript)](#browser-api-typescript)
54+
- [Async API Usage](#async-api-usage)
55+
* [Async API (TypeScript)](#async-api-typescript)
56+
* [Basic Async Operations](#basic-async-operations)
57+
* [Working with Raw CSV Data](#working-with-raw-csv-data)
58+
* [Processing Large Files](#processing-large-files)
59+
* [Error Handling and Retries](#error-handling-and-retries)
60+
* [Batch Processing](#batch-processing)
61+
- [Chaining Pattern](#chaining-pattern)
62+
* [Synchronous Chaining](#synchronous-chaining)
63+
* [Asynchronous Chaining](#asynchronous-chaining)
64+
- [Common Use Cases](#common-use-cases)
65+
* [1. Processing CSV from HTTP Response](#1-processing-csv-from-http-response)
66+
* [2. Batch Processing Multiple Files](#2-batch-processing-multiple-files)
67+
* [3. Data Transformation Pipeline](#3-data-transformation-pipeline)
68+
* [4. Error Recovery and Logging](#4-error-recovery-and-logging)
69+
- [Troubleshooting](#troubleshooting)
70+
* [Memory Issues with Large Files](#memory-issues-with-large-files)
71+
* [Handling Different CSV Formats](#handling-different-csv-formats)
72+
* [Common Error Solutions](#common-error-solutions)
73+
* [Performance Optimization](#performance-optimization)
74+
* [TypeScript Support](#typescript-support)
5275
- [Development](#development)
5376
- [CI CD github action](#ci-cd-github-action)
5477
- [License](#license)
@@ -98,17 +121,21 @@ will generate:
98121
}
99122
]
100123
```
101-
## Support for JS & TS
124+
## Support for NodeJS, Browser, JS, TS
125+
126+
This package is compatible with:
102127

103-
This package is compatible with ![JavaScript](https://img.shields.io/badge/javascript-%23323330.svg?style=for-the-badge&logo=javascript&logoColor=%23F7DF1E) and ![TypeScript](https://img.shields.io/badge/typescript-%23007ACC.svg?style=for-the-badge&logo=typescript&logoColor=white).
128+
![NodeJS](https://img.shields.io/badge/node.js-6DA55F?style=for-the-badge&logo=node.js&logoColor=white)
129+
![Browser Support](https://img.shields.io/badge/browser-supported-brightgreen.svg?style=for-the-badge&logo=google-chrome&logoColor=white)
130+
![JavaScript](https://img.shields.io/badge/javascript-%23323330.svg?style=for-the-badge&logo=javascript&logoColor=%23F7DF1E)
131+
![TypeScript](https://img.shields.io/badge/typescript-%23007ACC.svg?style=for-the-badge&logo=typescript&logoColor=white)
104132

105133
## Prerequisites
106134
**NPM** (see [Installing Npm](https://docs.npmjs.com/getting-started/installing-node)).
107135

108136
## Install npm *convert-csv-to-json package*
109137
Go to NPM package [convert-csv-to-json](https://www.npmjs.com/package/convert-csv-to-json).
110138

111-
### Install
112139
Install package in your *package.json*
113140
```bash
114141
$ npm install convert-csv-to-json --save
@@ -357,10 +384,138 @@ let jsonArray = csvToJson
357384
.csvStringToJson(csvString);
358385
```
359386

387+
### Sync API (TypeScript)
388+
389+
TypeScript typings are available via the included `index.d.ts`. You can import the default converter or use named imports. Below are common patterns when using the synchronous API from TypeScript.
390+
391+
```ts
392+
// Named import (recommended when using ES modules)
393+
import converter, { /* or */ } from 'convert-csv-to-json';
394+
// Access the default converter
395+
const csvToJson = require('convert-csv-to-json');
396+
397+
// Define a type for your CSV records
398+
interface Person {
399+
name: string;
400+
age: number;
401+
}
402+
403+
// Parse CSV string synchronously and assert the returned type
404+
const csv = 'name,age\nAlice,30';
405+
const parsed = csvToJson.csvStringToJson(csv) as Person[];
406+
407+
// Chain configuration and call sync methods
408+
const result = csvToJson
409+
.fieldDelimiter(',')
410+
.formatValueByType()
411+
.csvStringToJson('name,age\nBob,25') as Person[];
412+
```
413+
414+
## Browser API Usage
415+
416+
The package exposes a `browser` helper that reuses the library's parsing logic but provides browser-friendly helpers for parsing CSV strings and `File`/`Blob` objects. The API mirrors the synchronous and asynchronous Node APIs and supports method chaining for configuration.
417+
418+
### Basic Browser Operations
419+
420+
```js
421+
const convert = require('convert-csv-to-json');
422+
423+
// Parse CSV string synchronously
424+
const arr = convert.browser
425+
.supportQuotedField(true)
426+
.fieldDelimiter(',')
427+
.csvStringToJson('name,age\nAlice,30');
428+
429+
// Parse CSV string asynchronously (returns Promise)
430+
const arrAsync = await convert.browser.csvStringToJsonAsync('name;age\nBob;25');
431+
432+
// Get stringified JSON synchronously
433+
const jsonString = convert.browser.csvStringToJsonStringified('name;age\nEve;40');
434+
```
435+
436+
### Parsing File/Blob
437+
438+
`parseFile(file, options)` reads a `File` or `Blob` and returns a Promise that resolves with the parsed array of objects.
439+
440+
```js
441+
// In a browser environment with an <input type="file">
442+
const file = document.querySelector('input[type=file]').files[0];
443+
convert.browser
444+
.fieldDelimiter(',')
445+
.formatValueByType()
446+
.parseFile(file)
447+
.then(json => console.log(json))
448+
.catch(err => console.error(err));
449+
```
450+
451+
`parseFile` accepts an optional `options` object with `encoding` (passed to `FileReader.readAsText`). If `FileReader` is not available, `parseFile` will reject.
452+
453+
### Browser API Notes
454+
455+
- The `browser` API proxies the same configuration methods as the Node API and follows the same behavior for quoted fields, sub-array parsing, trimming, and value formatting.
456+
- `parseFile` depends on the browser `FileReader` API; calling it in Node.js will reject with an informative error.
457+
458+
### Browser API (TypeScript)
459+
460+
TypeScript typings are provided via the included `index.d.ts`. You can import the default converter and access the `browser` helper, or import `browser` directly. Below are common usage patterns.
461+
462+
```ts
463+
// Named import (recommended for direct use)
464+
import { browser } from 'convert-csv-to-json';
465+
466+
// Or default import and access the browser helper
467+
import converter from 'convert-csv-to-json';
468+
const browserApi = converter.browser;
469+
470+
// Define a type for your CSV records
471+
interface Person {
472+
name: string;
473+
age: number;
474+
}
475+
476+
// Synchronous parse (assert the returned type)
477+
const csv = 'name,age\nAlice,30';
478+
const parsed = browser.csvStringToJson(csv) as Person[];
479+
480+
// Async parse
481+
const parsedAsync = await browser.csvStringToJsonAsync(csv) as Person[];
482+
483+
// Parse a File in the browser
484+
const inputEl = document.querySelector('input[type=file]') as HTMLInputElement;
485+
const file = inputEl.files![0];
486+
const data = await browser.parseFile(file) as Person[];
487+
```
488+
489+
The `BrowserApi` interface in `index.d.ts` exposes typed method signatures for IDE autocompletion and compile-time checks.
490+
360491
## Async API Usage
361492
362493
This library provides a Promise-based async API that's perfect for modern Node.js applications. For a detailed migration guide from sync to async API, see [MIGRATION.md](MIGRATION.md).
363494

495+
### Async API (TypeScript)
496+
497+
The async API also has TypeScript typings. Typical usage in TypeScript looks like this:
498+
499+
```ts
500+
import csvToJson from 'convert-csv-to-json';
501+
502+
interface Person {
503+
name: string;
504+
age: number;
505+
}
506+
507+
// Using async/await
508+
async function load(): Promise<Person[]> {
509+
const csv = 'name,age\nAlice,30';
510+
const parsed = await csvToJson.getJsonFromCsvAsync(csv, { raw: true }) as Person[];
511+
return parsed;
512+
}
513+
514+
// Using the async helper that parses CSV strings
515+
const parsedDirect = await csvToJson.csvStringToJsonAsync('name;age\nBob;25') as Person[];
516+
```
517+
518+
364519
### Basic Async Operations
365520

366521
1. Convert CSV file to JSON:

index.d.ts

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -116,4 +116,28 @@ declare module 'convert-csv-to-json' {
116116
}
117117
const converter: ConvertCsvToJson;
118118
export default converter;
119+
120+
/**
121+
* Browser API exposes parsing helpers for browser environments
122+
*/
123+
export interface BrowserApi {
124+
formatValueByType(active: boolean): this;
125+
trimHeaderFieldWhiteSpace(active: boolean): this;
126+
supportQuotedField(active: boolean): this;
127+
fieldDelimiter(delimiter: string): this;
128+
indexHeader(index: number): this;
129+
parseSubArray(delimiter: string, separator: string): this;
130+
131+
csvStringToJson(csvString: string): any[];
132+
csvStringToJsonStringified(csvString: string): string;
133+
csvStringToJsonAsync(csvString: string): Promise<any[]>;
134+
csvStringToJsonStringifiedAsync(csvString: string): Promise<string>;
135+
136+
/**
137+
* Parse a File or Blob and return a Promise that resolves to the JSON array
138+
*/
139+
parseFile(file: Blob | File, options?: { encoding?: string }): Promise<any[]>;
140+
}
141+
142+
export const browser: BrowserApi;
119143
}

index.js

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -202,3 +202,9 @@ exports.csvStringToJsonStringified = function(csvString) {
202202
exports.jsonToCsv = function(inputFileName, outputFileName) {
203203
csvToJson.generateJsonFileFromCsv(inputFileName, outputFileName);
204204
};
205+
206+
/**
207+
* Browser API
208+
* Provides parsing helpers suitable for browser environments (parsing strings and File/Blob objects)
209+
*/
210+
exports.browser = require('./src/browserApi');

jest.config.js

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,13 @@
11
/** @type {import('jest').Config} */
22
const config = {
3-
3+
preset: 'ts-jest',
4+
testEnvironment: 'node',
5+
transform: {
6+
'^.+\\.(ts|tsx)$': 'ts-jest'
7+
},
8+
testMatch: ['**/?(*.)+(spec|test).[tj]s?(x)'],
49
coverageReporters: ['clover', 'html' ,'json', 'lcov', ['text', {skipFull: true}]],
510
collectCoverage: true
6-
711
};
812

913
module.exports = config;

0 commit comments

Comments
 (0)