Replies: 1 comment
|
A If you control the file operations, pass a base directory and resolve paths against it instead: // main.mjs
import { Worker } from 'node:worker_threads';
import { fileURLToPath } from 'node:url';
const worker = new Worker(new URL('./worker.mjs', import.meta.url), {
workerData: {
baseDir: fileURLToPath(new URL('./data/', import.meta.url)),
},
});
worker.on('message', console.log);
worker.on('error', (error) => {
console.error(error);
process.exitCode = 1;
});// worker.mjs
import { parentPort, workerData } from 'node:worker_threads';
import { readFile } from 'node:fs/promises';
import { resolve } from 'node:path';
const text = await readFile(resolve(workerData.baseDir, 'input.txt'), 'utf8');
parentPort.postMessage(text);Create If a library requires its own actual working directory, run it in a child process instead: import { fork } from 'node:child_process';
const child = fork(new URL('./child.mjs', import.meta.url), [], {
cwd: new URL('./data/', import.meta.url),
});
child.on('error', console.error);Here References: Worker limitations, fork's cwd option. Locally verified on Windows with Node v25.3.0: explicit-path reads in a worker succeeded, worker |
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
process.chdirallows changing node's working directory. When using a Worker fromworker_threadsit is not available though.How can I customize a worker thread's directory e.g. upon startup?
All reactions