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:

1
2
3
4
5
6
// index.js
const { Worker } = require("node:worker_threads");

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

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.

Love it? Hate it? Have something to say? Let me know at comments@nalanj.dev.