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, which means Found. If not, we'll reply with HTTP response code 404, which means Not Found:
res.status(err ? 404 : 200);
Add the preceding code and restart the service.
If you use curl to check for our previously uploaded file, you'll receive something like this:
curl --head 'http://localhost:3000/uploads/example.png'
HTTP/1.1 200 OK
X-Powered-By: Express
Content-Length: 0
Connection: keep-alive
If you change the path to something else, you should receive something like this:
curl --head 'http://localhost:3000/uploads/other.png'
HTTP/1.1 404 Not Found
X-Powered-By: Express
Connection: keep-alive