I'm using express.js on a Node server and at the moment some GET request is for static file like ZZZ.html or YY.css ... I want to identify wich url is for static file and wich is a route.
How can I do that in my middleware ?
(not sure if it's clear or not :/)
Put your static files in a public
directory and have
app.use(express.static(__dirname + '/public'));
after your routes so it will catch other requests.
You may use fs
module to determine if requested file exists.
In the simplest case your code might look like following:
app.use(function(req, res, next) {
require('fs').stat(__dirname + req.url, function(err, stats) {
var isFile = stats && stats.isFile();
//do something with isFile variable
next();
});
});
Just put it before any other routes.
Edit: doing this way you suppose that all your static files are located in the project's root dir. If your static files are in another dir (/public for example), you should write __dirname + '/public' + req.url
, and check if req.url
starts with /public
.