O'Reilly logo

Hands-On Microservices with Node.js by Diogo Resende

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Checking an image exists in the folder

We can now create a route to check whether an image exists in our uploads folder. We'll use the HEAD verb. If you're not familiar with it, it's just like a GET request, but without a body (no content). It's used to request only information (headers) from a path.

app.head("/uploads/:image", (req, res) => {    fs.access(        path.join(__dirname, "uploads", req.params.image),        fs.constants.R_OK ,        (err) => {            res.status(err ? 404 : 200);            res.end();        }    );});

We'll look for a similar route, but this time we're only handling HEAD requests. This is a simple check. We just question if the current process has read access to the local file.

fs.access(path, mode, callback);

If so, we'll reply with HTTP response code 200

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required