|
1 | | -import path from 'path'; |
2 | | -import { pipeline } from 'stream/promises'; |
3 | | -import { parse as parseCSV } from 'csv-parse'; |
4 | | -import { Writable } from 'stream'; |
5 | | -import { createReadStream } from 'fs'; |
| 1 | +import assert from 'node:assert'; |
| 2 | +import { createReadStream } from 'node:fs'; |
| 3 | +import { Writable } from 'node:stream' |
| 4 | +import { finished } from 'node:stream/promises'; |
6 | 5 | import desm from "desm"; |
7 | | -const __dirname = desm(import.meta.url); |
8 | | - |
9 | | -async function testRecordsSkip() { |
10 | | - const errors = []; |
11 | | - const records = []; |
12 | | - |
13 | | - const sink = new Writable({ |
14 | | - objectMode: true, |
15 | | - write: (_, __, callback) => { |
16 | | - records.push(_); |
17 | | - callback(); |
18 | | - }, |
19 | | - }); |
| 6 | +import { parse } from 'csv-parse'; |
20 | 7 |
|
21 | | - const csvSource = createReadStream(path.join(__dirname, '411.csv')); |
22 | | - const parser = parseCSV({ |
23 | | - skip_records_with_error: true, |
24 | | - bom: true, |
25 | | - }); |
26 | | - parser.on('skip', function (err) { |
27 | | - errors.push(err); |
28 | | - }); |
29 | | - |
30 | | - await pipeline(csvSource, parser, sink); |
31 | | - |
32 | | - console.log({ |
33 | | - records, |
34 | | - errors, |
35 | | - }); |
36 | | -} |
| 8 | +const __dirname = desm(import.meta.url); |
| 9 | +const errors = [] |
37 | 10 |
|
38 | | -testRecordsSkip().catch(console.error); |
| 11 | +const parser = parse({ |
| 12 | + bom: true, |
| 13 | + skipRecordsWithError: true, |
| 14 | +}); |
| 15 | +// Create a stream and consume its source |
| 16 | +const sink = new Writable ({objectMode: true, write: (_, __, callback) => callback()}) |
| 17 | +const outStream = createReadStream(`${__dirname}/411.csv`).pipe(parser).pipe(sink); |
| 18 | +// Catch records with errors |
| 19 | +parser.on('skip', (e) => { |
| 20 | + errors.push(e); |
| 21 | +}); |
| 22 | +// Wait for stream to be consumed |
| 23 | +await finished(outStream); |
| 24 | +// Catch error from skip event |
| 25 | +assert.deepStrictEqual(errors.map(e => e.message), [ |
| 26 | + 'Invalid Record Length: expect 5, got 6 on line 3' |
| 27 | +]) |
0 commit comments