Node.js Reference ยท Globals and Console
The AbortController class
Reference for AbortController in Node.js: create a signal, call abort() with a reason, cancel timers, events and streams, and clean up listeners.
An AbortController is a small object with one job: it lets one piece of code tell another "stop what you are doing". The controller owns an AbortSignal (the signal property) that you pass to a cancellable operation, and an abort() method that triggers it.
Many Node.js APIs accept a signal option: fetch, timers from node:timers/promises, fs.promises.readFile, events.once, streams, child processes, and http requests. When the controller aborts, those operations stop and usually reject with an AbortError.
const controller = new AbortController(); // pass controller.signal to an API, then later: controller.abort();
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.
Syntax
const controller = new AbortController(); controller.signal // AbortSignal controller.abort(reason?)
| Name | Description |
|---|---|
signal |
Read-only AbortSignal linked to this controller. Hand it to the code that should be cancellable. |
reason |
Optional value stored in signal.reason. If omitted, a DOMException named AbortError is created. |
Returns: abort() returns undefined.
Errors: none from the controller. The operation holding the signal decides how it fails; most reject with an AbortError whose cause is the reason.
Usage notes
- One-way and one-shot. A controller can be aborted once; later calls are ignored. Make a new controller for the next operation.
- Give out the signal, keep the controller. Code that only needs to listen should receive
controller.signal, not the ability to abort. - Check by name, not by class:
err.name === 'AbortError'is the reliable test across APIs. abort()runs listeners synchronously, in the order they were added, before it returns.- Listener cleanup: use
addEventListener('abort', fn, { once: true })and remove the listener if the work finishes first, or long-lived signals accumulate listeners (Node warns after many). - Timeouts: for "cancel after N ms", prefer
AbortSignal.timeout(ms)over a manualsetTimeoutplusabort(). SeeAbortSignal. - Garbage collection: an operation that keeps its signal alive also keeps its listeners; abort or finish cleanly to release them.
- Own APIs: accept an optional
signalargument, callsignal.throwIfAborted()between steps and listen for theabortevent to release resources. - Global since Node.js 15; stable in 16+.