Rich-Harris/devalue

Allow `ReadableStream`s for `parse`

plutoniumm opened this issue · 0 comments

I have a ServerSide JSON file that was encoded with devalue.stringify since it has Maps, doing a fetch call to it with .json doesn't work i.e consider

fetch("https://example.com/data.json")
.then(res => res.json()) // Breaks

But if I do (workaround)

fetch("https://example.com/data.json")
.then(res => res.text())
.then(data => devalue.parse(data)) // Works

So I think it would be nice if devalue.parse could accept a ReadableStream as well so that we can do something like one of the two below

fetch("https://example.com/data.json")
  .then(res => devalue.parse(res)) // This probably is the wrong way to approach it, not sure
  // similarly
  .then(res => res.devalueParse())

or alternatively

// via stream chunking
fetch("https://example.com/data.json")
  .then(res => {
    res.body.pipe( devalueParser );

    devalueParser.on( 'error', function ( error ) { } );
    devalueParser.on( 'readable', function () {
      let stream = this; // `this` is from `devalueParser`, which is a stream
      let item;

      let chunks = [];
      while ( item = stream.read() ) chunks.push( item );

      return chunks;
    } );
  })

I can see some obvious dumbness in my examples but the general idea is to be able to use a stream parser to not have to wait for the text and then parse it