The “require” function is used often in Node.js applications. Node allows you to require modules from different files and use their content in other parts of your application. The “require” function also maintains a cache. Now, most would not touch the cache. But today, let’s talk about the cache and how we can use it to improve our workflow.
The “Require” Cache
The “require” function maintains a cache that contains all the contents that were loaded into the running program. This is for efficiency reasons; loading modules repeatedly would only serve to slow down a program in the long run. However, the information on the cache is useful to us, because we know now the code is maintained within the loaded module.
Now, we know how the cache works. But, how can we leverage this in our program? The answer is managing the cache; by doing so we can reload/update modules at different points in our application. Now, let’s go into cache management.
As a developer, I’m sure a cache has caused you issue from time to time (Google Chrome Developer tools cache anyone?). A cache is useful, but being able to reload services in our program can be beneficial to development as a whole. Imagine updating your business services without taking down your application. That can be extremely beneficial when people rely on your services. This deserves an example.
Here’s an example of cache management from a Discord side project of mine.
In this example, we created a function that can run commands once the path to the module(where it is on the computer system) is resolved. Once the path is resolved, it requires the module and runs the ‘run’ function within the context of our application. The actual module is now maintained in the cache and will not be reloaded from the underlying file system. Now, let’s look at a function that helps manage the cache.
Here’s an example of the reload function that removes the cache contents in the same project.
Now, because in our previous example we require the module before executing the code in the context of our program, require will reload a new version of our module when the command is called allowing us to maintain and improve our services dynamically. Awesome!
Personally, I think this shows a lot of the power behind server side work. As a developer, I don’t often think of using the underlying file system in this way when building programs. But, the idea can help build out a more robust architecture in our code that uses not only our coding tools but the platform(machine) we’re working on. So, in the future think of the places, your program will run and consider the solution that covers the lowest common denominator.