Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Node.JS + Sails.JS. Custom image if image in specific directory not found

Node.JS + Sails.JS. Custom image if image in specific directory not found

Problem

Is there any way to make some image returning if user accesses /images/avatars/thumbnails/ID.png and it doesn't exist? (for users without avatars)

Problem courtesy of: Nick Messing

Solution

There are a few ways to do this. The simplest that comes to mind is a route like:

// in config/routes.js
'/images/avatars/thumbnails/:thumb': 'AvatarController.show'

// controllers/AvatarController.js
var fs = require('fs');
show: function(req, res, next) {
  var path = sails.config.appPath+'/assets/images/avatars/thumbnails/'+req.param('thumb');
  fs.exists(path, function(exists) {
     if (exists) return next();
  }
  fs.createReadStream(sails.config.appPath+'/assets/images/defaultAvatar.png').pipe(res);
}

This sets a custom action to handle requests for avatar thumbnails. If the file is found, it falls back to the default action for static assets (sending it to the client). If the file doesn't exist, it streams your default avatar file to the client.

Solution courtesy of: sgress454

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Node.JS + Sails.JS. Custom image if image in specific directory not found

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×