75 lines
1.8 KiB
Markdown
75 lines
1.8 KiB
Markdown
# @techniker-me/csv
|
|
|
|
To install dependencies:
|
|
|
|
```bash
|
|
bun install
|
|
```
|
|
|
|
To run:
|
|
|
|
```bash
|
|
bun run src/index.ts
|
|
```
|
|
|
|
This project was created using `bun init` in bun v1.2.20. [Bun](https://bun.com) is a fast all-in-one JavaScript runtime.
|
|
|
|
## Usage
|
|
|
|
### Parse from string
|
|
|
|
```ts
|
|
import { CsvParser } from "@techniker-me/csv";
|
|
|
|
const parser = new CsvParser();
|
|
const csv = "name,age\nAlice,30\nBob,40";
|
|
const result = await parser.parseFromString(csv, {
|
|
hasHeader: true,
|
|
output: "object", // "object" or "array"
|
|
});
|
|
|
|
// result.headers -> ["name", "age"]
|
|
// result.rows -> [{ name: "Alice", age: "30" }, { name: "Bob", age: "40" }]
|
|
```
|
|
|
|
### Parse from file
|
|
|
|
```ts
|
|
import { CsvParser, FileChunkSource } from "@techniker-me/csv";
|
|
|
|
const parser = new CsvParser();
|
|
const source = new FileChunkSource("/path/to/file.csv");
|
|
const result = await parser.parseFromSource(source, {
|
|
hasHeader: true,
|
|
output: "array",
|
|
});
|
|
```
|
|
|
|
### Dialect options
|
|
|
|
```ts
|
|
import { CsvParser, CsvDialect } from "@techniker-me/csv";
|
|
|
|
const parser = new CsvParser();
|
|
const result = await parser.parseFromString("a;b\n1;2", {
|
|
hasHeader: true,
|
|
dialect: { delimiter: ";", quote: '"', trimWhitespace: true },
|
|
});
|
|
```
|
|
|
|
### API
|
|
|
|
- `CsvParser.parseFromString(input: string, options?: ParseOptions)`
|
|
- `CsvParser.parseFromSource(source: IChunkSource, options?: ParseOptions)`
|
|
- `FileChunkSource(path: string, chunkSize?: number)`
|
|
- `StringChunkSource(content: string, chunkSize?: number)`
|
|
|
|
`ParseOptions`:
|
|
|
|
- `dialect` (partial): `{ delimiter, quote, trimWhitespace }`
|
|
- `hasHeader`: treat first row as headers (default true for object mode, optional for array mode)
|
|
- `output`: `"object" | "array"` (default `"array"`)
|
|
- `validateRowLength`: pads/truncates rows to uniform length (default true)
|
|
- `skipEmptyLines`: ignore empty lines (default true)
|
|
|