镜像站点 · 本页由第三方 GitHub 只读镜像提供,非 GitHub 官方站点,不接受任何登录或凭据输入。前往 github.com
Skip to content

stream: How to destroy and stop Readable? #29856

Description

@ronag

I ran into this today:

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

const someOtherResource = {
  doStuff () {
    if (this.destroyed) {
      throw new Error('destroyed!')
    }
  },
  destroy () {
    this.destroyed = true
  }
}

const r = new Readable({})

r.on('data', () => {
  someOtherResource.doStuff()
})
someOtherResource.destroy()
r.push('asd')
r.destroy() // or r.destroy(new Error('kaboom'))
r.read()

This will crash with destroyed! since read() will emit already buffered 'data' even though the stream is destroyed.

I can fix my above example by replacing r.destroy() with:

function destroy (r) {
  r.removeAllListeners('data')
  r.destroy()
}

I find this a bit unfortunate.

Questions:

  • Is this expected behaviour?
  • Can we fix it without breaking the ecosystem?
  • If no, can we provide another method to Readable that makes it possible to fully destroy and silence a readable?

In order to fix this in readable we would have to check for destroyed and return early inside Readable.read().

Activity

  1. added
    streamIssues and PRs related to Node.js streams.
    on Oct 7, 2019
  2. ronag commented on Oct 8, 2019

    @ronag
    MemberAuthor

    @jasnell maybe?

  3. ctcpip commented on Jul 24, 2025

    @ctcpip

    it's expected behavior and can't be changed directly without breaking the ecosystem. it seems easy enough to work around either by checking r.destroyed or removing listeners, no?

  4. github-actions commented on Jun 27, 2026

    @github-actions
    Contributor

    This issue has been marked as stale due to 210 days of inactivity.
    It will be automatically closed in 30 days if no further activity occurs. If this is still relevant, please leave a comment or update it to keep it open.

  5. added
    staleIssues and PRs marked stale due to inactivity and scheduled for automatic closure.
    on Jun 27, 2026
  6. github-actions commented on Jul 28, 2026

    @github-actions
    Contributor

    This issue has been automatically closed after 30 days of inactivity following its stale status (no activity for a total of 120 days).
    If this is still relevant, feel free to reopen it or leave a comment with additional details so we can continue the discussion.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    staleIssues and PRs marked stale due to inactivity and scheduled for automatic closure.streamIssues and PRs related to Node.js streams.

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions