Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
165 views
in Technique[技术] by (71.8m points)

javascript - NodeJS Process.on Bidirectional Communication

I am having a simple NodeJS application, where there are a parent process and child process.

Both are communicating with each other. Below is the code.

parent.js

import { createRequire } from 'module';
const require = createRequire(import.meta.url);

const { fork } = require('child_process');
const forked = fork('./child.js');


forked.on('message', (msg) => {
  console.log('Message from child', msg);
});

forked.send({ hello: 'world' });

child.js

process.on('message', (msg) => {
  console.log('Message from parent: ', msg);
});


let counter = 0;

setInterval(() => {
  process.send({ counter: counter++ });
}, 1000);

Expected Output

  Message from parent: {hello: "world"}
  Message from child { counter: 0 }
  Message from child { counter: 1 }
  Message from child { counter: 2 }
  Message from child { counter: 3 }
  Message from child { counter: 4 }
    ......and so on

But I am not getting Message from parent: {hello : "world"}

I am getting this as

Output

  Message from child { counter: 0 }
  Message from child { counter: 1 }
  Message from child { counter: 2 }
  Message from child { counter: 3 }
  Message from child { counter: 4 }
    ......and so on

Environment

  • OS: Ubuntu 20.04.1 LTS
  • NodeJS: 14.6.0

package.json

{
  "name": "simple-app",
  "version": "0.1.0",
  "type": "module",
  "private": true,
  "dependencies": {
    "axios": "^0.21.1",
    "bcryptjs": "latest",
    "body-parser": "latest"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject",
    "api": "nodemon ./server/server.js",
    "dev": "concurrently "react-scripts start" "nodemon server/server.js""
  },
  "devDependencies": {
    "concurrently": "latest",
    "nodemon": "latest"
  }
}

So what I am doing wrong?

question from:https://stackoverflow.com/questions/65661828/nodejs-process-on-bidirectional-communication

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Actually, due to the asynchronous, nature of the ES module loading, there is a race condition in my script.

Since I am using

"type": "module"

In my package.json and my project is huge, I can't change ES module loading.

So you overcome the race condition I have to delay a little sending message to the child process.

Thus,

   setTimeout(() = >{
        forked.send({ hello: 'world' });
    , 100};

avoids race condition.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...