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

File validation with fs.stat always fail

File validation with fs.stat always fail


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:

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?

Problem courtesy of: jviotti


'/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


You can do this:

fs.stat(__dirname + '/public/images/' + image, ...
Solution courtesy of: loganfsmyth


View additional discussion.

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

Share the post

File validation with fs.stat always fail


Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription