LoginSignup
22
23

More than 5 years have passed since last update.

[Node]画像をバイナリデータで取得する時にはまった

Last updated at Posted at 2016-03-30

画像をバイナリデータで取得する時にはまった

requestを使って画像を取得、ヘッダーから画像フォーマットの情報を取得しようとした際にハマったので共有。

JavaScript
const request = require('request');

request.get(IMAGE_URL, function(error, response, body) {
  var buffer = new Buffer.from(body);
  console.log(buffer);
});

これで取得できると思ったが以下のようになった。
スクリーンショット 2016-03-31 0.48.42.png
上が正しい画像データで、下がコードの実行結果。
内容が違う...(jpgなのでFF D8からはじまるはず)

解決方法

request - npmに書いてありました。

encoding - encoding to be used on setEncoding of response data. If null, the body is returned as a Buffer. Anything else (including the default value of undefined) will be passed as the encoding parameter to toString() (meaning this is effectively utf8 by default). (Note: if you expect binary data, you should set encoding: null.)

つまりバイナリデータを期待する場合はencodingnullにセットしなければならない

それを考慮すると....

JavaScript
const request = require('request');

request.get(IMAGE_URL, {encoding: null},function(error, response, body) {
  var buffer = new Buffer.from(body);
  console.log(buffer);
});

実行して上下同じ結果になったので成功です。
スクリーンショット 2016-03-31 1.16.17.png

22
23
1

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
22
23