Created
September 30, 2020 22:50
-
-
Save marcbachmann/12391b927126b5f5527984f625d1c794 to your computer and use it in GitHub Desktop.
Newline Delimited JSON Stream Iterator for json streams in the browser
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const response = await fetch(`http://localhost:8080/stream`, { | |
method: 'get', | |
headers: { | |
Authorization: `Bearer SomeToken` | |
} | |
}) | |
for await (const value of ndJsonIterator(response.body)) { | |
console.log(value) | |
} | |
async function* ndJsonIterator (stream) { | |
const decoder = new TextDecoder() | |
const reader = stream.getReader() | |
try { | |
while (true) { | |
const {done, value} = await reader.read() | |
if (done) return | |
const json = decoder.decode(value, {stream: true}).trim().split('\n') | |
if (!json.length) continue | |
for (const line of json) { | |
try { | |
yield JSON.parse(json) | |
} catch (err) { | |
console.error('Failed to parse json line', line) | |
} | |
} | |
} | |
} | |
finally { | |
reader.releaseLock() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment