MeetJoeBlack
MeetJoeBlack

Reputation: 2904

node.js download image with unknown extension from url

My issue is download image from given link, but there is one trouble - I dont know image extension(bmp, jpg, png etc.) I am using request module, and succesfully download image of png extension:

var fs = require('fs');
var request = require('request');
var url = 'www.images.com/image01.';
request(url+ '.png').pipe(fs.createWriteStream('./image.png')); 

But what to do when I dont know image extension. I think maybe I can check responce and if it's = '404' , then second try to download image from: url + '.[another extension]' and so on. By its look likes callback hell.

Upvotes: 1

Views: 1405

Answers (2)

diegomaidana
diegomaidana

Reputation: 39

Make a Request to the URL, check the Content-type in the header of the request for the Mime-type of the file. You can have a file in your project, called mime-types.js

Where you download the file, you can make a request of that file:

    var mime = request('mime-types.js');

And the content of your mime-types.js file should be something like this

    const JPG = "image/jpeg";
    module.exports = {
          JPG: JPG
    }

Then you can switch between the different mime-types you have and the result of the request.

You can find mime-types here: https://en.wikipedia.org/wiki/Internet_media_type#Type_image

Upvotes: 1

supertopi
supertopi

Reputation: 3488

Perform HEAD requests and check HTTP response message Content-Type header. It should include one of the specified MIME-types for images.

Upvotes: 0

Related Questions