File validation with fs.stat always fail
Problem
I wrote a little function to validate a path image:
var validateImage = function(image) {
fs.stat('/images/' + image, function(err, stats) {
if(stats.isFile()) {
return true;
}
});
};
It simply checks if the image parameter, that would be something like "myimage.jpg"
exists under my public/images directory.
I can access the image at:
http://127.0.0.1:3000/images/myimage.jpg
However validateImage("myimage.jpg")
always return false.
The images directory is under /public
, which is defined at my app.js:
app.use(express.static(path.join(__dirname, 'public')));
What am I missing?
Solution
'/images/'
is an absolutely path, it will not check inside your public/images directory.
You can make the url relative to your Node scripts by using __dirname
.
Your directory structure is something like this, it seems
root
public
images
app.js
You can do this:
fs.stat(__dirname + '/public/images/' + image, ...
Discussion
View additional discussion.