Skip to content

Instantly share code, notes, and snippets.



Last active Aug 29, 2015
What would you like to do?
External image cacheing
var Promise = require("bluebird");
var bhttp = require("bhttp");
var currentImage;
function fetchNewImage(){
var fetchPromise = Promise.try(function(){
/* You can replace this with anything that returns a promise, really... */
return bhttp.get("");
/* We just want the body, which is the image data as a Buffer... */
return response.body;
if (currentImage == null) {
/* First time we're fetching the image, set the promise immediately. */
currentImage = fetchPromise;
} else {
/* Not the first time; we only update the currentImage value once we're done fetching it. */
currentImage = fetchPromise;
setTimeout(fetchNewImage, 10 * 60 * 1000); // every 10 minutes
fetchNewImage(); // fetch it the first time
/* Actually using the image: */
app.get("/image", function(req, res){
currentImage.then(function(image){ // this will only run once we *have* an image
res.set("Content-Type", "image/png"); // or whatever content-type is appropriate for the image
/* Possible scenarios here:
* 1) Image fetched for the first time, not done yet; the /image route will wait for completion.
* 2) Image fetched for the first time, done; the .then in the /image route triggers immediately.
* 3) Image fetched for the Nth time, not done yet; currentImage still has the old image, and triggers immediately.
* 4) Image fetched for the Nth time, done; currentImage is replaced with the new image we completed fetching just now.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.