Created
July 18, 2022 09:19
-
-
Save rarous/4e82a4dfbe2b116fe7817deb27e1c960 to your computer and use it in GitHub Desktop.
Reads fetched response with declared charset
This file contains 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
/** | |
* 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