DEV Community

Alan Johnson
Alan Johnson

Posted on • Edited on • Originally published at nalanj.dev

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.

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay