From 402fddfe3bcef7ce8b3dd972711a8d038a6f54fc Mon Sep 17 00:00:00 2001 From: Ardis Lu Date: Tue, 21 Jan 2025 21:35:38 -0800 Subject: [PATCH] Add graceful failure example --- examples/README.md | 4 +++- examples/data/ex9-in.csv | 11 +++++++++++ examples/data/ex9-out.csv | 11 +++++++++++ examples/ex9.js | 22 ++++++++++++++++++++++ 4 files changed, 47 insertions(+), 1 deletion(-) create mode 100644 examples/data/ex9-in.csv create mode 100644 examples/data/ex9-out.csv create mode 100644 examples/ex9.js diff --git a/examples/README.md b/examples/README.md index 3d97d78..f2000cd 100644 --- a/examples/README.md +++ b/examples/README.md @@ -24,4 +24,6 @@ node ./examples/ex1.js [Example 7: Processing rows in batches (multi-row input)](./ex7.js) -[Example 8: Processing rows concurrently (async)](./ex8.js) \ No newline at end of file +[Example 8: Processing rows concurrently (async)](./ex8.js) + +[Example 9: Handling a flaky transformation (graceful failure)](./ex9.js) \ No newline at end of file diff --git a/examples/data/ex9-in.csv b/examples/data/ex9-in.csv new file mode 100644 index 0000000..9e3c659 --- /dev/null +++ b/examples/data/ex9-in.csv @@ -0,0 +1,11 @@ +columnA,columnB +1,A +2,B +3,C +4,D +5,E +6,F +7,G +8,H +9,I +10,J diff --git a/examples/data/ex9-out.csv b/examples/data/ex9-out.csv new file mode 100644 index 0000000..c1979c5 --- /dev/null +++ b/examples/data/ex9-out.csv @@ -0,0 +1,11 @@ +columnA,columnB +1,A +n/a,n/a +3,C +n/a,n/a +5,E +n/a,n/a +7,G +n/a,n/a +9,I +n/a,n/a diff --git a/examples/ex9.js b/examples/ex9.js new file mode 100644 index 0000000..1cbfba3 --- /dev/null +++ b/examples/ex9.js @@ -0,0 +1,22 @@ +// ## Example 9: Handling a flaky transformation (graceful failure) + +import { CSVReader, CSVTransformer, CSVWriter } from '../src/index.js'; + +// Set a placeholder value and continue processing +function graceful(row) { + return row.map(() => 'n/a'); +} + +// Will throw on every other row +let i = 0; +function flaky(row) { + i++; + if (i % 2 === 0) { + throw new Error('Example error message'); + } + return row; +} + +await new CSVReader(new URL('./data/ex9-in.csv', import.meta.url)) + .pipeThrough(new CSVTransformer(flaky, { onError: row => graceful(row) })) + .pipeTo(new CSVWriter(new URL('./data/ex9-out.csv', import.meta.url))); \ No newline at end of file -- 2.47.3