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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…