Skip to main content
Deno 2 is finally here 🎉️
Learn more
Module

std/node/stream.ts>addAbortSignal

Deno standard library
Go to Latest
The Standard Library has been moved to JSR. See the blog post for details.
function addAbortSignal
import { addAbortSignal } from "https://deno.land/std@0.142.0/node/stream.ts";

Attaches an AbortSignal to a readable or writeable stream. This lets code control stream destruction using an AbortController.

Calling abort on the AbortController corresponding to the passedAbortSignal will behave the same way as calling .destroy(new AbortError())on the stream.

const fs = require('fs');

const controller = new AbortController();
const read = addAbortSignal(
  controller.signal,
  fs.createReadStream(('object.json'))
);
// Later, abort the operation closing the stream
controller.abort();

Or using an AbortSignal with a readable stream as an async iterable:

const controller = new AbortController();
setTimeout(() => controller.abort(), 10_000); // set a timeout
const stream = addAbortSignal(
  controller.signal,
  fs.createReadStream(('object.json'))
);
(async () => {
  try {
    for await (const chunk of stream) {
      await process(chunk);
    }
  } catch (e) {
    if (e.name === 'AbortError') {
      // The operation was cancelled
    } else {
      throw e;
    }
  }
})();

Parameters

signal: AbortSignal

A signal representing possible cancellation

stream: T

a stream to attach a signal to