Skip to content

Instantly share code, notes, and snippets.

@mfdj
Last active June 19, 2021 04:57
Show Gist options
  • Save mfdj/fef9d52609d771b78a81c85ff44442a3 to your computer and use it in GitHub Desktop.
Save mfdj/fef9d52609d771b78a81c85ff44442a3 to your computer and use it in GitHub Desktop.
General use body-logger to use with browser fetch - riffing on https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream/getReader
/*
fetch('http://example.com')
.then(res => res.ok ? logReadableStream(res.body) : Promise.reject(`Status: ${res.status}`))
.catch(console.log)
*/
let logReadableStream = function (stream) {
const reader = stream.getReader();
let bytesReceived = 0;
let result = new Uint8Array(0);
const readableStreamLogger = function ({ done, value }) {
if (done) {
console.log('Stream complete: ' + new TextDecoder('utf-8').decode(result));
return;
}
bytesReceived += value.length;
console.log('Received ' + bytesReceived + ' bytes so far');
// value for fetch streams is a Uint8Array
const nextResult = new Uint8Array(result.length + value.length)
nextResult.set(result);
nextResult.set(value);
result = nextResult;
return reader.read().then(readableStreamLogger);
};
return reader.read().then(readableStreamLogger);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment