# Function finished

- finished(stream, options, callback): (() => void)

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

      const { finished } = require('stream');

      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:

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

      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.

  `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

  - stream: WritableStream | ReadableStream | ReadWriteStream

    A readable and/or writable stream.

  - options: FinishedOptions
  - callback: ((err?: ErrnoException) => void)

    A callback function that takes an optional error argument.

    - - (err?): void

      - #### Parameters

        - `Optional` err: ErrnoException

        #### Returns void

  #### Returns (() => void)

  A cleanup function which removes all registered listeners.

  - - (): void

    - #### Returns void

  #### Since

  v10.0.0

  - Defined in node_modules/@types/node/stream.d.ts:1378
- finished(stream, callback): (() => void)

- #### Parameters

  - stream: WritableStream | ReadableStream | ReadWriteStream
  - callback: ((err?: ErrnoException) => void)
    - - (err?): void

      - #### Parameters

        - `Optional` err: ErrnoException

        #### Returns void

  #### Returns (() => void)

  - - (): void

    - #### Returns void

  - Defined in node_modules/@types/node/stream.d.ts:1383