WorkerWrapper
This file defines the WorkerWrapper
class, which acts as a wrapper for worker threads in the @sodacore/core
library. It manages IPC (inter-process communication) between the main thread and the worker, dynamically imports the worker module, and executes exposed methods in response to incoming messages.
Features
- Dynamic Module Import: Loads and instantiates the worker module from a specified filename.
- IPC Handling: Listens for messages from the main thread and dispatches them to the appropriate module methods.
- Method Execution: Executes requested methods on the worker module and returns results or errors via IPC.
- Initialization Support: Handles special
init
command to initialize the worker module.
Usage
import WorkerWrapper from './module/worker';
const worker = new WorkerWrapper('/path/to/worker-module.js');
await worker.init();
// IPC messages from the main thread will be handled automatically.
API
Constructor
constructor(protected filename: string)
- filename: The path to the file containing the worker module to load.
Methods
async init(): Promise<void>
Dynamically imports and instantiates the worker module. Calls its init
method if present.
async handleIpc(message: IWorkerMessage): Promise<void>
Handles incoming IPC messages:
- If the command is
'init'
, initializes the module and responds with an acknowledgment or error. - For method calls, checks if the method exists on the module, executes it with provided arguments, and posts the result or error back to the main thread.
How It Works
Initialization: Creates a new instance of the worker module and calls its
init
method if available.IPC Handling: Listens for messages from the main thread. Handles the
'init'
command and method invocation requests.Method Execution: When a method call message is received, verifies the method exists, executes it with the provided arguments, and sends the result or error back via
postMessage
.
Notes
- The worker module must export a class with methods to be invoked via IPC.
- Only methods that exist on the module can be called; otherwise, an error is returned.
- This class is used internally by the worker bootstrap process and is not intended for direct use in application code.