Node.JS + Sails.JS. Custom image if image in specific directory not found
Question
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)
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.
OTHER TIPS
you can use the node.js fs module
var fs = require('fs');
var imagePath = '/images/avatars/thumbnails/ID.png';
fs.open(imagePath, 'r', function(err,fd){
if(err) imagePath = 'path/to/custom/image.png';
else console.log('user image exists');
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow