Last active
January 28, 2022 07:15
-
-
Save hamiltop/376d25058b996aa75afc0b5323533775 to your computer and use it in GitHub Desktop.
Example of Node, Typescript, and Comlink
This file contains hidden or 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
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(); |
This file contains hidden or 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
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)); | |
} |
This file contains hidden or 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
const path = require("path"); | |
const { workerData } = require("worker_threads"); | |
require("ts-node").register(); | |
require(path.resolve(__dirname, workerData.path)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output: