stream.finished(stream[, options])


const { finished } = require('node:stream/promises');
const fs = require('node:fs');

const rs = fs.createReadStream('archive.tar');

async function run() {
  await finished(rs);
  console.log('Stream is done reading.');
}

run().catch(console.error);
rs.resume(); // Drain the stream.import { finished } from 'node:stream/promises';
import { createReadStream } from 'node:fs';

const rs = createReadStream('archive.tar');

async function run() {
  await finished(rs);
  console.log('Stream is done reading.');
}

run().catch(console.error);
rs.resume(); // Drain the stream.

finished API 也提供了一个 回调版本

【The finished API also provides a callback version.】

stream.finished() 在返回的 Promise 被解决或拒绝后会留下悬空的事件监听器(特别是 'error''end''finish''close')。这样设计的原因是为了防止意外的 'error' 事件(由于流实现不正确)导致意外崩溃。如果不希望出现这种行为,应将 options.cleanup 设置为 true

await finished(rs, { cleanup: true });