Shift_JIS を fetch する
- カテゴリ:
- JavaScript
- コメント数:
- Comments: 1
◆ text() は UTF-8 のみ
◆ TextDecoder を使う
◆ 一応 FileReader でもできる
◆ TextDecoder を使う
◆ 一応 FileReader でもできる
fetch と encoding
fetch でテキストファイルを取得すると文字化けしてましたやっぱり Chrome の自動判定はダメだなぁ……あれ でもこれちゃんと Content-Type がレスポンスヘッダにあるはずだけど
devtools の Network タブで通信を見てみても
Content-Type:text/html;charset=Shift_JIS
なのに出力したテキストは
<h1>����</h1>
調べてみたら Response の text メソッドは UTF-8 固定らしいです
https://developer.mozilla.org/ja/docs/Web/API/Body/text
となるとバイナリデータから自分で文字列化する必要があります
TextDecoder
シンプルなのは TextDecoder を使うことですArrayBuffer でレスポンスボディを取得して decode します
!async function() {
const res = await fetch("sjis.html")
const ab = await res.arrayBuffer()
const td = new TextDecoder("Shift_JIS")
console.log(td.decode(ab))
}()
// <h1>あああ</h1>
ちゃんと日本語が表示されました
FileReader
FileReader を使うこともできますblob でレスポンスボディを取得してそれを readAsText でテキスト化します
第二引数で encoding を指定できます
!async function() {
const res = await fetch("sjis.html")
const blob = await res.blob()
const fr = new FileReader()
fr.onload = eve => console.log(fr.result)
fr.readAsText(blob, "Shift_JIS")
}()
// <h1>あああ</h1>
TextDecoder のない IE ならこっち……と思いましたが IE はそもそも fetch がないですね