DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Alan Johnson
Alan Johnson

Posted on

An Experiment With Dynamic Loading

I've been thinking about how to hot reload within server code to improve my development experience a lot lately. One thing that doesn't appeal to me much is using something like webpack and its HMR implementation, primarily because it has a lot of tricky implementation details when handling things like reconnecting databases, etc.

One idea I had the other day was to simply try out using a Worker within node to handle the reloading. Workers run in their own interpreter, so they should work!

Here's the quick test I wrote up to in fact confirm that using Worker is feasible for dynamic loading:

// index.js
const { Worker } = require("node:worker_threads");

const t = setInterval(() => {
  new Worker("./worker.js");
}, 1000);
Enter fullscreen mode Exit fullscreen mode
// worker.js
console.log("WORKER", "1", new Date());
Enter fullscreen mode Exit fullscreen mode

Running node index.js causes the process to start and spawn a new worker every second. And indeed, if I edit the worker.js file the updates are displayed on the next execution of the file.

It should be feasible to build an HTTP server that loads in a worker on every request and processes the request with the latest copy of the code.

Latest comments (0)

Timeless DEV post...

How to write a kickass README

Arguably the single most important piece of documentation for any open source project is the README. A good README not only informs people what the project does and who it is for but also how they use and contribute to it.

If you write a README without sufficient explanation of what your project does or how people can use it then it pretty much defeats the purpose of being open source as other developers are less likely to engage with or contribute towards it.