Skip to content

Instantly share code, notes, and snippets.

@phenomnomnominal
Last active January 22, 2021 21:15
Show Gist options
  • Save phenomnomnominal/ad8d0f7a2a2c85099384ec86ca9e1c00 to your computer and use it in GitHub Desktop.
Save phenomnomnominal/ad8d0f7a2a2c85099384ec86ca9e1c00 to your computer and use it in GitHub Desktop.
workerRequire!
import callsite from 'callsite';
import { releaseProxy, wrap } from 'comlink';
import nodeEndpoint from 'comlink/dist/umd/node-adapter';
import path from 'path';
import { Worker } from 'worker_threads';
const WORKER_PATH = path.resolve(__dirname, './worker.js');
export function workerRequire(id) {
const [, call] = callsite();
const sourcePath = call.getFileName();
const idPath = path.resolve(path.dirname(sourcePath), id);
const requirePath = require.resolve(idPath);
const module = require(requirePath);
return new Proxy({}, {
get(_, name) {
return function (...args) {
const worker = new Worker(WORKER_PATH, { workerData: requirePath });
const api = wrap(nodeEndpoint(worker));
return api[name](...args);
};
},
});
}
import { expose } from 'comlink';
import nodeEndpoint from 'comlink/dist/umd/node-adapter';
import { parentPort, workerData } from 'worker_threads';
const required = require(workerData);
expose(required, nodeEndpoint(parentPort));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment