LoginSignup
7
8

More than 5 years have passed since last update.

hubot で utf-8 以外のページも取得していろいろしたい

Posted at

まず request を使いましょう。 jsdom で楽をしようなどとは思ってはいけません。
jsdom も内部で request を使っていますが結果的に utf8 決め打ちになります。死にます。

request = require('request')
iconv = require('iconv-jp')

module.exports = (robot) ->
  robot.hear /https?:\/\/\S+/i, (msg) ->
    url = msg.match[0]

    # encoding に null を渡すと body を buffer のままで返してくれる
    request.get url: url, encoding: null, (error, response, body) ->

      if 200 <= response?.statusCode < 300

        # 適当に charset をぶっこぬく
        charset = response.headers['content-type']?.match(/charset=([\w\-]+)/)?[1]
        charset = body.toString('binary').match(/charset="?([\w\-]+)"?/)?[1] unless charset?

        # utf-8 じゃなかったら iconv で変換
        if charset? && !charset.match(/utf-?8/i)
          converter = new iconv.Iconv(charset, 'UTF-8//IGNORE')
          body = converter.convert(body)

        body = body.toString()

        # なにかする

なんかたまに response が null で返ってきたりしてよくわかりませんね。

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