I’m not saying this trick is bullet-proof, or even a necessarily good idea for production. But it seems like a good thing for testing and perhaps for getting a project off the ground with some prototyping. It also serves as a small example of how to write an Express Middleware2.
With that caveat I will present you with the code and explanation of it3.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
The part that concerns us are lines 12-18. This section is telling
Express that if a request comes in with a path starting with
that we will want to do some special processing on it.
Line 13 determines the path to the CoffeeScript file (which is in the
../clientdirectory relative to our current directory). Of note here is that
request.pathdoes not contain the
/clientpart of the path and
__dirnameis the directory of the currently executing file.
Line 14 sets up the reading of this CoffeeScript file. It is important to specify the encoding otherwise the Coffeescript compile will throw an error.
If there is an error reading the file (line 15), such as the file not existing, then we tell express to run whatever is the next rule (eventually if no other rules work Express will send a
If we can read the file then we use CoffeeScript to compile that file (line 18) and send that data back as the response (lines 16-18). (Of note here is that we set the content type to be
Congratulations, we’ve just written an Express Middleware!