Type-safe wrapper for Node.js Worker Threads
npm install typed-worker-threadsTyped Worker Threads is a library designed to make working with threads in Node.js easier, while providing type safety with TypeScript. This README will guide you through setting up and using the library in your project.
Install the package using npm or yarn or pnpm.
``bash`
npm install typed-worker-threads
1. Create a folder called threads in your project root.threads
2. Create a new file in the directory. Name it to describe the thread's purpose, for example, pdf_thread.ts or compress_thread.ts.Thread
3. In the file, import the class and create a new instance of it. Pass the path to the file that will be executed in the thread as the first argument. The path is relative to the threads directory. The second argument is the name of the thread, which is optional and defaults to the name of the file.Thread
4. Export the instance of the class.parentPort
5. In the main thread, import the created thread and use it (handle events, send messages, etc.).
6. In the worker thread, import from the created thread instance and use it.
Here's an example of how to set up a typed worker thread:
`ts
// 'compress_thread.ts' file in 'threads' directory
import { Thread } from "typed-worker-threads";
type ParentToChild = {
type: "compress";
payload: {
name: string;
buffer: ArrayBuffer;
outDir: string;
compressionLevel: number;
type: "gzip" | "deflate";
};
};
type CompressionError = {
type: "error";
payload: { error: Error };
};
type CompressionSuccess = {
type: "success";
payload: {
name: string;
path: string;
};
};
type ChildToParent = CompressionError | CompressionSuccess;
const compressionThread = new Thread
"../dist/workers/compress_worker.js",
"compress_thread"
);
export default compressionThread;
// Main thread
import compressionThread from "./threads/compress_thread";
compressionThread.worker.on("message", (message) => {
switch (message.type) {
case "success":
console.log(File ${message.payload.name} compressed successfully);
break;
case "error":
console.error(message.payload.error);
break;
}
});
// Worker thread
import { parentPort } from "./threads/compress_thread";
parentPort.on("message", (message) => {
// Make heavy computations (compress file, etc.)
// If an error occurs, send an error message to the main thread
});
`
- Thread: Class for creating and managing worker threads.parentPort
- : An instance of MessagePort to communicate with the main thread.
The "structured clone algorithm" is used to send messages between threads. Read more about it here. typed-worker-threads has a built-in type StructureCloned that describes the types that can be sent between threads safely. If you want to send a type that is not StructureCloned, you can use the transferList (supports ArrayBuffer, MessagePort, FileHandle`) option when sending a message. Read more about it here.
Typed Worker Threads is released under the BSD-3-Clause License. See LICENSE for details.