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.
Comments
Post a Comment