1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

(備忘録)fetchでShift_JIS/gzipを受ける

1
Posted at

fetch APIのResponse:text()メソッドはUTF-8にのみ対応しています

レスポンスは常に UTF-8 としてデコードされます
MDN Response: text() メソッド

潔いですね。しかし、入力データとしてShift_JISを扱わねばならない場合もあるかと思います(先日遭遇しました)。そのような場合はarrayBufferを経由し、

fetch("sampleSjisText.txt")
.then((response)=>response.arrayBuffer())
.then((arrayBuffer)=>{
  const textDecoder = new TextDecoder('shift-jis');
  const text = textDecoder.decode(arrayBuffer);
  console.log( text);
});

のようにして解釈できます

また、gzipデータが入力として与えられた場合は、

fetch("sampleGzipCompressedText.txt.gz")
.then((response)=>{
  const ds = new DecompressionStream('gzip');
  const decompressedStream = response.body.pipeThrough(ds);
  return new Response(decompressedStream).text();
})
.then((text)=>{
  console.log(text);
});

のようにして展開できます

サンプルページ

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?