0

I'm in the process of making my own Discord bot and I have no previous experience with JS. I'm making a feature that downloads and posts an image from this website: http://random.dog

I have successfully downloaded images from elsewhere when I know the exact link to the picture. Here's the relevant part of my code:

var download = function(uri, filename, callback){

request(uri).pipe(fs.createWriteStream(filename)).on('close', callback);}

download('http://random.dog/14769-27888-18622.jpg', 'dog.png',

I'm using this request module https://www.npmjs.com/package/reques , is it possible to get images without the exact URL, with that module?

WillardSolutions
  • 2,316
  • 4
  • 28
  • 38
Sharb
  • 3
  • 2
  • 4

1 Answers1

0

this who you can fetch URL dynamicaly and download picture with name you need these two module request-promise, cheerio,

var app = require('express')();

    var http = require('http').Server(app);

fs = require('fs');   

var fs = require('fs'),
    request = require('request');
//save image 

    var download = function(uri, filename, callback){
      request.head(uri, function(err, res, body){
    request(uri).pipe(fs.createWriteStream(filename)).on('close', callback);
  });
};

//get URL
var Imgpath="";
var rp = require('request-promise'),
    cheerio = require('cheerio'),
    url = require('url'),
    base = 'http://random.dog/';

var options = {
    uri: base,
    method: 'GET',
    resolveWithFullResponse: true
};
rp(options)
  .then (function (response) {
    $ = cheerio.load(response.body);
    var relativeLinks = $("img");
    relativeLinks.each( function() {
        var link = $(this).attr('src');
        var fullImagePath = url.resolve(base, link); // should be absolute 
   //pass to download to download image link is file name and base is base url
        download(base+link,link,function()
                {
            console.log("wao great we done this...THINK DIFFERENT")
        })
   });
});
app.listen(3000);
console.log("server start");
app.get('/',function(req,res){
    res.sendfile(__dirname + '/a.html');
});

enter image description here

Adiii
  • 54,482
  • 7
  • 145
  • 148