the code running with tsx works differently than with node
jack-theripper opened this issue · 2 comments
jack-theripper commented
Acknowledgements
- I read the documentation and searched existing issues to avoid duplicates
- I understand this is a bug tracker and anything other than a proven bug will be closed
- I understand this is a free project and relies on community contributions
- I read and understood the Contribution guide
Minimal reproduction URL
https://stackblitz.com/edit/node-wksbsy?file=index.ts
Problem & expected behavior (under 200 words)
Example: index.ts
import cluster from "node:cluster";
console.log(new Date);
if (cluster.isPrimary) {
const worker = cluster.fork();
worker.send('ok');
} else {
console.log('fork');
process.on('message', (message) => { // <----- it is not called when the tsx
console.log('fork', message, new Date())
})
}
tsx index.ts
Output:
2024-09-06T12:35:48.631Z
2024-09-06T12:35:49.569Z
fork
Now use tsc and run node:
tsc index.ts
node index.js
Output:
2024-09-06T12:38:15.278Z
2024-09-06T12:38:15.344Z
fork
fork ok 2024-09-06T12:38:15.356Z <--- this
❓
Why does this example work differently? Is it correct with node and incorrect with tsx ?
Bugs are expected to be fixed by those affected by it
- I'm interested in working on this issue
Compensating engineering work will speed up resolution and support the project
- I'm willing to offer $10 for financial support
uinz commented
It seems to be related to the module type, but generally don't rely too much on this timing.
If you keep sending messages in the main thread, the fork process can receive the messages.
// main.mjs
import cluster from "node:cluster";
console.log(new Date());
if (cluster.isPrimary) {
const worker = cluster.fork();
worker.send("ok");
} else {
console.log("fork");
process.on("message", (message) => {
console.log("fork", message, new Date());
});
}
// main.cjs
const cluster = require("node:cluster");
console.log(new Date());
if (cluster.isPrimary) {
const worker = cluster.fork();
worker.send("ok");
} else {
console.log("fork");
process.on("message", (message) => {
console.log("fork", message, new Date());
});
}
privatenumber commented
Going to keep this open as it's still a bug in Module mode