Skip to content

Instantly share code, notes, and snippets.

@giuseppeg
Last active September 6, 2020 12:49
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save giuseppeg/7cabba93800628f7482a488667895cb1 to your computer and use it in GitHub Desktop.
Save giuseppeg/7cabba93800628f7482a488667895cb1 to your computer and use it in GitHub Desktop.
// RN's fetch seems to not handling responses with other charsets correctly like Node.js does
// eg. the following link returns content-type: "text/html; charset=ISO-8859-1"
// https://www.corriere.it/cronache/20_marzo_13/coronavirus-ultimi-aggiornamenti-dall-italia-mondo-d4c07168-64f4-11ea-ac89-181bb7c2e00e.shtml
// response.text() resolves to undefined
const src = await fetch(url)
.then(response => {
const charset = (response.headers.get("content-type") || "").split(
"charset="
)[1];
if (!charset || charset.toLowerCase() === "utf-8") {
return response.text();
}
return response.blob().then(blob => [blob, charset]);
})
.then(result => {
if (Array.isArray(result)) {
let resolve, reject;
const readingPromise = new Promise((res, rej) => {
resolve = res;
reject = rej;
});
const fileReader = new FileReader();
fileReader.addEventListener("loadend", result => {
resolve(fileReader.result);
});
fileReader.addEventListener("error", reject);
fileReader.addEventListener("abort", reject);
const [blob, charset] = result;
fileReader.readAsText(blob, charset);
return readingPromise;
}
return result;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment