user606521
user606521

Reputation: 15454

How to convert string into binary buffer?

I have two pieces of code:

var mmmagic = require('mmmagic');
var request = require('request');
var magic = new mmmagic.Magic(mmmagic.MAGIC_MIME_TYPE);

data = fs.readFileSync('/Users/myaccount/Desktop/test.png');
magic.detect(data,function(err,mime){
    console.log(mime); // prints 'image/png'
}

and

var mmmagic = require('mmmagic');
var request = require('request');
var magic = new mmmagic.Magic(mmmagic.MAGIC_MIME_TYPE);

request.get('https://www.google.pl/images/srpr/logo11w.png',function(err,res,data){
    data = new Buffer(data); // tried also new Buffer(data,'binary');
    magic.detect(data,function(err,mime){
        console.log(mime); // prints 'application/octet-stream'
    }
})

So first one checks mime type of file from local disk and its 'image/png'. The second one downloads image from url (its google logo in png format) from url and check its mime type and it is 'application/octet-stream'.

How I can convert response from request (which is a string) to a binary buffer so mime detection would return 'image/png'??

Upvotes: 2

Views: 1202

Answers (1)

Jay
Jay

Reputation: 19887

You have to pass in the option encoding: null

var mmmagic = require('mmmagic')
, request = require('request')
, magic = new mmmagic.Magic(mmmagic.MAGIC_MIME_TYPE)
, image = 'https://www.google.pl/images/srpr/logo11w.png';

request({
    uri: image,
    encoding: null
}, function(err, res, data) {

    console.log(typeof data);
    console.log(data.constructor);

    magic.detect(data, function(err,mime) {
        console.log(mime); // prints 'image/png'
    });
});

I noticed that data was a string when using request.get(<urlString>). For debugging purposes I used typeof <something> & <something>.constructor to determine what <something> really was.

The docs are a little misleading stating that

encoding - Encoding to be used on setEncoding of response data. If null, the body is returned as a Buffer.

Making one think that the default would be a Buffer!

Upvotes: 3

Related Questions