Skip to content

Commit 550673f

Browse files
kormidealexeagle
authored andcommitted
fix(builtin): avoid unnecessary chdir to prevent worker threads from failing
1 parent 71f4b95 commit 550673f

File tree

4 files changed

+38
-1
lines changed

4 files changed

+38
-1
lines changed

internal/node/node.bzl

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -279,7 +279,15 @@ fi
279279
fail("""nodejs_binary/nodejs_test only support chdir inside the current package
280280
but %s is not a subfolder of %s""" % (ctx.attr.chdir, ctx.label.package))
281281
chdir_script = ctx.actions.declare_file(_join(relative_dir, "__chdir.js__"))
282-
ctx.actions.write(chdir_script, "process.chdir(__dirname)")
282+
ctx.actions.write(chdir_script, """
283+
/* This script is preloaded with --require, meaning it will run for the main node process
284+
as well as each worker thread that gets spawned. Calling process.chdir() in a worker
285+
is an error in node, so ensure it's only called once for the main process.
286+
*/
287+
if (process.cwd() !== __dirname) {
288+
process.chdir(__dirname);
289+
}
290+
""")
283291
runfiles.append(chdir_script)
284292

285293
# this join is effectively a $(rootdir) expansion

internal/node/test/chdir/BUILD.bazel

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,3 +52,10 @@ nodejs_test(
5252
data = ["build/app.js"],
5353
entry_point = "test.js",
5454
)
55+
56+
nodejs_test(
57+
name = "test_multithread",
58+
chdir = package_name(),
59+
data = ["worker.js"],
60+
entry_point = "multithread.js",
61+
)
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
const { Worker } = require("worker_threads")
2+
3+
function runWorker(message) {
4+
return new Promise((resolve, reject) => {
5+
const worker = new Worker("./worker.js", {workerData: {message}});
6+
worker.on("message", resolve);
7+
worker.on("error", reject);
8+
worker.on("exit", code => {
9+
if (0 !== code) {
10+
reject(new Error(`Worker exited with code ${code}`));
11+
}
12+
});
13+
})
14+
}
15+
16+
(async () => {
17+
await runWorker("foobar");
18+
})();

internal/node/test/chdir/worker.js

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
const {parentPort, workerData} = require("worker_threads");
2+
3+
console.log(workerData.message);
4+
parentPort.postMessage(true);

0 commit comments

Comments
 (0)