I recently found myself needing to support an unknown URL folder structure with an Express router. The gist of it is that I am serving video files that may or may not be in a sub-folder, from another service.
For example, I need to have all of these URLs handled by the same Express router:
- /files/foo.mp4
- /files/bar/quux.mp4
- /files/wombat/baz/stuff.mp4
- /files/i/dont/know/how/many/folders/file.mp4
The request coming into my server will be logged and forwarded to the actual host, and it would be easier for me to maintain the same folder structure as the actual host.
And after some digging, I found there are at least three ways to make this work – most of which involve copy & paste programming.
The Hard Way
The really hard way of handling this is to manually code each of the supported folders. I call this “hard” because it involves a lot of duplicated code – copy and paste programming.
An Easier Way
Shortly after I realized how terrible it is to hard code folder, because of 1) the duplicated code, and 2) the limited sub-folders and nesting that I could support while doing this manually, I found a way to optionally specify any number of sub-folders:
Adding the asterisk after the :folder parameter name allows Express to use any number of folders at that point in the URL.
But this doesn’t work with no folders – files at the root of the URL mount – so I ended up with 2 routing entries, still:
While 2 entries instead of 10 or 15 or more is a pretty big improvement, I wanted to do better. This is still a tiny bit of copy & paste in the URL definitions, even if the handler function was re-used.
The Really Easy Way
With some further digging through google and stackoverflow, I eventually found the answer I needed for my route setup:
By adding the ? to the end of the folder parameter with the asterisk, I am telling Express that there will be zero or more folders. This allows me to have a single route definition that handles all of my use cases – no folders, all the way out to as many nested folders as needed.
Very Express-ive Routes
Express allows for some very complex and expressive routing setup, with many different options to get the job done. It wasn’t until I really starting digging into this need that I saw the use of regular expressions and wildcards, though.
The more I work with express, the more I seem to learn from it and the more I want to continue working with it to really master every last detail.
If you’re interested in Express and want to see how I build large apps, join me at WatchMeCode and check out the Architecting Express series, and the follow-on series. You’ll get an over-the-shoulder view of how small Express apps can be composed into larger systems.