Skip to main content

finished

function internal.finished
Jump to headingfinished(
stream:
ReadableStream
| WritableStream
| ReadWriteStream
,
options: FinishedOptions,
callback: (err?: ErrnoException | null) => void,
): () => void

A readable and/or writable stream/webstream.

A function to get notified when a stream is no longer readable, writable or has experienced an error or a premature close event.

import { finished } from 'node:stream';
import fs from 'node:fs';

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

finished(rs, (err) => {
  if (err) {
    console.error('Stream failed.', err);
  } else {
    console.log('Stream is done reading.');
  }
});

rs.resume(); // Drain the stream.

Especially useful in error handling scenarios where a stream is destroyed prematurely (like an aborted HTTP request), and will not emit 'end' or 'finish'.

The finished API provides promise version.

stream.finished() leaves dangling event listeners (in particular 'error', 'end', 'finish' and 'close') after callback has been invoked. The reason for this is so that unexpected 'error' events (due to incorrect stream implementations) do not cause unexpected crashes. If this is unwanted behavior then the returned cleanup function needs to be invoked in the callback:

const cleanup = finished(rs, (err) => {
  cleanup();
  // ...
});

Parameters Jump to heading

Jump to headingstream:
ReadableStream
| WritableStream
| ReadWriteStream

A readable and/or writable stream.

Jump to headingcallback: (err?: ErrnoException | null) => void

A callback function that takes an optional error argument.

Return Type Jump to heading

() => void

A cleanup function which removes all registered listeners.

Jump to headingfinished(
stream:
ReadableStream
| WritableStream
| ReadWriteStream
,
callback: (err?: ErrnoException | null) => void,
): () => void

Parameters Jump to heading

Jump to headingstream:
ReadableStream
| WritableStream
| ReadWriteStream
Jump to headingcallback: (err?: ErrnoException | null) => void

Return Type Jump to heading

() => void
Back to top