Missing message when using child_process.send in CoffeeScript

I just started with coffeescript and I love it, but I ran into a frustrating problem. When I reproduce the basic version of sending and receiving messages between a process and a forked child process in javascript, I get the expected result. So far so good.

----------- 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'});

      

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

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

process.send({foo:'bar'});

      

-------------- output of node app2.js -----

child received  { hello: 'world' }
parent recieved  { foo: 'bar' }

      

However, when I reproduce the example in coffeescript, I only get the parent receiving the message from the child; the child does not appear to receive the message from the parent.

----------- 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'}

      

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

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

console.log "Child process running"

process.send {bar:'hello from the child process'}

      

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

Child process running
PARENT recieved { bar: 'hello from the child process' }

      

Looking at the compiled javascript I can see (as expected) that the result of the compilation of coffeescript is essentially the same as the JavaScript source code, just wrapped in a function with a call. The problem must be one of the areas, but I can't figure out how to resolve it. Surely it will be trivial for a guru and I am at the end of my attachment to him, so I thought I would ask if someone is kind to show me the way.

Dr. Darrin Reid.

+3


source to share


1 answer


Unfortunately, this is not as easy as a problem. The problem is with your fork command, which in the case of JS will start a new process node

, and in the case of CoffeeScript will start a new process coffee

.

I can't say for sure without a lot of time, but the problem is the difference in their startup / compilation times or something.



// 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

      

I think the simplest solution for you would be not to send any messages to the child until you have received the initial event 'ready'

from the child process. This way you can send the child.coffee

following initial message, which will tell the parent process that it is finally compiled and fully loaded.

+5


source







All Articles