Modular Node.js App Structure
I wrote a post on a monolitic app structure a while back. However, I never revisited that post and provided the way I actually organize my node applications. So at long last, here is that post.
To preface, the apps I work on these days are primarily realtime backend services, interfacing with cassandra, kafka, and redis pub/sub, all over express. On initialization of an express app, you will get a
In following this same modular pattern, I decided on the following:
1 2 3 4 5 6 7 8 9 10
Using this structure, you essentially have small modular “apps” (resources) that you can just move around or even drop into another node backend service. By the way, although
app somewhat makes sense, this directory may also simply be called
resources. I just like my resources to be at the top of the directory, so
app works for me. It’s easier for me as a Vim user (NERDTree plugin in this case) where I like to leave the tree open.
You will notice that
models/ are on the same level as
app/. This is because resources may not necessarily be tied to one model and may share models with other resources.
config/ directory is used to host configurations for components such as persistence stores, caching, app configs, and others. Each of these files is responsible for specifying their own configs per environment.
lib/ directory is fairly standard, in that it is responsible for initializing the configs and enabling various 3rd party modules.
test/ directory is standard to mocha. Typically, I have a test helper file to enable test environment-specific options.
Here is an example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
Of course no one in the node community has been able to assert one end-all-and-be-all application structure yet. This is fine if people can find what works best for them. The application structure described in this post tries to establish a modular, logical, and clean way to organize a node application.