LoginSignup
6
8

More than 5 years have passed since last update.

Shift_JISなサイトをgulp, BrowserSyncで文字化けさせずに表示する

Last updated at Posted at 2016-12-14

なぜかいまだにShift_JISなサイトたくさんありますね。
見る分にはShift_JISでも問題ありませんが、運用にかかわってしまうとちょっと面倒なことになります。なぜか。
BrowsersyncだとShift_JISなサイトは文字化けするから。

そこでBrowsersyncでもshift-jisが文字化けしない方法を考えてみました。

※検索するとShift_JISなhtmlをUTF-8に変換して書き出すと言うものは見つかりますが、そんな対応はしたくない、ということで以下になります。

Browsersyncのmiddlewareを使用して、Shift_JISなhtmlをUTF-8に変換してブラウザに表示させてしまいます。

package.json
"devDependencies": {
    "browser-sync": "^2.8.0",
    "gulp": "^3.9.0",
    "iconv-lite": "^0.4.15",
    "jschardet": "^1.4.1"
  }
gulpfile.js
var gulp = require('gulp'),
    browser = require('browser-sync'),
    fs = require('fs'),
    path = require('path'),
    iconvLite = require('iconv-lite'),
    util = require('util'),
    jschardet = require('jschardet'),
    url = require('url');

gulp.task('server', function() {
    browser({
    port: ****,
        server: {
            baseDir: '****',
            middleware: [
              function (req, res, next) {
                // pathnameを取得
                var urlParse = url.parse(req.url);

                // .htmlなら
                if (/\.html$/.test(urlParse.pathname)) {

                  // データ取得
                  var data = fs.readFileSync(path.join(__dirname, 'htmlデータ格納先', urlParse.pathname));

                  // 文字コード判定
                  var charset = jschardet.detect(data)

                  if (charset.encoding == 'SHIFT_JIS') {
                    // shift-jisなら文字コード変換
                    var source = iconvLite.decode(new Buffer(data, 'binary'), "Shift_JIS");
                    res.setHeader("Content-Type", "text/html; charset=UTF-8");
                    res.end(source);
                  } else {
                    // shift-jis以外
                    next();
                  }

                } else {
                  next();
                }
              }
            ]

        }
    });
});

gulp.task("default", ['server']);

これで読み込むファイルがhtmlかつShift_JISの場合に、UTF-8へ変換されBrowsersync上でも文字化けしなくなります。

単純に変換しているだけなのでjsファイルなどは諦めたほうがいい場合もあると思いますが、
cssなどは強制的に変換させても大丈夫そう。

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