Help us understand the problem. What is going on with this article?

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

More than 1 year has passed since last update.

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

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

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした