|
1 | 1 |
|
2 | | -import assert from 'node:assert'; |
3 | | -import { parse } from 'csv-parse/sync'; |
| 2 | +import assert from "node:assert"; |
| 3 | +import { parse } from "csv-parse/sync"; |
4 | 4 |
|
5 | 5 | const data = ` |
6 | | - 2000-01-01,date1 |
7 | | - 2050-11-27,date2 |
| 6 | + 1,2,3 |
| 7 | + 4,5,6 |
8 | 8 | `.trim(); |
9 | 9 | const records = parse(data, { |
10 | | - // The cast option exect a function which |
| 10 | + // The cast option exect a function which |
11 | 11 | // is called with two arguments, |
12 | 12 | // the parsed value and a context object |
13 | | - cast: function(value, context){ |
14 | | - // You can return any value |
15 | | - if(context.index === 0){ |
16 | | - // Such as a string |
17 | | - return `${value}T05:00:00.000Z`; |
18 | | - }else{ |
19 | | - // Or the `context` object literal |
20 | | - return context; |
| 13 | + cast: function (value, context) { |
| 14 | + // Index indicates the column position |
| 15 | + if (context.index === 0) { |
| 16 | + // Return the value untouched |
| 17 | + return value; |
| 18 | + } else if (context.index === 1) { |
| 19 | + // Convert the value to a string |
| 20 | + return parseInt(value); |
| 21 | + } else { |
| 22 | + // Return a different value |
| 23 | + return `Value is ${value}` |
21 | 24 | } |
22 | 25 | }, |
23 | | - trim: true |
| 26 | + trim: true, |
24 | 27 | }); |
25 | 28 | assert.deepStrictEqual(records, [ |
26 | | - [ '2000-01-01T05:00:00.000Z', { |
27 | | - bytes: 16, comment_lines: 0, empty_lines: 0, invalid_field_length: 0, |
28 | | - lines: 1, records: 0, columns: false, error: undefined, header: false, |
29 | | - index: 1, column: 1, quoting: false, raw: undefined |
30 | | - } ], |
31 | | - [ '2050-11-27T05:00:00.000Z', { |
32 | | - bytes: 35, comment_lines: 0, empty_lines: 0, invalid_field_length: 0, |
33 | | - lines: 2, records: 1, columns: false, error: undefined, header: false, |
34 | | - index: 1, column: 1, quoting: false, raw: undefined |
35 | | - } ] |
| 29 | + [ "1", 2, "Value is 3" ], |
| 30 | + [ "4", 5, "Value is 6" ], |
36 | 31 | ]); |
0 commit comments