Skip to content

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

Closed
@alanshaw

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.

Metadata

Metadata

Assignees

Labels

confirmed-bugIssues with confirmed bugs.experimentalIssues and PRs related to experimental features.streamIssues and PRs related to the stream subsystem.

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions