I am creating a worker from a source string like so:
import { Worker } from "worker_threads"
const w = new Worker(mySourceCode, {eval: true})
This works fine in most cases.
However, suppose I have a CommonJS module (ESM isn’t supported in eval’ed workers) that I want to import into the worker scope. Since the worker doesn’t have a source file on the disk, there is no way I can think of to make a relative import work. This is the error message I get if I try to relative import from the path of the source file of the parent thread:
node:internal/event_target:916
process.nextTick(() => { throw err; });
^
node:internal/modules/cjs/loader:936
throw err;
^
Error: Cannot find module './c.js'
Require stack:
- /mnt/c/ME/[worker eval]
at Function.Module._resolveFilename (node:internal/modules/cjs/loader:933:15)
at Function.Module._load (node:internal/modules/cjs/loader:778:27)
at Module.require (node:internal/modules/cjs/loader:999:19)
at require (node:internal/modules/cjs/helpers:102:18)
at [worker eval]:3:20
at Script.runInThisContext (node:vm:129:12)
at Object.runInThisContext (node:vm:305:38)
at node:internal/process/execution:76:19
at [worker eval]-wrapper:6:22
at evalScript (node:internal/process/execution:75:60)
Emitted 'error' event on Worker instance at:
at Worker.[kOnErrorMessage] (node:internal/worker:289:10)
at Worker.[kOnMessage] (node:internal/worker:300:37)
at MessagePort.<anonymous> (node:internal/worker:201:57)
at MessagePort.[nodejs.internal.kHybridDispatch] (node:internal/event_target:647:20)
at MessagePort.exports.emitMessage (node:internal/per_context/messageport:23:28) {
code: 'MODULE_NOT_FOUND',
requireStack: [ '/mnt/c/Users/ME/[worker eval]' ]
}
Node.js v17.5.0
How can I relative import a module from a Worker?