@konstit/csv 0.4.1 → 0.4.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +136 -463
- package/dist/api.d.ts +356 -21
- package/dist/api.js +64 -93
- package/dist/batches.d.ts +291 -0
- package/dist/batches.js +72 -43
- package/dist/file-stream.d.ts +2 -2
- package/dist/file-stream.js +5 -2
- package/dist/files.d.ts +148 -2
- package/dist/files.js +30 -24
- package/dist/filter.d.ts +82 -0
- package/dist/latin1-rows.d.ts +3 -0
- package/dist/latin1-rows.js +84 -0
- package/dist/materialize-field.d.ts +1 -0
- package/dist/materialize-field.js +26 -0
- package/dist/native.d.ts +29 -0
- package/dist/native.js +44 -3
- package/dist/normalize.d.ts +18 -1
- package/dist/normalize.js +10 -0
- package/dist/options-snapshot.d.ts +3 -0
- package/dist/options-snapshot.js +50 -0
- package/dist/options.d.ts +44 -3
- package/dist/parser.d.ts +307 -1
- package/dist/parser.js +121 -8
- package/dist/strict-schema.d.ts +1 -1
- package/dist/strict-schema.js +4 -1
- package/dist/types.d.ts +435 -67
- package/dist/worker-count.d.ts +33 -1
- package/dist/worker-count.js +6 -1
- package/dist/worker-pool.d.ts +77 -1
- package/dist/worker-pool.js +11 -3
- package/dist/worker-rows.d.ts +31 -3
- package/dist/worker-rows.js +11 -2
- package/dist/workers/count.worker.js +13 -26
- package/dist/workers/rows.worker.js +23 -52
- package/package.json +23 -10
- package/prebuilds/darwin-arm64/libcsv_native.dylib +0 -0
- package/prebuilds/darwin-x64/libcsv_native.dylib +0 -0
- package/prebuilds/linux-x64/libcsv_native.so +0 -0
- package/prebuilds/manifest.json +8 -8
- package/prebuilds/provenance/darwin-arm64.json +1 -1
- package/prebuilds/provenance/darwin-x64.json +1 -1
- package/prebuilds/provenance/linux-x64.json +1 -1
package/README.md
CHANGED
|
@@ -1,554 +1,227 @@
|
|
|
1
1
|
# @konstit/csv
|
|
2
2
|
|
|
3
|
-
A
|
|
4
|
-
columns, apply composable filters, and process data in parallel without loading the complete dataset into memory.
|
|
3
|
+
A CSV toolkit for Bun with native parsing, streaming file access, filtering, and column selection.
|
|
5
4
|
|
|
6
|
-
|
|
5
|
+
[Quick start](#quick-start) · [Choose an API](#choose-an-api) · [CLI](#cli) · [Documentation](#documentation)
|
|
7
6
|
|
|
8
|
-
- Stream
|
|
9
|
-
-
|
|
10
|
-
-
|
|
11
|
-
-
|
|
12
|
-
- Compose nested native filters with `csv.all()`, `csv.any()`, and `csv.not()`.
|
|
13
|
-
- Process file shards in parallel with Bun workers or reuse workers through `csv.workerPool()`.
|
|
14
|
-
- Find CSV-safe split offsets without breaking quoted records or embedded newlines.
|
|
15
|
-
- Stream gzip, deflate, deflate-raw, Brotli, Zstandard, and ZIP input into serial APIs.
|
|
16
|
-
- Select an exact ZIP entry or use `entry: '*'` when the archive contains exactly one file.
|
|
17
|
-
- Detect comma, tab, semicolon, pipe, colon, caret, and tilde delimiters for serial file operations.
|
|
18
|
-
- Decode UTF-8 and Latin-1 input and emit UTF-8 strings.
|
|
19
|
-
- Validate strict quote syntax, fixed column counts, headers, and minimum data-row counts.
|
|
20
|
-
- Use typed option helpers, immutable filters, and explicit resource disposal from TypeScript.
|
|
21
|
-
- Run native C++20 parsing with AVX2 on x64 and NEON on ARM64.
|
|
7
|
+
- Stream large files in batches, or parse a buffer you already have in memory.
|
|
8
|
+
- Filter records and select columns before materializing results as JavaScript rows.
|
|
9
|
+
- Read compressed input, detect delimiters, and decode UTF-8 or Latin-1 files.
|
|
10
|
+
- Use native batches and reusable views for low-allocation access, or workers for parallel file processing.
|
|
22
11
|
|
|
23
|
-
##
|
|
12
|
+
## Installation
|
|
24
13
|
|
|
25
|
-
|
|
26
|
-
`bun install`, a fresh clone can run the Bun API, examples, and tests without compiling native code.
|
|
14
|
+
Requires **Bun `^1.4.0`**. Published packages include native libraries for these targets:
|
|
27
15
|
|
|
28
|
-
|
|
16
|
+
| Operating system | Architecture | CPU requirement |
|
|
17
|
+
| ---------------- | ------------ | --------------- |
|
|
18
|
+
| macOS 13+ | ARM64 | NEON |
|
|
19
|
+
| macOS 13+ | x64 | AVX2 |
|
|
20
|
+
| Linux | x64 | AVX2 |
|
|
29
21
|
|
|
30
22
|
```sh
|
|
31
|
-
bun
|
|
32
|
-
bun run build:native
|
|
33
|
-
bun run stage:native
|
|
23
|
+
bun add @konstit/csv
|
|
34
24
|
```
|
|
35
25
|
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
The downloaded sources are reused from `.cache/fetchcontent/`.
|
|
26
|
+
No native build is needed on supported targets. For building from source, see
|
|
27
|
+
[Contributing](https://github.com/Konstit-Engenharia/csv-parser/blob/main/CONTRIBUTING.md).
|
|
39
28
|
|
|
40
|
-
|
|
41
|
-
builds both `darwin-arm64` and `darwin-x64`. The FFI loader uses the tracked library under
|
|
42
|
-
`prebuilds/<platform>-<arch>/` by default. Set `CSV_NATIVE_LIBRARY_PATH` to an absolute library path to test a specific
|
|
43
|
-
local build. Target-specific and legacy build paths remain development fallbacks when no tracked prebuild exists.
|
|
29
|
+
## Quick start
|
|
44
30
|
|
|
45
|
-
|
|
31
|
+
Parse a buffer with `await csv.parse()`. Save this example as `parse.ts`:
|
|
46
32
|
|
|
47
|
-
```
|
|
48
|
-
|
|
49
|
-
```
|
|
50
|
-
|
|
51
|
-
The command caches an Ubuntu 24.04 image with Clang, CMake, and Ninja, mounts the repository at `/work`, builds the
|
|
52
|
-
existing `linux-x64-release` preset, and stages `prebuilds/linux-x64/libcsv_native.so`.
|
|
53
|
-
|
|
54
|
-
Tracked prebuilds are the native release inputs. Use the manual `Update prebuilds` workflow to rebuild and test all
|
|
55
|
-
targets. The workflow records the runner and toolchain, signs each binary with a GitHub build attestation, and creates one
|
|
56
|
-
`tracked-prebuilds-<commit>` artifact. Download that artifact, replace `prebuilds/`, and commit the result. Run this
|
|
57
|
-
workflow once before the first release that uses this policy because the existing binaries have no build attestations.
|
|
33
|
+
```ts
|
|
34
|
+
import { csv } from '@konstit/csv';
|
|
58
35
|
|
|
59
|
-
|
|
60
|
-
|
|
36
|
+
const input = Buffer.from('id,name,state\n1,Ada,SP\n2,Grace,RJ\n');
|
|
37
|
+
const rows = await csv.parse(input);
|
|
61
38
|
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
39
|
+
console.log(rows);
|
|
40
|
+
// [
|
|
41
|
+
// ['id', 'name', 'state'],
|
|
42
|
+
// ['1', 'Ada', 'SP'],
|
|
43
|
+
// ['2', 'Grace', 'RJ'],
|
|
44
|
+
// ]
|
|
65
45
|
```
|
|
66
46
|
|
|
67
|
-
This local route produces checksum metadata only. Release publication requires the attested workflow output.
|
|
68
|
-
|
|
69
|
-
Normal CI verifies and tests the tracked Linux prebuild without compiling native code. A separate `Native source`
|
|
70
|
-
workflow builds and tests Linux x64 only when native source or build files change. Package release jobs do not rebuild
|
|
71
|
-
native code. Release publication also verifies that each committed binary was signed by the `Update prebuilds` workflow
|
|
72
|
-
and that its attested source inputs match the release commit.
|
|
73
|
-
|
|
74
|
-
The supported native targets are Clang C++20 builds for macOS ARM64/x64 and Linux x64. ARM64 requires NEON, and x64
|
|
75
|
-
requires AVX2. CPUs without those instruction sets are not supported. Target-specific configuration is available through
|
|
76
|
-
CMake presets, for example:
|
|
77
|
-
|
|
78
47
|
```sh
|
|
79
|
-
|
|
80
|
-
cmake --build --preset darwin-arm64-release
|
|
81
|
-
cmake --preset linux-x64-sanitize
|
|
82
|
-
cmake --build --preset linux-x64-sanitize
|
|
83
|
-
ctest --preset linux-x64-sanitize
|
|
48
|
+
bun parse.ts
|
|
84
49
|
```
|
|
85
50
|
|
|
86
|
-
|
|
51
|
+
Each row is an array of strings. Headers remain ordinary records, and numeric-looking fields remain strings.
|
|
52
|
+
The default delimiter is a comma and the default encoding is UTF-8.
|
|
87
53
|
|
|
88
|
-
|
|
89
|
-
native library not found. Run: bun run build:native
|
|
90
|
-
```
|
|
54
|
+
## Stream a file
|
|
91
55
|
|
|
92
|
-
|
|
93
|
-
Bun's transpiler for runtime JavaScript, and uses TypeScript for declarations. It does not rebuild native code. The
|
|
94
|
-
JavaScript and declarations are written to `dist/`. The `Package` workflow packs the tracked prebuilds once, attests the
|
|
95
|
-
tarball, and smoke-tests that exact file on Linux x64 and macOS ARM64/x64. Run the workflow with a release tag to create a
|
|
96
|
-
draft release, attach the tested tarball, publish the immutable release, and publish the same tarball through the protected
|
|
97
|
-
`npm-publish` environment. Leave the release tag empty to build and test without publishing.
|
|
56
|
+
For files that do not fit in memory, use `csv.rows()`. Create `data.csv` with the same sample data:
|
|
98
57
|
|
|
99
|
-
|
|
58
|
+
```csv
|
|
59
|
+
id,name,state
|
|
60
|
+
1,Ada,SP
|
|
61
|
+
2,Grace,RJ
|
|
62
|
+
```
|
|
100
63
|
|
|
101
64
|
```ts
|
|
102
65
|
import { csv } from '@konstit/csv';
|
|
103
66
|
|
|
104
|
-
const
|
|
105
|
-
|
|
106
|
-
for await (
|
|
107
|
-
const rows of csv.rows(path, {
|
|
108
|
-
delimiter: ';',
|
|
109
|
-
columns: [0, 1, 2],
|
|
110
|
-
chunkSize: 8 * 1024 * 1024,
|
|
111
|
-
})
|
|
112
|
-
) {
|
|
113
|
-
for (const row of rows) {
|
|
67
|
+
for await (const batch of csv.rows('data.csv')) {
|
|
68
|
+
for (const row of batch) {
|
|
114
69
|
console.log(row);
|
|
115
70
|
}
|
|
116
71
|
}
|
|
117
72
|
```
|
|
118
73
|
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
### Large corpus files
|
|
122
|
-
|
|
123
|
-
The files in `corpus/large/` are too large to commit to this repository. Download and prepare them with Bun. The script
|
|
124
|
-
requires `unzip` and skips files that already exist:
|
|
125
|
-
|
|
126
|
-
```sh
|
|
127
|
-
bun scripts/download-large-corpus.ts
|
|
128
|
-
```
|
|
129
|
-
|
|
130
|
-
- `example.csv` is an approximately 6 GB ISO-8859-1-encoded Brazilian government data dump after extraction. Download
|
|
131
|
-
it from [Arquivos Receita](https://arquivos.receitafederal.gov.br/public.php/dav/files/gn672Ad4CF8N6TK/Dados/Cadastros/CNPJ/2026-08/Estabelecimentos0.zip).
|
|
132
|
-
- `formatted_addresses_tagged.random.tsv.gz` is part of the libpostal training data and remains compressed for the
|
|
133
|
-
benchmarks. Download it from the
|
|
134
|
-
[Internet Archive](https://archive.org/download/libpostal-parser-training-data-20170304/formatted_addresses_tagged.random.tsv.gz).
|
|
74
|
+
Each iteration yields a **batch of rows**, so use the inner loop to process individual records. Process batches as
|
|
75
|
+
they arrive to avoid collecting the complete file in memory. The header is returned as the first row.
|
|
135
76
|
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
## Library API
|
|
139
|
-
|
|
140
|
-
Import the `csv` namespace for file-oriented helpers:
|
|
77
|
+
To count records without materializing rows:
|
|
141
78
|
|
|
142
79
|
```ts
|
|
143
80
|
import { csv } from '@konstit/csv';
|
|
144
81
|
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
const selected = csv.rows('data.csv', {
|
|
148
|
-
delimiter: ';',
|
|
149
|
-
columns: [0, 2],
|
|
150
|
-
where: csv.all(
|
|
151
|
-
csv.column(2).isOneOf(['SP', 'RJ']),
|
|
152
|
-
csv.column(1).startsWith('A'),
|
|
153
|
-
csv.column(3).hasMatch(/^[0-9]{5}-[0-9]{3}$/),
|
|
154
|
-
),
|
|
155
|
-
});
|
|
156
|
-
|
|
157
|
-
const compressed = csv.rows('data.csv.gz', {
|
|
158
|
-
compression: 'auto',
|
|
159
|
-
delimiter: 'auto',
|
|
160
|
-
});
|
|
161
|
-
|
|
162
|
-
const zipped = csv.rows('export.zip', {
|
|
163
|
-
compression: { format: 'zip', entry: 'data/export.csv' },
|
|
164
|
-
});
|
|
82
|
+
console.log(await csv.count('data.csv')); // 3, including the header
|
|
165
83
|
```
|
|
166
84
|
|
|
167
|
-
|
|
85
|
+
## Choose an API
|
|
168
86
|
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
- `csv.
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
87
|
+
| Task | API | Result or lifecycle |
|
|
88
|
+
| ---------------------------- | -------------------------------------------------- | ------------------------------------------------------ |
|
|
89
|
+
| Parse an in-memory buffer | `await csv.parse(buffer)` | All rows as arrays of strings |
|
|
90
|
+
| Stream a file | `csv.rows(path)` | Async stream of row batches |
|
|
91
|
+
| Count records | `await csv.count(path)` | Record count, optionally filtered |
|
|
92
|
+
| Access native batches | `csv.withBatches(path, options, callback)` | Callback with automatic batch disposal |
|
|
93
|
+
| Reuse row or columnar views | `csv.withRowViews()` / `csv.withColumnarBatches()` | Synchronous callback; views are scoped to the callback |
|
|
94
|
+
| Process a file in parallel | `csv.rows()` / `csv.count()` with `workerCount` | Worker-based processing of an uncompressed file |
|
|
95
|
+
| Repeat parallel operations | `csv.workerPool(path, options)` | Reusable pool that must be closed |
|
|
96
|
+
| Supply your own input chunks | `NativeCsvParser` | Manual parser and batch disposal |
|
|
178
97
|
|
|
179
|
-
|
|
98
|
+
Start with `csv.rows()` for streaming records. Use batches or views when you need byte access or lower allocation
|
|
99
|
+
overhead. Parallel row output is not globally ordered; workers require an uncompressed file, a fixed delimiter, and
|
|
100
|
+
non-strict parsing. See the [API guide](https://github.com/Konstit-Engenharia/csv-parser/blob/main/docs/api.md)
|
|
101
|
+
for options and resource lifetimes.
|
|
180
102
|
|
|
181
|
-
|
|
182
|
-
The selected column is reusable, and one filter can be reused across row, count, and worker APIs:
|
|
103
|
+
## Common operations
|
|
183
104
|
|
|
184
|
-
|
|
185
|
-
const state = csv.column(2);
|
|
186
|
-
const isSP = state.equals('SP');
|
|
187
|
-
const isSouthEast = state.isOneOf(['SP', 'RJ']);
|
|
105
|
+
These examples read the `data.csv` shown above.
|
|
188
106
|
|
|
189
|
-
|
|
190
|
-
await csv.count('data.csv', { where: isSouthEast, workerCount: 4 });
|
|
191
|
-
```
|
|
107
|
+
### Filter records and select columns
|
|
192
108
|
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
The `where` option accepts only filters created by this API; TypeScript object-literal predicates are not supported.
|
|
196
|
-
If a row does not contain the selected column, it does not match, including for `doesNotEqual` and `isNoneOf`.
|
|
197
|
-
Use `hasMatch()` for regular expressions:
|
|
109
|
+
Column indexes are zero-based **source column indexes**: `id` is `0`, `name` is `1`, and `state` is `2`.
|
|
110
|
+
Filters use source indexes even when output columns are reordered.
|
|
198
111
|
|
|
199
112
|
```ts
|
|
200
|
-
|
|
201
|
-
where: csv.column(1).hasMatch(/^ana$/iu),
|
|
202
|
-
});
|
|
203
|
-
```
|
|
204
|
-
|
|
205
|
-
Regex filters use statically linked RE2 and search the field. Use `^` and `$` for a full-field match. The supported flags
|
|
206
|
-
are `i`, `m`, `s`, and `u`. Unicode matching is enabled by default; `u` documents the JavaScript pattern intent. The
|
|
207
|
-
`g`, `d`, `y`, and `v` flags are rejected. RE2 does not support lookaround or backreferences. `hasMatch()` converts
|
|
208
|
-
JavaScript Unicode escapes and escaped `/` characters, then validates the RE2 expression immediately. A compiled
|
|
209
|
-
pattern is limited to 4096 UTF-8 bytes, and one operation can use at most 32 regex filters.
|
|
210
|
-
|
|
211
|
-
Use `csv.all()` when every child must match, `csv.any()` when at least one child must match, and `csv.not()` to negate
|
|
212
|
-
one child. Groups can be nested. `all` and `any` require at least one filter:
|
|
113
|
+
import { csv } from '@konstit/csv';
|
|
213
114
|
|
|
214
|
-
|
|
215
|
-
const
|
|
216
|
-
|
|
217
|
-
csv.column(2).equals('SP'),
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
115
|
+
for await (
|
|
116
|
+
const batch of csv.rows('data.csv', {
|
|
117
|
+
columns: [1, 0],
|
|
118
|
+
where: csv.column(2).equals('SP'),
|
|
119
|
+
})
|
|
120
|
+
) {
|
|
121
|
+
console.log(batch); // [['Ada', '1']]
|
|
122
|
+
}
|
|
222
123
|
```
|
|
223
124
|
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
true.
|
|
227
|
-
|
|
228
|
-
Serial file operations accept `compression: 'auto' | 'gzip' | 'deflate' | 'deflate-raw' | 'brotli' | 'zstd'`.
|
|
229
|
-
Decompression streams into the parser and does not buffer the complete file. `auto` reads at most four prefix bytes and
|
|
230
|
-
combines signatures with `.gz`, `.gzip`, `.zst`, `.zstd`, `.br`, `.zz`, `.zlib`, `.deflate`, or `.deflate-raw`.
|
|
231
|
-
Signature and extension mismatches fail. A `.deflate` file without a zlib wrapper requires explicit `deflate-raw`.
|
|
232
|
-
Compressed input does not support worker pools, parallel operations, or CSV byte-offset sharding.
|
|
125
|
+
The filter also applies to the header, which does not match `'SP'` here. Combine conditions with `csv.all()`,
|
|
126
|
+
`csv.any()`, and `csv.not()`. Filters support equality, membership, prefixes, and RE2 regular expressions.
|
|
233
127
|
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
`entry: '*'` to select the file when the archive contains exactly one file; directory entries are ignored. Archives
|
|
237
|
-
with zero or multiple files fail in this mode. Encrypted entries and compression methods other than stored and
|
|
238
|
-
DEFLATE fail. The defaults limit output to 64 GiB and the declared compression ratio to 1000. Use
|
|
239
|
-
`maxDecompressedBytes` and `maxCompressionRatio` to set lower application limits or to permit a larger trusted entry.
|
|
128
|
+
See [Filters](https://github.com/Konstit-Engenharia/csv-parser/blob/main/docs/api.md#filters) for matching rules
|
|
129
|
+
and supported regex syntax.
|
|
240
130
|
|
|
241
|
-
|
|
242
|
-
ignores separators inside quoted fields. It checks comma, tab, semicolon, pipe, colon, caret, and tilde. The `.csv`,
|
|
243
|
-
`.tsv`, `.tab`, and `.psv` extensions are confirmed hints, including before a compression extension such as `.gz`.
|
|
244
|
-
Empty, single-column, inconsistent, and ambiguous probes fail with an error. Omitted `delimiter` still means comma.
|
|
245
|
-
Automatic delimiter detection does not support in-memory parsing, workers, parallel operations, or byte-offset sharding.
|
|
131
|
+
### Read compressed files
|
|
246
132
|
|
|
247
|
-
|
|
248
|
-
exactly one character unless a serial file operation uses `auto`.
|
|
133
|
+
Create a gzip copy of the sample file:
|
|
249
134
|
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
`strict: true` validates RFC-style quote syntax for row materialization:
|
|
253
|
-
|
|
254
|
-
```ts
|
|
255
|
-
await csv.parse(Buffer.from('id,name\n1,"Ada'), { strict: true });
|
|
256
|
-
// throws: native CSV parser failed: strict CSV quote syntax error: unterminated quoted field
|
|
135
|
+
```sh
|
|
136
|
+
gzip -c data.csv > data.csv.gz
|
|
257
137
|
```
|
|
258
138
|
|
|
259
|
-
Strict mode also validates optional schema metadata during row parsing:
|
|
260
|
-
|
|
261
139
|
```ts
|
|
262
|
-
|
|
263
|
-
strict: true,
|
|
264
|
-
expectedHeaders: ['id', 'name'],
|
|
265
|
-
minDataRows: 1,
|
|
266
|
-
});
|
|
267
|
-
```
|
|
268
|
-
|
|
269
|
-
- `expectedHeaders` validates the first row exactly.
|
|
270
|
-
- `requireHeader` rejects empty input when a header row is required.
|
|
271
|
-
- `minDataRows` validates row count after the header row.
|
|
272
|
-
|
|
273
|
-
Strict mode currently covers row batches, `count()` without filters, `fixedColumns`, and row schema metadata. Projected
|
|
274
|
-
batches and count filters reject `strict: true` explicitly until they have strict native variants.
|
|
275
|
-
|
|
276
|
-
## Typed Options
|
|
277
|
-
|
|
278
|
-
Use the option factories when you want literal-preserving inference without repeating `satisfies` everywhere:
|
|
140
|
+
import { csv } from '@konstit/csv';
|
|
279
141
|
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
const rowOptions = defineRowsOptions({
|
|
290
|
-
columns,
|
|
291
|
-
delimiter: ';',
|
|
292
|
-
where: csv.column(1).equals('SP'),
|
|
293
|
-
});
|
|
294
|
-
|
|
295
|
-
const countOptions = defineCountOptions({
|
|
296
|
-
strict: true,
|
|
297
|
-
});
|
|
298
|
-
|
|
299
|
-
for await (const rows of csv.rows('data.csv', rowOptions)) {
|
|
300
|
-
console.log(rows);
|
|
142
|
+
for await (
|
|
143
|
+
const batch of csv.rows('data.csv.gz', {
|
|
144
|
+
compression: 'auto',
|
|
145
|
+
delimiter: 'auto',
|
|
146
|
+
})
|
|
147
|
+
) {
|
|
148
|
+
for (const row of batch) {
|
|
149
|
+
console.log(row);
|
|
150
|
+
}
|
|
301
151
|
}
|
|
302
|
-
|
|
303
|
-
console.log(await csv.count('data.csv', countOptions));
|
|
304
152
|
```
|
|
305
153
|
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
options supported by its native path.
|
|
154
|
+
Decompression streams into the parser. Serial file APIs support gzip, deflate, deflate-raw, Brotli, Zstandard,
|
|
155
|
+
and selected ZIP entries. Automatic delimiter detection is also available for serial files.
|
|
309
156
|
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
157
|
+
For a ZIP archive, select an entry with `compression: { format: 'zip', entry: 'data.csv' }`. See
|
|
158
|
+
[Compression](https://github.com/Konstit-Engenharia/csv-parser/blob/main/docs/api.md#compression-and-delimiter-detection)
|
|
159
|
+
for supported formats, detection rules, and limits.
|
|
313
160
|
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
Use batches when you need low allocation row access or byte ranges.
|
|
161
|
+
### Validate input
|
|
317
162
|
|
|
318
163
|
```ts
|
|
319
164
|
import { csv } from '@konstit/csv';
|
|
320
165
|
|
|
321
|
-
await csv.
|
|
322
|
-
|
|
323
|
-
{
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
rowIndex: row.rowIndex,
|
|
328
|
-
first: row.getPhysical(0),
|
|
329
|
-
bytes: row.bytes(0),
|
|
330
|
-
range: row.range(0),
|
|
331
|
-
selected: row.pickPhysical([0, 2]),
|
|
332
|
-
});
|
|
333
|
-
});
|
|
166
|
+
const rows = await csv.parse(
|
|
167
|
+
Buffer.from('id,name,state\n1,Ada,SP\n2,Grace,RJ\n'),
|
|
168
|
+
{
|
|
169
|
+
strict: true,
|
|
170
|
+
expectedHeaders: ['id', 'name', 'state'],
|
|
171
|
+
minDataRows: 1,
|
|
334
172
|
},
|
|
335
173
|
);
|
|
336
|
-
```
|
|
337
|
-
|
|
338
|
-
`row.get()`, `row.getPhysical()`, `row.pick()`, and `row.pickPhysical()` all read physical CSV column indexes.
|
|
339
|
-
If you requested projected columns elsewhere in the API, `row.selectedColumns` is metadata that lets you map projected
|
|
340
|
-
positions back to source columns.
|
|
341
174
|
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
```ts
|
|
345
|
-
for await (using batch of csv.batches('data.csv', { delimiter: ';' })) {
|
|
346
|
-
console.log(batch.rowCount);
|
|
347
|
-
}
|
|
175
|
+
console.log(rows.length); // 3
|
|
348
176
|
```
|
|
349
177
|
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
-
|
|
353
|
-
|
|
354
|
-
- `rowsInto(target, columns?)`
|
|
355
|
-
- `forEachRow(callback)`
|
|
356
|
-
- `data()`, `dataView()`
|
|
357
|
-
- `rowOffsets()`, `fieldOffsets()`
|
|
358
|
-
- `rowFieldCount(rowIndex)`
|
|
359
|
-
- `fieldRange(rowIndex, columnIndex)`
|
|
360
|
-
- `fieldBytes(rowIndex, columnIndex)`
|
|
361
|
-
- `fieldBuffer(rowIndex, columnIndex)`
|
|
362
|
-
- `fieldString(rowIndex, columnIndex)`
|
|
363
|
-
- `countWhereEquals(columnIndex, value)`
|
|
364
|
-
- `close()`
|
|
365
|
-
|
|
366
|
-
`rowOffsets()` and `fieldOffsets()` return `BigUint64Array`. Convert individual offsets to `number` only after checking
|
|
367
|
-
that they are within `Number.MAX_SAFE_INTEGER` and the associated backing data. `scanColumns()` supplies its
|
|
368
|
-
JavaScript-safe numeric ranges in a `Float64Array`.
|
|
369
|
-
|
|
370
|
-
## Manual Parser API
|
|
371
|
-
|
|
372
|
-
Use `NativeCsvParser` when you already own chunking:
|
|
373
|
-
|
|
374
|
-
```ts
|
|
375
|
-
import { NativeCsvParser } from '@konstit/csv';
|
|
376
|
-
|
|
377
|
-
using parser = new NativeCsvParser({ delimiter: ';' });
|
|
378
|
-
const rowsBuffer: string[][] = [];
|
|
379
|
-
|
|
380
|
-
using batch = parser.writeBatch(Buffer.from('1;Ana\n2;Bia\n'), true);
|
|
381
|
-
console.log(batch.rowsInto(rowsBuffer));
|
|
382
|
-
```
|
|
383
|
-
|
|
384
|
-
Always dispose parser-owned batches and the parser. `NativeCsvParser` supports row batches, projected batches, and direct
|
|
385
|
-
count filters.
|
|
386
|
-
|
|
387
|
-
Resource objects expose `close()`, `dispose()`, `closed`, and `Symbol.dispose`, so explicit-resource-management syntax works
|
|
388
|
-
in Bun:
|
|
389
|
-
|
|
390
|
-
```ts
|
|
391
|
-
using parser = new NativeCsvParser({ delimiter: ';' });
|
|
392
|
-
using batch = parser.writeBatch(Buffer.from('1;Ana\n'), true);
|
|
393
|
-
console.log(batch.rows());
|
|
394
|
-
```
|
|
178
|
+
Strict mode validates quote syntax and can check header and row-count requirements. It supports column selection
|
|
179
|
+
with `csv.parse()` and `csv.rows()`, but cannot be combined with filters or workers. See
|
|
180
|
+
[Strict validation](https://github.com/Konstit-Engenharia/csv-parser/blob/main/docs/api.md#strict-validation)
|
|
181
|
+
for supported combinations.
|
|
395
182
|
|
|
396
183
|
## CLI
|
|
397
184
|
|
|
398
|
-
Count
|
|
185
|
+
Count records or emit the first records as newline-delimited JSON:
|
|
399
186
|
|
|
400
187
|
```sh
|
|
401
188
|
bunx @konstit/csv count data.csv
|
|
402
|
-
|
|
403
|
-
```
|
|
404
|
-
|
|
405
|
-
With Bun 1.4 or newer, install the command globally and use its shorter form:
|
|
406
|
-
|
|
407
|
-
```sh
|
|
408
|
-
bun add --global @konstit/csv
|
|
409
|
-
csv count data.csv
|
|
410
|
-
```
|
|
411
|
-
|
|
412
|
-
Stream parsed records as normalized UTF-8 CSV:
|
|
413
|
-
|
|
414
|
-
```sh
|
|
415
|
-
csv lines data.csv
|
|
416
|
-
csv lines data.csv --limit 10
|
|
417
|
-
csv lines data.csv --json --limit 10
|
|
418
|
-
csv lines data.csv --columns 0,2 --where-eq 3=active --limit 10
|
|
419
|
-
csv lines input.tsv --delimiter $'\t' --output-delimiter ',' > selected.csv
|
|
420
|
-
```
|
|
421
|
-
|
|
422
|
-
`--limit N` stops after matching output record `N`, numbered from 1. A quoted field can contain embedded newlines, but
|
|
423
|
-
its enclosing record counts as one. The header counts only when it is emitted. Early stop validates only the consumed
|
|
424
|
-
input prefix, so `--limit` cannot be combined with `--min-data-rows`. With `--strict`, a limit requires a fixed input
|
|
425
|
-
delimiter and either an omitted chunk size or `--chunk-size 1`; the CLI uses one-byte chunks to avoid strict read-ahead.
|
|
426
|
-
`--strict` with `--limit` cannot use `--compression`, including `auto`.
|
|
427
|
-
|
|
428
|
-
`lines` writes normalized UTF-8 CSV, not the original source bytes. The default output uses commas, LF record endings,
|
|
429
|
-
and standard quote escaping. Use `--output-delimiter` to select another safe ASCII delimiter. `--columns` selects the
|
|
430
|
-
output fields and their order. Filters still use the original input column indexes.
|
|
431
|
-
|
|
432
|
-
Use `--json` for newline-delimited JSON. Each output line is one array of strings, including the header when it is
|
|
433
|
-
emitted. JSON output escapes embedded field newlines and quotes. Stdout contains only JSON records. Diagnostics remain
|
|
434
|
-
on stderr. `--json` cannot be combined with `--output-delimiter`.
|
|
189
|
+
# 3
|
|
435
190
|
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
filter values are strings; use the TypeScript API for `workerCount` and binary `Buffer` or `Uint8Array` values.
|
|
440
|
-
|
|
441
|
-
```sh
|
|
442
|
-
csv count data.csv --delimiter ';' --where-eq 2=SP
|
|
443
|
-
csv count data.csv --where-neq 2=SP
|
|
444
|
-
csv count data.csv --where-in 2=SP --where-in 2=RJ --where-prefix 1=A
|
|
445
|
-
csv count data.csv --where-noin 2=SP --where-noin 2=RJ
|
|
446
|
-
csv count data.csv --where-regex '1=/^A/i'
|
|
447
|
-
csv lines data.csv --where-in 2=SP --where-in 2=RJ --limit 25
|
|
448
|
-
csv lines data.csv --columns 0,1 --json --limit 25
|
|
191
|
+
bunx @konstit/csv lines data.csv --json --limit 2
|
|
192
|
+
# ["id","name","state"]
|
|
193
|
+
# ["1","Ada","SP"]
|
|
449
194
|
```
|
|
450
195
|
|
|
451
|
-
|
|
196
|
+
Without `--json`, `lines` writes normalized UTF-8 CSV. Both commands support column filters; `lines` also supports
|
|
197
|
+
column selection. Use `bunx @konstit/csv lines --help` or read the
|
|
198
|
+
[CLI guide](https://github.com/Konstit-Engenharia/csv-parser/blob/main/docs/cli.md) for flags and output behavior.
|
|
452
199
|
|
|
453
|
-
|
|
454
|
-
csv lines corpus/large/example.csv --delimiter ';' --limit 10
|
|
455
|
-
csv lines corpus/large/example.csv --delimiter ';' --columns 0,1,2 --limit 100 > sample.csv
|
|
456
|
-
```
|
|
200
|
+
## Documentation
|
|
457
201
|
|
|
458
|
-
|
|
459
|
-
|
|
202
|
+
- [API guide](https://github.com/Konstit-Engenharia/csv-parser/blob/main/docs/api.md): filters, encoding, compression,
|
|
203
|
+
validation, typed options, batches, views, workers, and manual parsing.
|
|
204
|
+
- [CLI guide](https://github.com/Konstit-Engenharia/csv-parser/blob/main/docs/cli.md): commands, filters, output formats,
|
|
205
|
+
and option constraints.
|
|
206
|
+
- [Benchmarks](https://github.com/Konstit-Engenharia/csv-parser/blob/main/docs/benchmarks.md): datasets, commands,
|
|
207
|
+
recorded measurements, and their limitations.
|
|
208
|
+
- [Contributing](https://github.com/Konstit-Engenharia/csv-parser/blob/main/CONTRIBUTING.md): repository setup, examples,
|
|
209
|
+
validation, native development, and releases.
|
|
460
210
|
|
|
461
|
-
|
|
462
|
-
csv count data.csv --where '{"all":[{"any":[{"column":2,"equals":"SP"},{"column":2,"equals":"RJ"}]},{"not":{"column":1,"startsWith":"B"}}]}'
|
|
463
|
-
```
|
|
211
|
+
## Performance
|
|
464
212
|
|
|
465
|
-
|
|
213
|
+
The parser uses native C++ with AVX2 on x64 and NEON on ARM64. Filtering and counting can avoid creating JavaScript
|
|
214
|
+
rows for records you do not need. The [benchmark guide](https://github.com/Konstit-Engenharia/csv-parser/blob/main/docs/benchmarks.md)
|
|
215
|
+
records a full-file comparison, including memory use and reproduction commands. Results depend on the workload,
|
|
216
|
+
hardware, and selected API.
|
|
466
217
|
|
|
467
|
-
##
|
|
218
|
+
## Contributing
|
|
468
219
|
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
bun run example:api:rows
|
|
472
|
-
bun run example:api:count
|
|
473
|
-
bun run example:api:batches
|
|
474
|
-
bun run example:api:typed-options
|
|
475
|
-
bun run example:api:strict-options
|
|
476
|
-
bun run example:api:worker-count
|
|
477
|
-
bun run example:api:worker-rows
|
|
478
|
-
bun run example:api:worker-pool
|
|
479
|
-
bun run example:api:shards
|
|
480
|
-
```
|
|
481
|
-
|
|
482
|
-
Example environment variables:
|
|
483
|
-
|
|
484
|
-
- `CSV_EXAMPLE_FILE`: Input file for examples. It defaults to `CSV_BENCH_FILE`, then
|
|
485
|
-
`corpus/large/example.csv`.
|
|
486
|
-
- `CSV_BENCH_FILE`: Input file for benchmarks. It also provides the example input when `CSV_EXAMPLE_FILE` is not set.
|
|
487
|
-
- `CSV_EXAMPLE_DELIMITER`: Field delimiter for examples. It defaults to `CSV_BENCH_DELIMITER`, then `;`.
|
|
488
|
-
- `CSV_BENCH_DELIMITER`: Field delimiter for benchmarks. It also provides the example delimiter when
|
|
489
|
-
`CSV_EXAMPLE_DELIMITER` is not set.
|
|
490
|
-
- `CSV_EXAMPLE_CHUNK_SIZE`: Number of bytes read per chunk by examples. It defaults to `CSV_BENCH_CHUNK_SIZE`, then
|
|
491
|
-
8 MiB.
|
|
492
|
-
- `CSV_BENCH_CHUNK_SIZE`: Number of bytes read per chunk by benchmarks. It also provides the example chunk size when
|
|
493
|
-
`CSV_EXAMPLE_CHUNK_SIZE` is not set.
|
|
494
|
-
- `CSV_EXAMPLE_COLUMNS`: Comma-separated, zero-based column indexes selected by examples. The default is `0,1,2`.
|
|
495
|
-
- `CSV_EXAMPLE_LIMIT`: Maximum number of rows printed by examples. It defaults to `CSV_PRINT_ROWS`, then `10`. This
|
|
496
|
-
limits output, but some examples can still parse more rows.
|
|
497
|
-
- `CSV_PRINT_ROWS`: Fallback output limit used when `CSV_EXAMPLE_LIMIT` is not set.
|
|
498
|
-
- `CSV_EXAMPLE_FILTER_COLUMN`: Zero-based column index used by examples with a filter. It defaults to the first selected
|
|
499
|
-
column, usually `0`.
|
|
500
|
-
- `CSV_EXAMPLE_FILTER_VALUE`: Match value used by examples with a filter. If it is not set, those examples do not apply
|
|
501
|
-
the optional filter.
|
|
502
|
-
|
|
503
|
-
## Validation
|
|
504
|
-
|
|
505
|
-
```sh
|
|
506
|
-
bun run test
|
|
507
|
-
bun run lint
|
|
508
|
-
```
|
|
509
|
-
|
|
510
|
-
Install the repository's pre-push hook once per clone:
|
|
511
|
-
|
|
512
|
-
```sh
|
|
513
|
-
bun run hooks:install
|
|
514
|
-
```
|
|
515
|
-
|
|
516
|
-
Before every push, the hook builds the host's native libraries and the Linux x64 library, checks TypeScript and C++
|
|
517
|
-
formatting, runs the linters and type checker, runs the Bun test suite against the new host build, and runs the native
|
|
518
|
-
test suite. Building Linux x64 requires Docker to be installed and running. Run the same checks manually with
|
|
519
|
-
`bun run prepush`. The hook only validates the push. It does not publish packages.
|
|
520
|
-
|
|
521
|
-
### Full-file filtered materialization benchmark
|
|
522
|
-
|
|
523
|
-
This benchmark compares `csv.rows()` with `csv-parser` after `iconv-lite` decodes ISO-8859-1 input. Both commands parse
|
|
524
|
-
the complete `corpus/large/example.csv` file, apply equivalent column filters, and materialize every field in each
|
|
525
|
-
matching row. `@konstit/csv` applies the filters in native code; the `csv-parser` pipeline applies them to its
|
|
526
|
-
materialized JavaScript rows.
|
|
527
|
-
|
|
528
|
-
```sh
|
|
529
|
-
bun run bench:csv-parser:example
|
|
530
|
-
```
|
|
531
|
-
|
|
532
|
-
In the recorded `hyperfine -r 2` result, both commands produced 11,516,955 rows, 345,508,650 cells, and 1,808,786,228
|
|
533
|
-
characters from the 6,780,467,695-byte corpus:
|
|
534
|
-
|
|
535
|
-
| Implementation | Mean time | Throughput | Relative result |
|
|
536
|
-
| -------------------------------- | --------: | ----------: | ---------------: |
|
|
537
|
-
| `@konstit/csv` with `csv.rows()` | 45.223 s | 143.0 MiB/s | **2.32× faster** |
|
|
538
|
-
| `iconv-lite` + `csv-parser` | 104.835 s | 61.7 MiB/s | Baseline |
|
|
539
|
-
|
|
540
|
-
For this workload, `@konstit/csv` was 2.32× faster and completed in 56.9% less time. This result contains only two runs
|
|
541
|
-
on one machine, so use it as a measured workload result, not a universal performance guarantee. Full-file benchmarks
|
|
542
|
-
are long CPU-bound runs. Run them separately when comparing numbers. `hyperfine` must be available on `PATH`.
|
|
543
|
-
|
|
544
|
-
Small correctness/performance smoke:
|
|
545
|
-
|
|
546
|
-
```sh
|
|
547
|
-
bun run bench:regression-smoke
|
|
548
|
-
bun run bench:csv-parser:guard
|
|
549
|
-
```
|
|
220
|
+
See [Contributing](https://github.com/Konstit-Engenharia/csv-parser/blob/main/CONTRIBUTING.md) to run the project locally,
|
|
221
|
+
validate changes, or rebuild the native libraries.
|
|
550
222
|
|
|
551
223
|
## License
|
|
552
224
|
|
|
553
|
-
MIT © 2026 KONSTIT ENGENHARIA E TECNOLOGIA LTDA. See
|
|
554
|
-
[
|
|
225
|
+
MIT © 2026 KONSTIT ENGENHARIA E TECNOLOGIA LTDA. See
|
|
226
|
+
[LICENSE](https://github.com/Konstit-Engenharia/csv-parser/blob/main/LICENSE) and
|
|
227
|
+
[third-party notices](https://github.com/Konstit-Engenharia/csv-parser/blob/main/THIRD_PARTY_NOTICES.md).
|