Skip to content

Instantly share code, notes, and snippets.

@hamiltop
Last active January 28, 2022 07:15
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hamiltop/376d25058b996aa75afc0b5323533775 to your computer and use it in GitHub Desktop.
Save hamiltop/376d25058b996aa75afc0b5323533775 to your computer and use it in GitHub Desktop.
Example of Node, Typescript, and Comlink
import { getRemoteAPI } from "./my_worker";
async function init() {
console.time("launch");
const api = getRemoteAPI();
console.timeLog("launch");
console.time("first result");
console.timeLog("first result", await api.doMath());
console.time("second result");
console.timeLog("second result", await api.doMath());
await api.doMath();
}
init();
import { parentPort, Worker, isMainThread } from "worker_threads";
import * as Comlink from "comlink";
import * as nodeEndpoint from "comlink/dist/umd/node-adapter";
const api = {
doMath() {
return 4;
}
};
export type API = typeof api;
export function getRemoteAPI(): Comlink.Remote<API> {
// Have to hack for typescript. `worker.js` is a wrapper that loads whatever
// we specify in `workerData.path`.
const worker = new Worker("./worker.js", {
workerData: {
path: "./my_worker.ts"
}
});
return Comlink.wrap(nodeEndpoint.default(worker));
}
// Because we are using this file on the main thread (to have the helper available)
if (!isMainThread && parentPort) {
//Comlink.expose(api, nodeEndpoint.default(parentPort));
}
const path = require("path");
const { workerData } = require("worker_threads");
require("ts-node").register();
require(path.resolve(__dirname, workerData.path));
@hamiltop
Copy link
Author

Output:

$ ts-node index.ts
launch: 6.881ms
first result: 877.905ms 4
second result: 0.201ms 4

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment