在集群消息上触发 class 函数

On cluster messages trigger class function

我目前正在试验集群和工作程序 (child_process)。 我正在尝试将我的 class 绑定到 "process.on" 函数,但它不起作用...

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

错误信息:

TypeError: this._test is not a function

谁能给我一点提示,或者处理消息的最佳做法是什么?

提前致谢

您正在根据 process.on 的结果调用 bind。您应该在事件处理程序回调中调用 bind。将其更改为:

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

或者:

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