Skip to content

fs.createReadStream(...)[Symbol.asyncIterator]() is not async iterable #23041

Closed

Description

@alanshaw
  • Version: v10.10.0
  • Platform: n/a
  • Subsystem: ?
const fs = require('fs')

async function main () {
  const iterator = fs.createReadStream(__filename)[Symbol.asyncIterator]()
  for await (const chunk of iterator) {
    console.log('got a chunk', chunk.toString())
  }
}

main()

I get the error:

(node:13875) UnhandledPromiseRejectionWarning: TypeError: iterator is not async iterable

This isn't exactly a bug, but I think the iterator returned by fs.createReadStream(__filename)[Symbol.asyncIterator]() doesn't implement the iterable protocol which is why this is happening.

It is not possible to know reflectively whether a particular object implements the iterator protocol, however it is easy to create an object that satisfies both the iterator and iterable protocols (as shown in the example below). Doing so allows an iterator to be consumed by the various syntaxes expecting iterables. Thus it is rarely desireable to implement the iterator protocol without also implementing iterable.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterator_protocol

This might be useful if you wanted to consume the first X chunks of a stream using await iterator.next() and then conditionally consume the rest with for await of.

Activity

  1. added
    fs
    stream
    experimental
    confirmed-bug
    and removed
    fs
    on Sep 23, 2018
  2. self-assigned this
    on Sep 23, 2018
  3. devsnek commented on Sep 23, 2018

    @devsnek
    Member

    fixed locally... just running tests and then i'll have a pr up

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

Metadata

Metadata

Assignees

Labels

confirmed-bugexperimentalstream

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions