Created
June 12, 2020 05:26
-
-
Save CatsMiaow/cc07796aee448b391970798d972302e0 to your computer and use it in GitHub Desktop.
Comlink example for Node.js with TypeScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* https://github.com/GoogleChromeLabs/comlink/blob/master/docs/examples/06-node-example/main.mjs | |
* https://github.com/GoogleChromeLabs/comlink/issues/476#issuecomment-642765445 | |
* esModuleInterop to true in tsconfig.json compilerOptions. | |
*/ | |
import { Worker } from 'worker_threads'; | |
import * as comlink from 'comlink'; | |
import nodeEndpoint from 'comlink/dist/umd/node-adapter'; | |
import { cpus } from 'os'; | |
import type { Api } from './worker'; | |
const workers = new Set<comlink.Remote<Api>>(); | |
function startWorkers() { | |
const count = cpus().length; | |
for (let i = 0; i < count; i += 1) { | |
const worker = new Worker(`${__dirname}/worker.js`, { workerData: { idx: i } }); | |
workers.add(comlink.wrap<Api>(nodeEndpoint(worker))); | |
} | |
} | |
function stopWorkers() { | |
workers.forEach((worker) => worker.exit()); | |
} | |
(async () => { | |
startWorkers(); | |
const promises = []; | |
for (const worker of workers) { | |
promises.push(worker.calc(Date.now())); | |
} | |
console.time('comlink'); | |
console.log(await Promise.all(promises)); | |
console.timeEnd('comlink'); | |
stopWorkers(); | |
})(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* https://github.com/GoogleChromeLabs/comlink/blob/master/docs/examples/06-node-example/worker.mjs | |
*/ | |
import { parentPort, workerData } from 'worker_threads'; | |
import * as comlink from 'comlink'; | |
import nodeEndpoint from 'comlink/dist/umd/node-adapter'; | |
if (!parentPort) { | |
throw new Error('InvalidWorker'); | |
} | |
export class Api { | |
private initData = workerData; | |
public calc(time: number): number { | |
const label = `${this.initData.idx}. calc-${time}`; | |
console.time(label); | |
let n = 0; | |
for (let i = 0; i <= 1000000000; i += 1) { | |
n += Number(i); | |
} | |
console.timeEnd(label); | |
return this.initData.idx * n + time; | |
} | |
public exit(): void { | |
return process.exit(); | |
} | |
} | |
comlink.expose(new Api(), nodeEndpoint(parentPort)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
👍 Thank you, setting the type wasn't clear to me from the docs