Skip to content

Commit 3db6dd5

Browse files
committed
add browser api
1 parent f4ccdb4 commit 3db6dd5

File tree

12 files changed

+793
-44
lines changed

12 files changed

+793
-44
lines changed

README.md

Lines changed: 156 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -25,30 +25,34 @@ show your :heart: and support.
2525
- [Description](#description)
2626
- [Support for JS & TS](#support-for-js--ts)
2727
- [Prerequisites](#prerequisites)
28-
- [Install npm *convert-csv-to-json package*](#install-npm-convert-csv-to-json-package)
29-
* [Install](#install)
30-
* [Sync API Usage](#sync-api-usage)
31-
+ [Generate JSON file](#generate-json-file)
32-
+ [Generate Array of Object in JSON format](#generate-array-of-object-in-json-format)
33-
+ [Generate Object with sub array](#generate-object-with-sub-array)
34-
+ [Define field delimiter](#define-field-delimiter)
35-
+ [Trim header field](#trim-header-field)
36-
+ [Trim header field with whitespaces](#trim-header-field-with-whitespaces)
37-
+ [Support Quoted Fields](#support-quoted-fields)
38-
+ [Index header](#index-header)
39-
+ [Empty rows](#empty-rows)
40-
+ [Format property value by type](#format-property-value-by-type)
41-
- [Number](#number)
42-
- [Boolean](#boolean)
43-
+ [Encoding](#encoding)
44-
+ [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)
28+
- [Install npm *convert-csv-to-json package*](#install-npm-convert-csv-to-json-package)
29+
* [Install](#install)
30+
* [Sync API Usage](#sync-api-usage)
31+
+ [Generate JSON file](#generate-json-file)
32+
+ [Generate Array of Object in JSON format](#generate-array-of-object-in-json-format)
33+
+ [Generate Object with sub array](#generate-object-with-sub-array)
34+
+ [Define field delimiter](#define-field-delimiter)
35+
+ [Trim header field](#trim-header-field)
36+
+ [Trim header field with whitespaces](#trim-header-field-with-whitespaces)
37+
+ [Support Quoted Fields](#support-quoted-fields)
38+
+ [Index header](#index-header)
39+
+ [Empty rows](#empty-rows)
40+
+ [Format property value by type](#format-property-value-by-type)
41+
- [Number](#number)
42+
- [Boolean](#boolean)
43+
+ [Encoding](#encoding)
44+
+ [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+
* [Browser API Usage](#browser-api-usage)
52+
+ [Basic Browser Operations](#basic-browser-operations)
53+
+ [Parsing File/Blob](#parsing-fileblob)
54+
+ [Notes](#browser-api-notes)
55+
* [Chaining Pattern](#chaining-pattern)
5256
- [Development](#development)
5357
- [CI CD github action](#ci-cd-github-action)
5458
- [License](#license)
@@ -108,7 +112,6 @@ This package is compatible with ![JavaScript](https://img.shields.io/badge/javas
108112
## Install npm *convert-csv-to-json package*
109113
Go to NPM package [convert-csv-to-json](https://www.npmjs.com/package/convert-csv-to-json).
110114

111-
### Install
112115
Install package in your *package.json*
113116
```bash
114117
$ npm install convert-csv-to-json --save
@@ -357,10 +360,138 @@ let jsonArray = csvToJson
357360
.csvStringToJson(csvString);
358361
```
359362

363+
### Sync API (TypeScript)
364+
365+
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.
366+
367+
```ts
368+
// Named import (recommended when using ES modules)
369+
import converter, { /* or */ } from 'convert-csv-to-json';
370+
// Access the default converter
371+
const csvToJson = require('convert-csv-to-json');
372+
373+
// Define a type for your CSV records
374+
interface Person {
375+
name: string;
376+
age: number;
377+
}
378+
379+
// Parse CSV string synchronously and assert the returned type
380+
const csv = 'name,age\nAlice,30';
381+
const parsed = csvToJson.csvStringToJson(csv) as Person[];
382+
383+
// Chain configuration and call sync methods
384+
const result = csvToJson
385+
.fieldDelimiter(',')
386+
.formatValueByType()
387+
.csvStringToJson('name,age\nBob,25') as Person[];
388+
```
389+
390+
## Browser API Usage
391+
392+
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.
393+
394+
### Basic Browser Operations
395+
396+
```js
397+
const convert = require('convert-csv-to-json');
398+
399+
// Parse CSV string synchronously
400+
const arr = convert.browser
401+
.supportQuotedField(true)
402+
.fieldDelimiter(',')
403+
.csvStringToJson('name,age\nAlice,30');
404+
405+
// Parse CSV string asynchronously (returns Promise)
406+
const arrAsync = await convert.browser.csvStringToJsonAsync('name;age\nBob;25');
407+
408+
// Get stringified JSON synchronously
409+
const jsonString = convert.browser.csvStringToJsonStringified('name;age\nEve;40');
410+
```
411+
412+
### Parsing File/Blob
413+
414+
`parseFile(file, options)` reads a `File` or `Blob` and returns a Promise that resolves with the parsed array of objects.
415+
416+
```js
417+
// In a browser environment with an <input type="file">
418+
const file = document.querySelector('input[type=file]').files[0];
419+
convert.browser
420+
.fieldDelimiter(',')
421+
.formatValueByType()
422+
.parseFile(file)
423+
.then(json => console.log(json))
424+
.catch(err => console.error(err));
425+
```
426+
427+
`parseFile` accepts an optional `options` object with `encoding` (passed to `FileReader.readAsText`). If `FileReader` is not available, `parseFile` will reject.
428+
429+
### Notes
430+
431+
- 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.
432+
- `parseFile` depends on the browser `FileReader` API; calling it in Node.js will reject with an informative error.
433+
434+
### Browser API (TypeScript)
435+
436+
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.
437+
438+
```ts
439+
// Named import (recommended for direct use)
440+
import { browser } from 'convert-csv-to-json';
441+
442+
// Or default import and access the browser helper
443+
import converter from 'convert-csv-to-json';
444+
const browserApi = converter.browser;
445+
446+
// Define a type for your CSV records
447+
interface Person {
448+
name: string;
449+
age: number;
450+
}
451+
452+
// Synchronous parse (assert the returned type)
453+
const csv = 'name,age\nAlice,30';
454+
const parsed = browser.csvStringToJson(csv) as Person[];
455+
456+
// Async parse
457+
const parsedAsync = await browser.csvStringToJsonAsync(csv) as Person[];
458+
459+
// Parse a File in the browser
460+
const inputEl = document.querySelector('input[type=file]') as HTMLInputElement;
461+
const file = inputEl.files![0];
462+
const data = await browser.parseFile(file) as Person[];
463+
```
464+
465+
The `BrowserApi` interface in `index.d.ts` exposes typed method signatures for IDE autocompletion and compile-time checks.
466+
360467
## Async API Usage
361468
362469
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).
363470

471+
### Async API (TypeScript)
472+
473+
The async API also has TypeScript typings. Typical usage in TypeScript looks like this:
474+
475+
```ts
476+
import csvToJson from 'convert-csv-to-json';
477+
478+
interface Person {
479+
name: string;
480+
age: number;
481+
}
482+
483+
// Using async/await
484+
async function load(): Promise<Person[]> {
485+
const csv = 'name,age\nAlice,30';
486+
const parsed = await csvToJson.getJsonFromCsvAsync(csv, { raw: true }) as Person[];
487+
return parsed;
488+
}
489+
490+
// Using the async helper that parses CSV strings
491+
const parsedDirect = await csvToJson.csvStringToJsonAsync('name;age\nBob;25') as Person[];
492+
```
493+
494+
364495
### Basic Async Operations
365496

366497
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)