NodeJS [SOLVED]: On cluster messages trigger class function

NodeJS [SOLVED]: On cluster messages trigger class function

Home Forums Scripting NodeJS Tutorials NodeJS [SOLVED]: On cluster messages trigger class function

Viewing 2 posts - 1 through 2 (of 2 total)
  • Author
    Posts
  • #245839

    Cloudy Point
    Keymaster

    QuestionQuestion

    im experimenting currently with cluster and worker (child_process).
    im trying to bind my class to “process.on” function, but it isnt working…

    var coresCount = require('os').cpus().length;
    var exec = require('child_process').exec;
    var cluster = require('cluster');
    class Listen extends Command {
    
        async trigger (args, options) {
            if (cluster.isMaster) {
                for (var i = 0; i < coresCount; i++) {
                    cluster.fork();
                }
            } else {
                process.on('message', function(msg) {
                    this._test()
                }).bind(this);
            }
        }
    
        _test() {
            console.log('test')
        }
    }
    
    module.exports = Listen
    

    Error Message:

    TypeError: this._test is not a function
    

    could anybody give me a little hint, or what would be the best practice to work with the messages?

    Thanks Advance

    #245840

    Cloudy Point
    Keymaster

    Accepted AnswerAnswer

    You’re calling bind on the result of process.on. You should be calling bind on your event handler callback. Change it to this:

    process.on('message', function(msg) {
        this._test()
    }.bind(this));
    

    Or:

    process.on('message', msg => {
        this._test()
    });
    

    Source: https://stackoverflow.com/questions/48011684/on-cluster-messages-trigger-class-function
    Author: SimpleJ
    Creative Commons License
    This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

Viewing 2 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic.