Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 39 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -92,8 +92,9 @@ Bugs Bunny,22
It could then be parsed, and results shown like so:

``` js
const csv = require('csv-parser')
const fs = require('fs')
import fs from 'node:fs';
import csv from 'csv-parser';

const results = [];

fs.createReadStream('data.csv')
Expand All @@ -108,6 +109,42 @@ fs.createReadStream('data.csv')
});
```

You can also use async iterators in modern Node.js versions:

```js
import fs from 'node:fs';
import csv from 'csv-parser';

async function readCSV(file) {
const results = [];

for await (const data of fs.createReadStream(file).pipe(csv())) {
results.push(data);
}

return results;
}

readCSV('data.csv')
.then((results) => console.log(results))
.catch((err) => console.error(err));
```

Or a shorter version in Node.js 22+ using [Array.fromAsync](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/fromAsync):

```js
import fs from 'node:fs';
import csv from 'csv-parser';

async function readCSV(file) {
return Array.fromAsync(fs.createReadStream(file).pipe(csv()));
}

readCSV('data.csv')
.then((results) => console.log(results))
.catch((err) => console.error(err));
```

To specify options for `csv`, pass an object argument to the function. For
example:

Expand Down
12 changes: 12 additions & 0 deletions examples/node22.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import fs from 'node:fs'
import path from 'node:path'

import csv from '../index.js'

async function readCSV (file) {
return Array.fromAsync(fs.createReadStream(file).pipe(csv()))
}

const results = await readCSV(path.join(import.meta.dirname, '../test/fixtures/basic.csv'))

console.log(results)