Using the standard request module, we can run the following script to check a file's MIME type;
var request = require('request');
var url = "http://www.somedomain.com/somepicture.jpg";
var magic = {
jpg: 'ffd8ffe0',
png: '89504e47',
gif: '47494638'
};
var options = {
method: 'GET',
url: url,
encoding: null // keeps the body as buffer
};
request(options, function (err, response, body) {
if(!err && response.statusCode == 200){
var magicNumberInBody = body.toString('hex',0,4);
if (magicNumberInBody == magic.jpg ||
magicNumberInBody == magic.png ||
magicNumberInBody == magic.gif) {
console.log("It's an image!");
return true;
}
}
});
Which is pretty self-explanatory. However, when working with node.js and relying on Promises, how can we carry out the above? I've attempted to install and use request-promise, and wrote up the following script;
return rp("http://www.somedomain.com/somepicture.jpg")
.then((response) => {
var magicNumberInBody = response.toString('hex',0,4);
console.log(magicNumberInBody);
if (magicNumberInBody == magic.jpg ||
magicNumberInBody == magic.png ||
magicNumberInBody == magic.gif) {
console.log("It's an image!");
return true;
}
However, for anything that's not html/txt based, request-promise seems to just return with the raw binary.
Would anyone know how I can change the above data into something meaningful, which I can easily use to identify if the MIME type is jpg/png/gif?