Today, I’m going to show how you can use that same technique to wrap an existing function for a different result–to execute it in a background process using the workerpool npm module.

Background Worker Process

Since Node.js is single-threaded, you have to be careful about performing any kind of lengthy synchronous processing, as this process will block the entire application. In many cases, you’ll want to use a robust job queue (e.g. Kue) to handle background tasks. But there are plenty of situations where a more lightweight solution will suffice–and there are countless libraries that can start up a background process (or pool of processes) and manage the interprocess communication for you.

For the purposes of this post, I’m going to use the workerpool library. Specifically, I’ll be creating a dedicated worker (one of the options for how to use workerpool).

The Function

Here’s a function that synchronously generates random data, writes the data to a file, and returns the path to that file on disk:

Depending on the size of the file being generated, this function could block the event loop for many seconds–clearly, not acceptable.

Background Process

When using a dedicated worker with workerpool, you pass the name (which can be any label) from the foreground process (the main event loop) to a background worker process which has a set of registered functions it can execute.

Here is our worker.ts file with the createRandomDataFile function registered:

This isn’t really that bad. The biggest downside is that the type signature of the function is now being defined in two places, and there’s nothing to enforce that they stay in sync. This is probably not that big of a deal for this simple example, but if the arguments included a more complicated object type, it could get out of sync and lead to an error that’s hard to catch.

The type signature of the backgroundedCreateRandomDataFile function will exactly match that of the original (with the exception of the return value being wrapped in a Promise), and it will immediately reflect any changes made to the signature of the original as well. Just what we wanted.