Skip to content

Instantly share code, notes, and snippets.

@marcbachmann
Created September 30, 2020 22:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marcbachmann/12391b927126b5f5527984f625d1c794 to your computer and use it in GitHub Desktop.
Save marcbachmann/12391b927126b5f5527984f625d1c794 to your computer and use it in GitHub Desktop.
Newline Delimited JSON Stream Iterator for json streams in the browser
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