stream.addAbortSignal(signal, stream)


将 AbortSignal 附加到可读或可写流。这允许代码使用 AbortController 控制流的销毁。

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

在对应传入 AbortSignalAbortController 上调用 abort,其行为与在流上调用 .destroy(new AbortError()) 相同。

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

const fs = require('node:fs');

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

或者将 AbortSignal 与可读流作为异步可迭代对象一起使用:

🌐 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;
    }
  }
})();