在CoffeeScript中使用child_process.send时缺少消息

use*_*604 3 process node.js coffeescript

我刚刚开始使用coffeescript,我喜欢它,但我遇到了令人沮丧的问题.当我在javascript中重现进程和分叉子进程之间发送和接收消息的基本版本时,我得到了预期的结果.到目前为止,一切都很好.

----------- app2.js -----------------------------

var child = require('child_process');
var forked = child.fork("./child2.js");

forked.on('message', function (msg) {
    console.log("parent recieved ", msg);
});

forked.send({hello:'world'});
Run Code Online (Sandbox Code Playgroud)

---------- child2.js --------------------------------

process.on('message', function(m) {
    console.log("child received ", m);
});

process.send({foo:'bar'});
Run Code Online (Sandbox Code Playgroud)

--------------节点app2.js的输出-----

child received  { hello: 'world' }
parent recieved  { foo: 'bar' }
Run Code Online (Sandbox Code Playgroud)

然而,当我在coffeescript中重现这个例子时,我只让父母接收来自子进程的消息; 显然,子进程没有收到来自父进程的消息.

-----------app.coffee ----------------------------

cp = require('child_process')
n = cp.fork("./child.coffee")

n.on 'message', (m) =>
    console.log 'PARENT recieved', m

n.send {foo:'hello from the parent process'}
Run Code Online (Sandbox Code Playgroud)

---------- child.coffee ---------------------------

process.on 'message', (m) =>
    console.log 'CHILD received ', m

console.log "Child process running"

process.send {bar:'hello from the child process'}
Run Code Online (Sandbox Code Playgroud)

--------------------咖啡app.coffee的输出----

Child process running
PARENT recieved { bar: 'hello from the child process' }
Run Code Online (Sandbox Code Playgroud)

查看已编译的javascript,我看到(正如预期的那样)编译coffeescript的结果与原始的javascript代码基本相同,只是包含在一个调用此函数的函数中.问题必须是范围之一,但我看不出如何重新解决它.毫无疑问,对于大师而言,这将是微不足道的,而且我已经完成了它的束缚,所以我想我会问,以防万一有人给我指路.

Darryn Reid博士.

log*_*yth 5

不幸的是,这并不像范围问题那么简单.问题是你的fork命令,它在JS案例中将启动一个新node进程,而在CoffeeScript案例中将启动一个新coffee进程.

如果没有大量的时间狩猎,我不能肯定地说,但问题是他们的启动/编译时间或与此相关的事情有所不同.

// Changing this line
n.send {foo:'hello from the parent process'}

// to this works for me
setTimeout (-> n.send {foo:'hello from the parent process'}), 300
Run Code Online (Sandbox Code Playgroud)

我认为最简单的解决方案是'ready'在孩子进程中收到一些初始事件之前,不要向孩子发送任何消息.因此,您可以child.coffee发送一些初始消息,告知父进程它最终已完全编译和加载.