stream.addAbortSignal(signal, stream)


将中止信号绑定到可读或可写的流。 这让代码可以使用 AbortController 来控制流销毁。

在与传入的 AbortSignal 对应的 AbortController 上调用 abort 的行为与在流上调用 .destroy(new AbortError()) 的行为相同。

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

const controller = new AbortController();
const read = addAbortSignal(
  controller.signal,
  fs.createReadStream(('object.json'))
);
// 稍后,中止关闭流的操作
controller.abort();

或者使用带有可读流的 AbortSignal 作为异步可迭代对象:

const controller = new AbortController();
setTimeout(() => controller.abort(), 10_000); // 设置超时
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') {
      // 操作被取消
    } else {
      throw e;
    }
  }
})();
  • signal <AbortSignal> A signal representing possible cancellation
  • stream <Stream> a stream to attach a signal to

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

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