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

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?

Problem courtesy of: jviotti

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, ...
Solution courtesy of: loganfsmyth

Discussion

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

×