Skip to content

Instantly share code, notes, and snippets.

@rarous
Created July 18, 2022 09:19
Show Gist options
  • Save rarous/4e82a4dfbe2b116fe7817deb27e1c960 to your computer and use it in GitHub Desktop.
Save rarous/4e82a4dfbe2b116fe7817deb27e1c960 to your computer and use it in GitHub Desktop.
Reads fetched response with declared charset
/**
* Reads the response text in given text encoding.
* When charset isn't defined on `content-type` header it falls back to `utf-8`.
* @param {Response} resp
* @returns {string}
*/
async function readTextResponse(resp) {
const contentType = resp.headers.get("content-type");
const [, charset] = contentType?.split("charset=");
const decoder = new TextDecoder(charset ?? "utf-8");
const buffer = await resp.arrayBuffer();
return decoder.decode(buffer);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment