I am fetching a large JSON file (200mb) and I want to render that data out as the data streams in. The problem I am having is that after I decode and parse the chunks that are streamed to me, a syntax error is returned to me Unexpected end of JSON input in the console. What I want to do is parse the return chunks and do something with that data as soon as I get it. However, because the ReadableStream is streamed in chunks that are unpredictable in how they are sliced, I cannot perform JSON.parse() on the return values. What sort of data massaging needs to be done to make this happen? Is there a better approach?
Here is my code:
const decoder = new TextDecoder('utf-8')
fetch("../files/response.json")
.then(response => {
const reader = response.body.getReader()
new ReadableStream({
start(controller) {
function enqueueValues() {
reader.read()
.then(({ done, value }) => {
if (done) {
controller.close() // stream is complete
return
}
var decodedValue = decoder.decode(value) // one chunk of invalid json data in string format
console.log(JSON.parse(decodedValue)) // json syntax error
// do something with the json value here
controller.enqueue(value)
enqueueValues() // run until all data has been streamed
})
}
enqueueValues()
}
})
})