nodejs / node

Node.js JavaScript runtime ✨🐢🚀✨
https://nodejs.org
Other
107.31k stars 29.46k forks source link

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

Closed alanshaw closed 6 years ago

alanshaw commented 6 years ago
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.

devsnek commented 6 years ago

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