Search code examples
angularjsnode.jsmongoosemeanmulter

Saving Location of Scraped Image to DB - Node/MEAN


After scraping an image I'm able to download to a folder using request. I would like to pass along the location of this image to my Mongoose collection.

In the callback I think there should be a way to save the location so I can pass this along when saving my model object.

exports.createLook = function(req, res) {
  var url = req.body.image;
  var randomizer = '123456';

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

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

  download(url, '../client/assets/images/' + randomizer + '.jpg', function() {
    console.log('done');
    // do something?
  });

   // now get model details to save
   var newLook = new Look();
   newLook.title = req.body.title;
   newLook.image =       // image location

   newLook.save(function(err, look) {
     if(err) return res.send(500);
  } else {
    res.send(item);
  }
}

Solution

  • Assuming that 'randomizer' will be generated I would do:

    exports.createLook = function(req, res) {
      var url = req.body.image;
      var randomizer = getSomthingRandom();
    
      var download = function(url, filename, callback) {
    
        request(url)
          .pipe(fs.createWriteStream(filename))
          .on('close', callback(filename);
      };
    
      download(url, '../client/assets/images/' + randomizer + '.jpg', function(filename) {
        console.log('done');
        // now get model details to save
        var newLook = new Look();
        newLook.title = req.body.title;
        newLook.image = filename;
        ....
      });