There are lots of tutorials written to teach people how to use popular Node modules to handle routes and creating http servers, like Express or Koa. We all get too spoiled by the easiness of Node packages that we forget how easy to use Node core functions are. It’s tempting to import a library for every functionality we want to implement, but we should step back and think if that’s really what we need.
One of the main use cases for using only native modules is tests. Each test case is written for one scenario only. The code does not need to be extensible, because it’s not exported to anywhere else. The DRY (don’t repeat yourself) rule don’t apply to tests. You want to repeatedly test every scenario using slightly different case.
Packages like Express can handle a lot of cases for you, like taking in different types of routes, makes it easy to handle errors and then some. This makes the development process much faster but for tests these benefits irrelevant. A lot of things can happen because it depends on so many modules. I’ve run into many cases when there is a vulnerability found in a package that’s a submodule of a submodule of a submodule of a very reputable and well-maintained module, and our CICD process fails for a couple of days before we can put a patch in the module in question. The last thing a developer wants to fix in a failing test is the test itself.
In my experience, Node core is much more stable than any other node modules. It’s a very rare scenario that Node itself would break something and a library picks up the slack, which has been my experience following contributors of Node core and when they hear the needs of users and module developers regardless if they’re independent devs or large companies.
There’s also nothing worse than jumping into a big Node.js codebase where there are packages that’s 3.2M and only ~30 lines of code is used. Although, another bad practice is to write your own implementation for functionalities that have been well established by commonly used modules, and leave it poorly documented or tested. It’s a balance, and you as an engineer have to decide what to do based on your scenario.
tl;dr
- Use only native node modules in tests
- Node core is much more stable
- Reduce node_module size
Without further ado, here’s a snippet I always use to serve up pages quickly.
Continue reading Using the Native Node http Module to Start a Node Server, When and Why