Skip to content

Instantly share code, notes, and snippets.

@phenomnomnominal
Last active Jan 22, 2021
Embed
What would you like to do?
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