In Node.js, given a URL, how do I check whether its a jpg/png/gif? In Node.js, given a URL, how do I check whether its a jpg/png/gif? node.js node.js

In Node.js, given a URL, how do I check whether its a jpg/png/gif?


Just read the first bytes of the stream, and check it for the so called "magic number".

Magic numbers are the first bits of a file which uniquely identify thetype of file.

For example:
-Every JPEG file begins with ff d8 (hex).
-Every png file begins with a 89 50 4e 47.
-There is a comprehensive table of magic numbers here

This way even if you have a file without extension you can still detect its type.
Hope this helps.


This code shows a working solution for the magic numbers approach (summary of the existing answers and information on https://github.com/request/request).

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 magigNumberInBody = body.toString('hex',0,4);        if (magigNumberInBody == magic.jpg ||             magigNumberInBody == magic.png ||            magigNumberInBody == magic.gif) {            // do something        }    }});