From bdf5ab0edd596cfd5a973eb29f4afbebba9b6e62 Mon Sep 17 00:00:00 2001 From: Ardis Lu Date: Sun, 2 Feb 2025 23:51:34 -0800 Subject: [PATCH] Add "Abort a transformation" example --- examples/README.md | 2 ++ examples/data/ex1_7-in.csv | 6 ++++++ examples/data/ex1_7-out.csv | 3 +++ examples/ex1_7.js | 22 ++++++++++++++++++++++ 4 files changed, 33 insertions(+) create mode 100644 examples/data/ex1_7-in.csv create mode 100644 examples/data/ex1_7-out.csv create mode 100644 examples/ex1_7.js diff --git a/examples/README.md b/examples/README.md index 8d5dbe2..4621fb4 100644 --- a/examples/README.md +++ b/examples/README.md @@ -26,6 +26,8 @@ These examples demonstrate the most common, expected usage. [Example 1.6: Track the status of the CSV processing](./ex1_6.js) +[Example 1.7: Abort a transformation](./ex1_7.js) + ### Section 2: Error strategies These examples demonstrate using the `onError` option to handle transformations that may throw errors. diff --git a/examples/data/ex1_7-in.csv b/examples/data/ex1_7-in.csv new file mode 100644 index 0000000..a9b543f --- /dev/null +++ b/examples/data/ex1_7-in.csv @@ -0,0 +1,6 @@ +Header A +abc +def +abort +ghi +jkl diff --git a/examples/data/ex1_7-out.csv b/examples/data/ex1_7-out.csv new file mode 100644 index 0000000..0e472ca --- /dev/null +++ b/examples/data/ex1_7-out.csv @@ -0,0 +1,3 @@ +Header A +abc +def diff --git a/examples/ex1_7.js b/examples/ex1_7.js new file mode 100644 index 0000000..dd2a643 --- /dev/null +++ b/examples/ex1_7.js @@ -0,0 +1,22 @@ +// ## Example 1.7: Abort a transformation +// +// Pass an [`AbortSignal`](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal) to `.pipeTo()` to gracefully +// abort a transformation. All transformations enqueued up until the row causing the abort (but *not* including the abort +// row itself) will be saved to disk. +// +// Aborting throws an error, so you must also add a `.catch()` to handle the abort. + +import { CSVReader, CSVTransformer, CSVWriter } from '../src/index.js'; + +const controller = new AbortController(); +function identityWithAbort(row) { + if (row[0] === 'abort') { // Arbitrary logic for aborting the transformation + controller.abort(); + } + return row; +} + +await new CSVReader(new URL('./data/ex1_7-in.csv', import.meta.url)) + .pipeThrough(new CSVTransformer(identityWithAbort)) + .pipeTo(new CSVWriter(new URL('./data/ex1_7-out.csv', import.meta.url)), { signal: controller.signal }) + .catch(() => {}); // No-op to catch the intentional abort for example purposes. Beware this will also catch other errors. \ No newline at end of file -- 2.47.3