Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions 5-network/01-fetch/article.md
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,26 @@ let text = await response.text(); // read response body as text

alert(text.slice(0, 80) + '...');
```
If you are dealing with non UTF-8 charset pages, use `.arrayBuffer()` to get binary text and `TextDecoder()` to decode it into a specific encoding:

```js run
fetch('/article/fetch/non-utf8-page.html')
.then( response => response.arrayBuffer() )
.then( bytes => {
let krDecoder = new TextDecoder('EUC-KR');
let decodedHtml = krDecoder.decode(bytes);
return decodedHtml;
})
.then( html => {
let parser = new DOMParser();
let doc = parser.parserFromString(html,'text/html');
return doc.documentElement.outerHTML;
})
.then( result => alert(result) )
.catch( err => {
console.warn('Error occurred. ', err);
});
```

As a show-case for reading in binary format, let's fetch and show a logo image of ["fetch" specification](https://fetch.spec.whatwg.org) (see chapter [Blob](info:blob) for details about operations on `Blob`):

Expand Down
6 changes: 6 additions & 0 deletions 5-network/01-fetch/non-utf8-page.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<!DOCTYPE html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=euc_kr">
</head>
<body>한글</body>
</html>