@konstit/csv 0.4.1 → 0.5.0
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 +152 -463
- package/THIRD_PARTY_NOTICES.md +7 -1
- package/dist/api.d.ts +169 -44
- package/dist/api.js +75 -368
- package/dist/batches.d.ts +250 -7
- package/dist/batches.js +135 -83
- package/dist/cli-command.d.ts +7 -0
- package/dist/cli-command.js +350 -0
- package/dist/cli-schema.d.ts +111 -0
- package/dist/cli-schema.js +219 -0
- package/dist/cli.js +2 -604
- package/dist/file-stream.d.ts +57 -2
- package/dist/file-stream.js +244 -36
- package/dist/files.d.ts +149 -3
- package/dist/files.js +37 -29
- package/dist/filter.d.ts +80 -0
- package/dist/format-bytes.d.ts +1 -0
- package/dist/format-bytes.js +11 -0
- package/dist/index.d.ts +3 -3
- package/dist/index.js +2 -14
- package/dist/inspect-file.d.ts +12 -0
- package/dist/inspect-file.js +88 -0
- package/dist/latin1-rows.d.ts +5 -0
- package/dist/latin1-rows.js +122 -0
- package/dist/materialize-field.d.ts +3 -0
- package/dist/materialize-field.js +31 -0
- package/dist/native.d.ts +51 -2
- package/dist/native.js +43 -4
- package/dist/normalize.d.ts +32 -2
- package/dist/normalize.js +51 -2
- package/dist/options-snapshot.d.ts +3 -0
- package/dist/options-snapshot.js +51 -0
- package/dist/options.d.ts +25 -10
- package/dist/options.js +0 -6
- package/dist/parser.d.ts +309 -4
- package/dist/parser.js +128 -31
- package/dist/strict-schema.d.ts +5 -3
- package/dist/strict-schema.js +4 -1
- package/dist/types.d.ts +355 -121
- package/dist/zip-reader.d.ts +11 -1
- package/dist/zip-reader.js +12 -3
- package/package.json +44 -29
- 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 +9 -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/dist/worker-count.d.ts +0 -2
- package/dist/worker-count.js +0 -96
- package/dist/worker-factory.d.ts +0 -3
- package/dist/worker-factory.js +0 -9
- package/dist/worker-filter.d.ts +0 -29
- package/dist/worker-filter.js +0 -46
- package/dist/worker-module.d.ts +0 -1
- package/dist/worker-module.js +0 -4
- package/dist/worker-pool.d.ts +0 -17
- package/dist/worker-pool.js +0 -290
- package/dist/worker-rows.d.ts +0 -8
- package/dist/worker-rows.js +0 -118
- package/dist/workers/count.worker.d.ts +0 -1
- package/dist/workers/count.worker.js +0 -49
- package/dist/workers/rows.worker.d.ts +0 -1
- package/dist/workers/rows.worker.js +0 -85
package/README.md
CHANGED
|
@@ -1,554 +1,243 @@
|
|
|
1
1
|
# @konstit/csv
|
|
2
2
|
|
|
3
|
-
A high-performance CSV
|
|
4
|
-
columns, apply composable filters, and process data in parallel without loading the complete dataset into memory.
|
|
3
|
+
A high-performance streaming CSV parsing library for Bun using a native C++ parser with SIMD acceleration (AVX2/NEON), 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
|
-
|
|
13
|
-
-
|
|
14
|
-
-
|
|
15
|
-
-
|
|
16
|
-
-
|
|
17
|
-
-
|
|
18
|
-
-
|
|
19
|
-
-
|
|
20
|
-
-
|
|
21
|
-
-
|
|
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
|
+
- Reads [RFC 4180](https://www.rfc-editor.org/info/rfc4180) CSV. Set `strict: true` to reject malformed quoting.
|
|
10
|
+
- Tested against [csv-spectrum](https://github.com/maxogden/csv-spectrum), selected [W3C CSVW](https://w3c.github.io/csvw/tests/) cases,
|
|
11
|
+
and fixtures derived from [csvkit](https://github.com/wireservice/csvkit).
|
|
12
|
+
- Stream compressed files:
|
|
13
|
+
- zip
|
|
14
|
+
- gzip
|
|
15
|
+
- brotli
|
|
16
|
+
- zstd
|
|
17
|
+
- deflate
|
|
18
|
+
- Auto detect delimiters, encoding and compression.
|
|
19
|
+
- UTF-8 and Latin-1 have specialized native fast paths.
|
|
20
|
+
- More encodings are supported out of the box, including Windows-1252, UTF-16LE, and Shift_JIS.
|
|
22
21
|
|
|
23
|
-
##
|
|
22
|
+
## Installation
|
|
24
23
|
|
|
25
|
-
|
|
26
|
-
`bun install`, a fresh clone can run the Bun API, examples, and tests without compiling native code.
|
|
24
|
+
Requires **Bun `^1.4.0`**. Published packages include native libraries for these targets:
|
|
27
25
|
|
|
28
|
-
|
|
26
|
+
| Operating system | Architecture | CPU requirement |
|
|
27
|
+
| ---------------- | ------------ | --------------- |
|
|
28
|
+
| macOS 13+ | ARM64 | NEON |
|
|
29
|
+
| macOS 13+ | x64 | AVX2 |
|
|
30
|
+
| Linux | x64 | AVX2 |
|
|
29
31
|
|
|
30
32
|
```sh
|
|
31
|
-
bun
|
|
32
|
-
bun run build:native
|
|
33
|
-
bun run stage:native
|
|
33
|
+
bun add @konstit/csv
|
|
34
34
|
```
|
|
35
35
|
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
The downloaded sources are reused from `.cache/fetchcontent/`.
|
|
36
|
+
No native build is needed on supported targets. For building from source, see
|
|
37
|
+
[Contributing](https://github.com/Konstit-Engenharia/csv-parser/blob/main/CONTRIBUTING.md).
|
|
39
38
|
|
|
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.
|
|
39
|
+
## Quick start
|
|
44
40
|
|
|
45
|
-
|
|
41
|
+
Parse a buffer with `await csv.parse()`. Save this example as `parse.ts`:
|
|
46
42
|
|
|
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.
|
|
43
|
+
```ts
|
|
44
|
+
import { csv } from '@konstit/csv';
|
|
58
45
|
|
|
59
|
-
|
|
60
|
-
|
|
46
|
+
const input = Buffer.from('id,name,state\n1,Ada,SP\n2,Grace,RJ\n');
|
|
47
|
+
const rows = await csv.parse(input);
|
|
61
48
|
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
49
|
+
console.log(rows);
|
|
50
|
+
// [
|
|
51
|
+
// ['id', 'name', 'state'],
|
|
52
|
+
// ['1', 'Ada', 'SP'],
|
|
53
|
+
// ['2', 'Grace', 'RJ'],
|
|
54
|
+
// ]
|
|
65
55
|
```
|
|
66
56
|
|
|
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
57
|
```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
|
|
58
|
+
bun parse.ts
|
|
84
59
|
```
|
|
85
60
|
|
|
86
|
-
|
|
61
|
+
Each row is an array of strings. Headers remain ordinary records, and numeric-looking fields remain strings.
|
|
62
|
+
File and buffer APIs default to a comma delimiter. Buffers default to UTF-8; file readers detect UTF-8, Latin-1,
|
|
63
|
+
Windows-1252 or BOM-marked UTF-16 from the first 64 KiB after decompression. Set `delimiter: 'auto'` on a file
|
|
64
|
+
to detect both from the same sample. To skip detection, pass the encoding and delimiter explicitly.
|
|
65
|
+
UTF-8 and Latin-1 use native paths; other supported `Bun.Encoding` labels are transcoded to UTF-8.
|
|
87
66
|
|
|
88
|
-
|
|
89
|
-
native library not found. Run: bun run build:native
|
|
90
|
-
```
|
|
67
|
+
## Stream a file
|
|
91
68
|
|
|
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.
|
|
69
|
+
For files that do not fit in memory, use `csv.rows()`. Create `data.csv` with the same sample data:
|
|
98
70
|
|
|
99
|
-
|
|
71
|
+
```csv
|
|
72
|
+
id,name,state
|
|
73
|
+
1,Ada,SP
|
|
74
|
+
2,Grace,RJ
|
|
75
|
+
```
|
|
100
76
|
|
|
101
77
|
```ts
|
|
102
78
|
import { csv } from '@konstit/csv';
|
|
103
79
|
|
|
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) {
|
|
80
|
+
for await (const batch of csv.rows('data.csv')) {
|
|
81
|
+
for (const row of batch) {
|
|
114
82
|
console.log(row);
|
|
115
83
|
}
|
|
116
84
|
}
|
|
117
85
|
```
|
|
118
86
|
|
|
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).
|
|
135
|
-
|
|
136
|
-
For manual downloads, place both files in `corpus/large/` before running benchmarks or examples that use them.
|
|
87
|
+
Each iteration yields a **batch of rows** in file order, so use the inner loop to process individual records. Process
|
|
88
|
+
batches as they arrive to avoid collecting the complete file in memory. The header is returned as the first row.
|
|
137
89
|
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
Import the `csv` namespace for file-oriented helpers:
|
|
90
|
+
To count records without materializing rows:
|
|
141
91
|
|
|
142
92
|
```ts
|
|
143
93
|
import { csv } from '@konstit/csv';
|
|
144
94
|
|
|
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
|
-
});
|
|
95
|
+
console.log(await csv.count('data.csv')); // 3, including the header
|
|
165
96
|
```
|
|
166
97
|
|
|
167
|
-
|
|
98
|
+
## Choose an API
|
|
168
99
|
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
- `csv.
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
- `csv.findCsvSafeSplitOffsets(
|
|
100
|
+
| Task | API | Result or lifecycle |
|
|
101
|
+
| ---------------------------- | ----------------------------------------------------------- | --------------------------------------------------- |
|
|
102
|
+
| Parse an in-memory buffer | `await csv.parse(buffer)` | All rows as arrays of strings |
|
|
103
|
+
| Stream a file | `csv.rows(path)` | Async stream of row batches |
|
|
104
|
+
| Count records | `await csv.count(path)` | Record count, optionally filtered |
|
|
105
|
+
| Access native batches | `csv.batches(path, options)` | Use `using` to close each batch after its iteration |
|
|
106
|
+
| Visit rows or scan columns | `batch.forEachRow()` / `batch.scanColumns()` | Read projected fields by position within the batch |
|
|
107
|
+
| Supply your own input chunks | `NativeCsvParser` | Manual parser and batch disposal |
|
|
108
|
+
| Find record-safe boundaries | `csv.findCsvSafeSplitOffsets()` / `csv.findCsvSafeShards()` | Advanced byte-range processing |
|
|
178
109
|
|
|
179
|
-
|
|
110
|
+
Start with `csv.rows()` for streaming records. Use batches or views when you need byte access or lower allocation
|
|
111
|
+
overhead. Advanced applications can use the record-safe boundary helpers to divide an uncompressed CSV file into
|
|
112
|
+
byte ranges for their own processing pipeline. See the [API guide](https://github.com/Konstit-Engenharia/csv-parser/blob/main/docs/api.md)
|
|
113
|
+
for options and resource lifetimes.
|
|
180
114
|
|
|
181
|
-
|
|
182
|
-
The selected column is reusable, and one filter can be reused across row, count, and worker APIs:
|
|
115
|
+
## Common operations
|
|
183
116
|
|
|
184
|
-
|
|
185
|
-
const state = csv.column(2);
|
|
186
|
-
const isSP = state.equals('SP');
|
|
187
|
-
const isSouthEast = state.isOneOf(['SP', 'RJ']);
|
|
117
|
+
These examples read the `data.csv` shown above.
|
|
188
118
|
|
|
189
|
-
|
|
190
|
-
await csv.count('data.csv', { where: isSouthEast, workerCount: 4 });
|
|
191
|
-
```
|
|
119
|
+
### Filter records and select columns
|
|
192
120
|
|
|
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:
|
|
121
|
+
Column indexes are zero-based **source column indexes**: `id` is `0`, `name` is `1`, and `state` is `2`.
|
|
122
|
+
Filters use source indexes even when output columns are reordered.
|
|
198
123
|
|
|
199
124
|
```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:
|
|
125
|
+
import { csv } from '@konstit/csv';
|
|
213
126
|
|
|
214
|
-
|
|
215
|
-
const
|
|
216
|
-
|
|
217
|
-
csv.column(2).equals('SP'),
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
127
|
+
for await (
|
|
128
|
+
const batch of csv.rows('data.csv', {
|
|
129
|
+
columns: [1, 0],
|
|
130
|
+
where: csv.column(2).equals('SP'),
|
|
131
|
+
})
|
|
132
|
+
) {
|
|
133
|
+
console.log(batch); // [['Ada', '1']]
|
|
134
|
+
}
|
|
222
135
|
```
|
|
223
136
|
|
|
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.
|
|
233
|
-
|
|
234
|
-
ZIP input uses `compression: { format: 'zip', entry: 'path/in/archive.csv' }`. The selected stored or DEFLATE entry
|
|
235
|
-
is decoded in bounded native chunks with zlib-ng AVX2 or NEON acceleration. Entry names must match exactly. Use
|
|
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.
|
|
137
|
+
The filter also applies to the header, which does not match `'SP'` here. Combine conditions with `csv.all()`,
|
|
138
|
+
`csv.any()`, and `csv.not()`. Filters support equality, membership, prefixes, and RE2 regular expressions.
|
|
240
139
|
|
|
241
|
-
|
|
242
|
-
|
|
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.
|
|
140
|
+
See [Filters](https://github.com/Konstit-Engenharia/csv-parser/blob/main/docs/api.md#filters) for matching rules
|
|
141
|
+
and supported regex syntax.
|
|
246
142
|
|
|
247
|
-
|
|
248
|
-
exactly one character unless a serial file operation uses `auto`.
|
|
143
|
+
### Read compressed files
|
|
249
144
|
|
|
250
|
-
|
|
145
|
+
Create a gzip copy of the sample file:
|
|
251
146
|
|
|
252
|
-
|
|
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
|
|
147
|
+
```sh
|
|
148
|
+
gzip -c data.csv > data.csv.gz
|
|
257
149
|
```
|
|
258
150
|
|
|
259
|
-
Strict mode also validates optional schema metadata during row parsing:
|
|
260
|
-
|
|
261
151
|
```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:
|
|
152
|
+
import { csv } from '@konstit/csv';
|
|
279
153
|
|
|
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);
|
|
154
|
+
for await (
|
|
155
|
+
const batch of csv.rows('data.csv.gz', {
|
|
156
|
+
delimiter: 'auto',
|
|
157
|
+
})
|
|
158
|
+
) {
|
|
159
|
+
for (const row of batch) {
|
|
160
|
+
console.log(row);
|
|
161
|
+
}
|
|
301
162
|
}
|
|
302
|
-
|
|
303
|
-
console.log(await csv.count('data.csv', countOptions));
|
|
304
163
|
```
|
|
305
164
|
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
Column indexes are integers from `0` through `2024`. A projection may contain at most 2024 columns and must not repeat
|
|
311
|
-
an index. A filter can contain at most 2024 predicates and 4096 total predicates and Boolean operators. Invalid values
|
|
312
|
-
fail before parsing begins.
|
|
165
|
+
File APIs and the CLI detect compression by default and read plain CSV, TSV, and text files directly.
|
|
166
|
+
For a plain file with an unrecognized name, use `compression: 'none'` or `--compression none`.
|
|
167
|
+
Decompression streams into the parser.
|
|
313
168
|
|
|
314
|
-
|
|
169
|
+
ZIP archives automatically select the only data file, ignoring directories and OS metadata.
|
|
170
|
+
For archives with multiple data files, select an entry with `compression: { format: 'zip', entry: 'data.csv' }`. See
|
|
171
|
+
[Compression](https://github.com/Konstit-Engenharia/csv-parser/blob/main/docs/api.md#compression-and-delimiter-detection)
|
|
172
|
+
for supported formats, detection rules, and limits.
|
|
315
173
|
|
|
316
|
-
|
|
174
|
+
### Validate input
|
|
317
175
|
|
|
318
176
|
```ts
|
|
319
177
|
import { csv } from '@konstit/csv';
|
|
320
178
|
|
|
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
|
-
});
|
|
179
|
+
const rows = await csv.parse(
|
|
180
|
+
Buffer.from('id,name,state\n1,Ada,SP\n2,Grace,RJ\n'),
|
|
181
|
+
{
|
|
182
|
+
strict: true,
|
|
183
|
+
expectedHeaders: ['id', 'name', 'state'],
|
|
184
|
+
minDataRows: 1,
|
|
334
185
|
},
|
|
335
186
|
);
|
|
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
|
-
|
|
342
|
-
If you use `csv.batches()` directly, declare each batch with `using` so it is disposed after its iteration:
|
|
343
187
|
|
|
344
|
-
|
|
345
|
-
for await (using batch of csv.batches('data.csv', { delimiter: ';' })) {
|
|
346
|
-
console.log(batch.rowCount);
|
|
347
|
-
}
|
|
188
|
+
console.log(rows.length); // 3
|
|
348
189
|
```
|
|
349
190
|
|
|
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
|
-
```
|
|
191
|
+
Strict mode validates quote syntax and can check header and row-count requirements. It supports column selection
|
|
192
|
+
with `csv.parse()` and `csv.rows()`, but cannot be combined with filters. See
|
|
193
|
+
[Strict validation](https://github.com/Konstit-Engenharia/csv-parser/blob/main/docs/api.md#strict-validation)
|
|
194
|
+
for supported combinations.
|
|
395
195
|
|
|
396
196
|
## CLI
|
|
397
197
|
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
```sh
|
|
401
|
-
bunx @konstit/csv count data.csv
|
|
402
|
-
bunx @konstit/csv count data.csv --delimiter ';' --chunk-size 262144
|
|
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`.
|
|
435
|
-
|
|
436
|
-
The CLI uses one process and exposes the serial file, parser, projection, and filter fields as flags. It does not expose
|
|
437
|
-
`workerCount`. Run `csv count --help` or `csv lines --help` for the complete list. Friendly filter flags use
|
|
438
|
-
`column=value`. Repeat `--where-in` or `--where-noin` for each value. Different filter clauses combine with AND. CLI
|
|
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
|
|
449
|
-
```
|
|
450
|
-
|
|
451
|
-
The large corpus file in this repository is semicolon-delimited:
|
|
198
|
+
Inspect a file, count its records, or emit the first records as newline-delimited JSON:
|
|
452
199
|
|
|
453
200
|
```sh
|
|
454
|
-
csv
|
|
455
|
-
csv lines corpus/large/example.csv --delimiter ';' --columns 0,1,2 --limit 100 > sample.csv
|
|
456
|
-
```
|
|
201
|
+
bunx @konstit/csv probe data.csv
|
|
457
202
|
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
```sh
|
|
462
|
-
csv count data.csv --where '{"all":[{"any":[{"column":2,"equals":"SP"},{"column":2,"equals":"RJ"}]},{"not":{"column":1,"startsWith":"B"}}]}'
|
|
463
|
-
```
|
|
464
|
-
|
|
465
|
-
CLI JSON filters can nest `all`, `any`, and `not`. Friendly filter flags still combine with AND.
|
|
466
|
-
|
|
467
|
-
## Examples
|
|
468
|
-
|
|
469
|
-
```sh
|
|
470
|
-
bun run example:first-rows
|
|
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:
|
|
203
|
+
bunx @konstit/csv count data.csv
|
|
204
|
+
# 3
|
|
511
205
|
|
|
512
|
-
|
|
513
|
-
|
|
206
|
+
bunx @konstit/csv lines data.csv --json --limit 2
|
|
207
|
+
# ["id","name","state"]
|
|
208
|
+
# ["1","Ada","SP"]
|
|
514
209
|
```
|
|
515
210
|
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
### Full-file filtered materialization benchmark
|
|
211
|
+
The CLI detects input encoding and delimiter by default. Without `--json`, `lines` writes normalized UTF-8 CSV.
|
|
212
|
+
`count` and `lines` support column filters; `lines` also supports
|
|
213
|
+
column selection. Use `bunx @konstit/csv lines --help` or read the
|
|
214
|
+
[CLI guide](https://github.com/Konstit-Engenharia/csv-parser/blob/main/docs/cli.md) for flags and output behavior.
|
|
522
215
|
|
|
523
|
-
|
|
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.
|
|
216
|
+
## Documentation
|
|
527
217
|
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
218
|
+
- [API guide](https://github.com/Konstit-Engenharia/csv-parser/blob/main/docs/api.md): filters, encoding, compression,
|
|
219
|
+
validation, typed options, batches, views, advanced byte boundaries, and manual parsing.
|
|
220
|
+
- [CLI guide](https://github.com/Konstit-Engenharia/csv-parser/blob/main/docs/cli.md): commands, filters, output formats,
|
|
221
|
+
and option constraints.
|
|
222
|
+
- [Benchmarks](https://github.com/Konstit-Engenharia/csv-parser/blob/main/docs/benchmarks.md): datasets, commands,
|
|
223
|
+
recorded measurements, and their limitations.
|
|
224
|
+
- [Contributing](https://github.com/Konstit-Engenharia/csv-parser/blob/main/CONTRIBUTING.md): repository setup, examples,
|
|
225
|
+
validation, native development, and releases.
|
|
531
226
|
|
|
532
|
-
|
|
533
|
-
characters from the 6,780,467,695-byte corpus:
|
|
227
|
+
## Performance
|
|
534
228
|
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
229
|
+
The parser uses native C++ with AVX2 on x64 and NEON on ARM64. Filtering and counting can avoid creating JavaScript
|
|
230
|
+
rows for records you do not need. The [benchmark guide](https://github.com/Konstit-Engenharia/csv-parser/blob/main/docs/benchmarks.md)
|
|
231
|
+
records a full-file comparison, including memory use and reproduction commands. Results depend on the workload,
|
|
232
|
+
hardware, and selected API.
|
|
539
233
|
|
|
540
|
-
|
|
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`.
|
|
234
|
+
## Contributing
|
|
543
235
|
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
```sh
|
|
547
|
-
bun run bench:regression-smoke
|
|
548
|
-
bun run bench:csv-parser:guard
|
|
549
|
-
```
|
|
236
|
+
See [Contributing](https://github.com/Konstit-Engenharia/csv-parser/blob/main/CONTRIBUTING.md) to run the project locally,
|
|
237
|
+
validate changes, or rebuild the native libraries.
|
|
550
238
|
|
|
551
239
|
## License
|
|
552
240
|
|
|
553
|
-
MIT © 2026 KONSTIT ENGENHARIA E TECNOLOGIA LTDA. See
|
|
554
|
-
[
|
|
241
|
+
MIT © 2026 KONSTIT ENGENHARIA E TECNOLOGIA LTDA. See
|
|
242
|
+
[LICENSE](https://github.com/Konstit-Engenharia/csv-parser/blob/main/LICENSE) and
|
|
243
|
+
[third-party notices](https://github.com/Konstit-Engenharia/csv-parser/blob/main/THIRD_PARTY_NOTICES.md).
|