Fast and powerful CSV parser for the browser that supports web workers and streaming large files.
npx @tessl/cli install tessl/npm-papaparse@5.5.00
# PapaParse
1
2
PapaParse is a fast and powerful CSV parsing library for JavaScript that works in browsers and Node.js environments. It provides comprehensive CSV-to-JSON and JSON-to-CSV conversion capabilities with support for RFC 4180 compliance, automatic delimiter detection, streaming of large files, web worker integration for non-blocking parsing, and advanced features like pause/resume/abort functionality.
3
4
## Package Information
5
6
- **Package Name**: papaparse
7
- **Package Type**: npm
8
- **Language**: JavaScript
9
- **Installation**: `npm install papaparse`
10
11
## Core Imports
12
13
```javascript
14
import Papa from 'papaparse';
15
```
16
17
For CommonJS:
18
19
```javascript
20
const Papa = require('papaparse');
21
```
22
23
For browsers:
24
25
```html
26
<script src="https://unpkg.com/papaparse@latest/papaparse.min.js"></script>
27
```
28
29
For AMD:
30
31
```javascript
32
define(['papaparse'], function(Papa) {
33
// Use Papa here
34
});
35
```
36
37
For jQuery:
38
39
```javascript
40
$('#fileInput').parse({
41
config: {
42
header: true,
43
complete: function(results, file) {
44
console.log('Parsed:', results.data);
45
}
46
}
47
});
48
```
49
50
## Basic Usage
51
52
```javascript
53
import Papa from 'papaparse';
54
55
// Parse CSV string to JSON
56
const csvData = "name,age,city\nJohn,25,NYC\nJane,30,LA";
57
const results = Papa.parse(csvData, {
58
header: true,
59
dynamicTyping: true
60
});
61
console.log(results.data);
62
// [{ name: "John", age: 25, city: "NYC" }, { name: "Jane", age: 30, city: "LA" }]
63
64
// Convert JSON to CSV
65
const jsonData = [
66
{ name: "John", age: 25, city: "NYC" },
67
{ name: "Jane", age: 30, city: "LA" }
68
];
69
const csv = Papa.unparse(jsonData);
70
console.log(csv);
71
// "name,age,city\nJohn,25,NYC\nJane,30,LA"
72
```
73
74
## Architecture
75
76
PapaParse is built around several key components:
77
78
- **Core Parser**: Main `Papa.parse()` and `Papa.unparse()` methods for CSV/JSON conversion
79
- **Streaming Engine**: Multiple streamer classes for handling different input types (files, strings, network, Node.js streams)
80
- **Web Worker Support**: Background processing for large datasets without blocking the UI
81
- **Configuration System**: Extensive options for customizing parsing and unparsing behavior
82
- **Parser Classes**: Low-level `Parser` and `ParserHandle` classes for direct parsing control
83
84
## Capabilities
85
86
### CSV Parsing
87
88
Core CSV-to-JSON parsing functionality with automatic type conversion, delimiter detection, and error handling. Supports strings, files, and URLs as input sources.
89
90
```javascript { .api }
91
Papa.parse(input: string | File | NodeJS.ReadableStream | 1, config?: ParseConfig): ParseResult | NodeJS.ReadableStream;
92
```
93
94
[CSV Parsing](./parsing.md)
95
96
### CSV Generation
97
98
JSON-to-CSV conversion with customizable formatting, quote handling, and column ordering. Supports arrays of objects, arrays of arrays, and structured data objects.
99
100
```javascript { .api }
101
Papa.unparse(input: object[] | string[][] | UnparseObject, config?: UnparseConfig): string;
102
```
103
104
[CSV Generation](./unparsing.md)
105
106
### File Streaming
107
108
High-performance streaming for large CSV files with chunk-based processing, progress callbacks, and memory-efficient parsing. Supports local files, remote URLs, and Node.js streams.
109
110
```javascript { .api }
111
Papa.parse(file: File | string, config: { download?: boolean; chunk?: Function; step?: Function }): void;
112
```
113
114
[File Streaming](./streaming.md)
115
116
### Web Worker Support
117
118
Background parsing using web workers to prevent UI blocking during large file processing. Automatically creates and manages worker threads with message passing.
119
120
```javascript { .api }
121
Papa.parse(input: string | File, config: { worker: true }): void;
122
```
123
124
[Web Workers](./workers.md)
125
126
### jQuery Integration
127
128
Optional jQuery plugin for easy file input processing when jQuery is available.
129
130
```javascript { .api }
131
$('#fileInput').parse(options: {
132
config?: ParseConfig;
133
before?: (file: File, inputElement: Element) => void | object;
134
error?: (error: ParseError, file: File, inputElement: Element, reason?: string) => void;
135
complete?: (results: ParseResult, file: File, inputElement: Element) => void;
136
}): jQuery;
137
```
138
139
**Usage Examples:**
140
141
```javascript
142
// Basic jQuery file processing
143
$('#csvFileInput').parse({
144
config: {
145
header: true,
146
dynamicTyping: true,
147
worker: true
148
},
149
complete: function(results, file) {
150
console.log('File:', file.name, 'Rows:', results.data.length);
151
}
152
});
153
154
// Multiple files with preprocessing
155
$('#multipleFiles').parse({
156
before: function(file, inputElem) {
157
if (file.size > 10 * 1024 * 1024) { // > 10MB
158
return { config: { worker: true, chunkSize: Papa.LocalChunkSize } };
159
}
160
},
161
config: { header: true },
162
complete: function(results, file) {
163
addFileResults(file.name, results.data);
164
},
165
error: function(error, file) {
166
console.error('Error parsing', file.name, ':', error);
167
}
168
});
169
```
170
171
## Constants and Configuration
172
173
### Built-in Constants
174
175
```javascript { .api }
176
Papa.RECORD_SEP: string; // ASCII record separator (char 30)
177
Papa.UNIT_SEP: string; // ASCII unit separator (char 31)
178
Papa.BYTE_ORDER_MARK: string; // UTF-8 BOM ('\ufeff')
179
Papa.BAD_DELIMITERS: string[]; // Invalid delimiter characters
180
Papa.WORKERS_SUPPORTED: boolean; // Web Worker availability
181
Papa.NODE_STREAM_INPUT: 1; // Node.js stream input constant
182
Papa.LocalChunkSize: number; // Default local file chunk size (10MB)
183
Papa.RemoteChunkSize: number; // Default remote file chunk size (5MB)
184
Papa.DefaultDelimiter: string; // Default delimiter (',')
185
```
186
187
### Internal APIs (Development/Testing)
188
189
These classes are exposed for development and testing purposes but are not recommended for typical usage:
190
191
```javascript { .api }
192
Papa.Parser: class; // Core parser class
193
Papa.ParserHandle: class; // Parser with configuration handling
194
Papa.NetworkStreamer: class; // Network streaming implementation
195
Papa.FileStreamer: class; // File streaming implementation
196
Papa.StringStreamer: class; // String streaming implementation
197
Papa.ReadableStreamStreamer: class; // Node.js ReadableStream streaming
198
Papa.DuplexStreamStreamer: class; // Node.js duplex streaming (Node.js only)
199
```
200
201
**Note:** These internal APIs may change without notice. Use the main `Papa.parse()` and `Papa.unparse()` methods for production applications.
202
203
## Types
204
205
### ParseResult
206
207
```javascript { .api }
208
interface ParseResult {
209
data: any[][]; // Parsed data rows
210
errors: ParseError[]; // Parse errors encountered
211
meta: {
212
delimiter: string; // Detected or used delimiter
213
linebreak: string; // Detected or used line break
214
aborted: boolean; // Whether parsing was aborted
215
truncated: boolean; // Whether data was truncated
216
cursor: number; // Final parsing position
217
fields?: string[]; // Field names when header: true
218
};
219
}
220
```
221
222
### ParseError
223
224
```javascript { .api }
225
interface ParseError {
226
type: string; // Error type
227
code: string; // Error code
228
message: string; // Error description
229
row: number; // Row number where error occurred
230
}
231
```
232
233
### ParseConfig
234
235
```javascript { .api }
236
interface ParseConfig {
237
delimiter?: string; // Field delimiter
238
newline?: string; // Line terminator
239
quoteChar?: string; // Quote character
240
escapeChar?: string; // Escape character
241
header?: boolean; // First row contains headers
242
transformHeader?: (header: string) => string; // Transform header names
243
dynamicTyping?: boolean | object | ((field: string) => boolean); // Auto-convert types
244
preview?: number; // Parse only first N rows
245
encoding?: string; // Character encoding (Node.js)
246
worker?: boolean; // Use web worker
247
comments?: string | boolean; // Comment character
248
step?: (result: ParseResult, parser: any) => void; // Row callback
249
complete?: (result: ParseResult) => void; // Completion callback
250
error?: (error: ParseError) => void; // Error callback
251
download?: boolean; // Download from URL
252
downloadRequestHeaders?: object; // Request headers
253
downloadRequestBody?: string | FormData; // Request body
254
skipEmptyLines?: boolean | 'greedy'; // Skip empty lines behavior
255
chunk?: (result: ParseResult, parser: any) => void; // Chunk callback
256
chunkSize?: number; // Chunk size in bytes
257
fastMode?: boolean; // Fast parsing mode
258
beforeFirstChunk?: (chunk: string) => string; // Pre-process chunk
259
withCredentials?: boolean; // Include credentials
260
transform?: (value: string, field: string | number) => any; // Transform values
261
delimitersToGuess?: string[]; // Delimiters for auto-detection
262
}
263
```
264
265
### UnparseConfig
266
267
```javascript { .api }
268
interface UnparseConfig {
269
quotes?: boolean | boolean[] | ((value: any, columnIndex: number) => boolean); // Quote behavior
270
quoteChar?: string; // Quote character
271
escapeChar?: string; // Escape character
272
delimiter?: string; // Field delimiter
273
header?: boolean; // Include header row
274
newline?: string; // Line terminator
275
skipEmptyLines?: boolean | 'greedy'; // Skip empty lines
276
columns?: string[]; // Column order
277
escapeFormulae?: boolean; // Escape spreadsheet formulas
278
}
279
```
280
281
### UnparseObject
282
283
```javascript { .api }
284
interface UnparseObject {
285
fields: string[]; // Column headers
286
data: any[][]; // Data rows
287
}
288
```