Make imgur link have .png or .jpg in the end of the url with nodeJS

2.1k views Asked by At

I have a node JS application that gets images from reddit.com/r/wallpaper.

You make a request on the html page and it gets a random image and displays it on the <img>.

Problem is sometimes you get imgur urls like http://imgur.com/a/Vtav5 which cannot be displayed on the <img>, but urls like http://i.imgur.com/vjUeUVj.jpg can be displayed, on Node.js how can i get the url to become a direct image url? Heres my currently working code.

app.get('/', function (req, res) {

    r.getSubreddit(subreddit).getRandomSubmission().then(function(post){

        if(post.url.includes(".jpg") || post.url.includes(".png")){
            currentUrl = post.url;
            console.log(currentUrl);
            res.send(currentUrl);
            res.end();

        } else{
            console.log("Not a direct image URL");
            console.log(post.url);
        }

        });
    console.log("Got request");
    //res.end();


})
1

There are 1 answers

4
Tuan Anh Tran On

If it's not available via their API, best you can do is scrape it and hopefully the number of links you need to scrape won't be too large.

var Xray = require('x-ray');
var x = Xray();

x('http://imgur.com/a/Vtav5', '.post-images .post-image', [{
  url: 'a@href'
}])(function (err, res) {
    console.log(res);
})

Output:

[ { url: 'http://i.imgur.com/vjUeUVj.jpg' } ]