node.jsmultiprocessingnode-cluster

Is it possible to name events differently from "message" in the NodeJS cluster module?


I'm wondering (since there's no mention of this in the official documentation) if there's a way to emit events from the worker processes which have a different event name from the default, which is message, so that I can set up listeners in the master process something along the lines of:

worker.once('someOtherMsgName', fn)

This is so that I can avoid conditions in the actual callback function and only match the listeners to execute the callback for appropriate messages by their message name?


Solution

  • No

    "message" means - you have got new incoming message received by IPC (inter process communication). NodeJS has only one build-in way to send messages between process - process.send and child_process.send

    Yes

    Of course you can use third party modules (node-ipc for example) or make node to interpret message contents in any way you want:

    main.js

    const childProcess = require('child_process');
    const fork = childProcess.fork(__dirname + '/fork.js');
    const initIPC = require('./init-ipc');
    
    initIPC(process);
    fork.on('hello', event => {
      console.log(event.hello);
    });
    
    // Say hello to forked process
    fork.send({event: 'hello', hello: 'Hello from main process!'});
    

    fork.js

    const initIPC = require('./init-ipc');
    
    initIPC(process);
    process.on('hello', event => {
      console.log(event.hello);
    });
    
    // Say hello to main process
    process.send({event: 'hello', hello: 'Hello from forked process!'});
    

    init-ipc.js

    exports.initIPC = function (process) {
        process.on('message', message => {
            if (('event' in message) && typeof message.event === 'string') {
                process.emit(message.event, message);
            }
        });
    };