Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/ncpa0cpl/node-worker-bridge
https://github.com/ncpa0cpl/node-worker-bridge
Last synced: about 10 hours ago
JSON representation
- Host: GitHub
- URL: https://github.com/ncpa0cpl/node-worker-bridge
- Owner: ncpa0cpl
- Created: 2021-09-19T13:51:50.000Z (about 3 years ago)
- Default Branch: master
- Last Pushed: 2022-09-07T15:03:20.000Z (about 2 years ago)
- Last Synced: 2024-09-16T01:32:19.180Z (2 months ago)
- Language: TypeScript
- Size: 19 MB
- Stars: 1
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
## Usage
### Expose Worker methods to the main thread
```ts
// worker.cjs
import { WorkerBridge } from "@ncpa0cpl/node-worker-bridge";export const worker = WorkerBridge({ file: __filename }, () => {
const calculatePi = () => {
return "3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679";
};return { calculatePi };
});
``````ts
// main.cjs
import { worker } from "./worker.cjs";function main() {
// create a pool of 4 workers
const workerPool = worker.createPool(4);const piCalcResult1 = await workerPool.calculatePi();
console.log(piCalcResult1); // will print the pi number// terminate the pool so the program can exit
workerPool.close();
}main();
```### Expose methods from the main thread to the Worker
```ts
// worker.cjs
import { WorkerBridge } from "@ncpa0cpl/node-worker-bridge";type MainThreadMethods = {
getGlobalState(): { foo: string };
};export const worker = WorkerBridge(
{ file: __filename },
(mainThreadMethods: MainThreadMethods) => {
const loopbackFoo = async () => {
return (await mainThreadMethods.getGlobalState()).foo;
};return { loopbackFoo };
}
);
``````ts
// main.cjs
import { worker } from "./worker.cjs";const globalState = {
foo: "Hello",
};function main() {
// create a pool of 4 workers
const workerPool = worker.createPool(4, {
getGlobalState: () => {
return { ...globalState };
},
});const foo = await workerPool.loopbackFoo();
console.log(foo); // will print "Hello"// terminate the pool so the program can exit
workerPool.close();
}main();
```