]> git.ardis.lu - csvio/commitdiff
Add "Abort a transformation" example
authorArdis Lu <ardisglu@gmail.com>
Mon, 3 Feb 2025 07:51:34 +0000 (23:51 -0800)
committerArdis Lu <ardisglu@gmail.com>
Mon, 3 Feb 2025 07:51:34 +0000 (23:51 -0800)
examples/README.md
examples/data/ex1_7-in.csv [new file with mode: 0644]
examples/data/ex1_7-out.csv [new file with mode: 0644]
examples/ex1_7.js [new file with mode: 0644]

index 8d5dbe29054bb7fe22a70f3b6807260aea8765bb..4621fb48582374acd6762c4a059098acb6b440f0 100644 (file)
@@ -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 (file)
index 0000000..a9b543f
--- /dev/null
@@ -0,0 +1,6 @@
+Header A\r
+abc\r
+def\r
+abort\r
+ghi\r
+jkl\r
diff --git a/examples/data/ex1_7-out.csv b/examples/data/ex1_7-out.csv
new file mode 100644 (file)
index 0000000..0e472ca
--- /dev/null
@@ -0,0 +1,3 @@
+Header A\r
+abc\r
+def\r
diff --git a/examples/ex1_7.js b/examples/ex1_7.js
new file mode 100644 (file)
index 0000000..dd2a643
--- /dev/null
@@ -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
This page took 0.057 seconds and 4 git commands to generate.