javascript - Node.js: how to request an image only if it changed -


i'm designing node.js app.
1 of tasks regularly download set of images public, external, site.
1 requirement avoid repeating download of images not changed previous download.
plan use "request" module, since far more complete , flexible respect other networking modules (please correct me if i'm wrong).

this code i'm using (please ignore mistakes, comparing dates > or < operators, consider pseudo-code...):

var request = require('request'); var myresource = {   'url': 'http://www.example.com/image1.jpg',   'last-modified': 'mon, 28 sep 2015 08:44:06 gmt' };  request(   myresource.url,   { method: 'head'},   function (err, res, body) {     if (err) {       return console.error('error requesting header:', err);     }     var lastmodifieddate = res.headers['last-modified'];     console.log('last modified date:', lastmodifieddate);     if (lastmodifieddate > myresource['last-modified']) { // resource did change       request(         myresource.url,         function (err, response, contents) {           if (err) {             return console.error('error requesting content:', err);           }           myresource['last-modified'] = lastmodifieddate;           storecontents(contents); // store contents db         }       );     }   } ); 

this code should work (in principle).
ask: request() called twice: waste of resources?
content request someway chained first request?
can suggest cleaner / smarter / faster approach?

maybe i'm missing something, if know last-modified date, should send if-modified-since header get request , skip head request. server should return 304 when appropriate.

how "304 not modified" works?


Comments

Popular posts from this blog

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -