LoginSignup
8
8

More than 5 years have passed since last update.

SJISなgoogle.co.jpからの応答をnode.jsで文字化けさせずに受け取るには

Last updated at Posted at 2015-04-15

背景

https通信でちょっとしたテスト先にgoogle.co.jpを指定して
応答を受けると

content-type : text/html; charset=Shift_JIS

と、古いブラウザを考慮してかシフトJISで返される。

node.jsはUTF-8だと日本語の文字列もあまり気にすることなく
扱えるが、SJISだと話は別。変換ライブラリを使えば、この辺り
面倒見てもらえそうではあるが、とりあえず、素のSJISのまま
HTTPレスポンスを受けてそのままファイルに保存するには
どうするんだっけ?という復習やらリハビリw。

Content-lengthに頼らないBufferの扱い

Content-lengthが返ってくれば、これを元にBufferを長さ分確保して、
オフセット指定で、詰め込んでいけるが、そうでない場合、
Buffer.concatを使うとBufferに追加する処理ができる。

node.jsでsjisで受けたレスポンスをそのままファイルにする

var fs = require('fs');
var https = require('https');
options = {
    host: 'www.google.co.jp',
    port: 443,
    path: '/',
};
https.get(options, function(res) {
    console.log('HEADERS: ' + JSON.stringify(res.headers));

    // HTTPヘッダを見てのとおり、sjisなので、utf8指定しても無駄
    //res.setEncoding('utf8');

    // content-lengthがなくても大丈夫
    var content = new Buffer([]);

    res.on('data', function(chunk) {
        content = Buffer.concat([content, chunk]);
    });
    res.on('end', function() {
        // エンコードは黙ってるとutf8にされるので、nullを明示的に指定する。
        fs.writeFileSync("dump_sjis.txt", content, {
            encoding: null
        });
    })
});

Link

関連投稿

関連記事

8
8
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
8
8