Skip to content

the child process created by child_process.fork can't receive message correctly when using ES module #39140

Description

@xiefenga
  • Version: v16.4.0、v14.17.1
  • Platform: Windows 10 x64
  • Subsystem: child_process

What steps will reproduce the bug?

when using ES module and child_process to fork child process, even 'spawn' event has happend,child process failed receive message from parent process.

Complete Testcase

package.json:

{
  "type": "module"
}

master.js

import { join } from 'path'
import { fork } from 'child_process'
import { fileURLToPath } from 'url'

const __dirname = join(
  fileURLToPath(import.meta.url),
  '../'
)

const worker = fork(
  join(__dirname, './worker.js')
);

worker.on('spawn', () => {
  console.log('start success');
  worker.send('hello', () => console.log('send success'));
});

worker.js

console.log('child process has started, processID:', process.pid);

process.on('message', (msg) => {
  console.log('child process get msg:', msg);
});

console ouput:

start success
send success
child process has started, processID: 6224

if i delay 1s send message to child process, it works:

worker.on('spawn', () => {
  console.log('start success');
  setTimeout(() => {
    worker.send('hello', () => console.log('send success'));
  }, 1000);
});

console output:

start success
child process has started, processID: 18156
send success
child process get msg: hello

What is the expected behavior?

the expected behavior just like this:

start success
send success
child process has started, processID: 16428
child process get msg: hello

when i rename worker.js to worker.cjs, got expected result.

Possible cause

I suspect this may have something to do with ESM asynchronous execution.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    child_processIssues and PRs related to the child_process subsystem.

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions