node.js - 子进程向父进程发送消息

标签 node.js child-process

我需要知道如何从子进程与其父进程进行通信。 我已经尝试过:

在我的主应用程序中:

var spawn = require('child_process').spawn
var cp = spawn('path/to/my/process', params)
cp.on('ready', function(){
  console.log('process is ready')
})

在我的子进程应用程序中:

process.emit('ready')

console.log('process is read') 从未执行

最佳答案

使用process.send()方法从子级向父级发送消息。

// Parent process
const childProcess = require('child_process');
var process = childProcess.fork('child.js');

process.on('message', function (message) {
    console.log('Message from Child process : ' + message);
});

在 child 身上

// child.js 

process.send('HELLO from child') 

关于node.js - 子进程向父进程发送消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33334436/

相关文章:

angularjs - 部分用于应用程序

Angular 9 : Sending data to parent component after destroying child component

node.js - 使用 node.js 运行 c 程序并获取响应

javascript - child_process.execFile 不适用于 phantomjs 和 highcharts-convert.js

javascript - 如何使用 ajax.get 调用从 node.js 服务器获取响应

javascript - Mongoose 子文档排序

node.js - 如何通过管道在 node.js 中运行?

javascript - 在 Node.js 上使用 SSH

node.js - 我如何将参数传递给 child_process.exec 回调

javascript - 如何使用流解析缓冲区中的行?