Serving static files with express/nodejs

express, node.js

Solution

This is the standard way if you don't need high performance or something specific. It doesn't start a separate server, instead when a request comes, it checks the path to see if a file with the specified name can be served from one of the dirs you added as static.

There are two main things you can do for performance. The first one is an easy fix - if you add `express.static` before the rest of the handlers, every request will incur a disk read to check if a file with that name exists. You can fix this by just putting the static middleware last (or by mounting it at a prefix: e.g. `/static`).

If that's not good enough for you, the standard solution would be to put a high performance server in front of your node.js server. An example would be an nginx server, which is highly optimized for serving static files. It can handle the requests for static files and redirect the rest of them to your node app.

Problem

I've set up static files to be served like this: ``` app.use(express.static(__dirname)); app.get('/', function(req, res) { res.locals.message = 'Hello!'; res.render('index'); }); ``` And this seems to work. Is this how it is usually done? I am a bit confused as to if `static` starts its own server on the same port, and if that is the case, is it a good idea?

Original source