From 66f4586dd031435984ed77837512531dfc4fe893 Mon Sep 17 00:00:00 2001 From: Ben Noordhuis Date: Mon, 22 Feb 2016 12:30:33 +0100 Subject: [PATCH] cluster: emit worker as first 'message' event arg It's documented as such but didn't actually behave that way. Bug introduced in commit 66fc8ca ("cluster: emit 'message' event on cluster master"), which is the commit that introduced the event. Fixes: https://github.com/nodejs/node/issues/5126 PR-URL: https://github.com/nodejs/node/pull/5361 Reviewed-By: Ali Ijaz Sheikh Reviewed-By: Colin Ihrig Reviewed-By: Sakthipriyan Vairamani --- doc/api/cluster.markdown | 18 ++++++++++++++++++ lib/cluster.js | 6 +++--- test/parallel/test-cluster-message.js | 3 ++- 3 files changed, 23 insertions(+), 4 deletions(-) diff --git a/doc/api/cluster.markdown b/doc/api/cluster.markdown index 215e48b12a4286..a8ccd68f357e0e 100644 --- a/doc/api/cluster.markdown +++ b/doc/api/cluster.markdown @@ -487,11 +487,29 @@ The `addressType` is one of: * `worker` {cluster.Worker} * `message` {Object} +* `handle` {undefined|Object} Emitted when any worker receives a message. See [child_process event: 'message'][]. +Before Node.js v6.0, this event emitted only the message and the handle, +but not the worker object, contrary to what the documentation stated. + +If you need to support older versions and don't need the worker object, +you can work around the discrepancy by checking the number of arguments: + +```js +cluster.on('message', function(worker, message, handle) { + if (arguments.length === 2) { + handle = message; + message = worker; + worker = undefined; + } + // ... +}); +``` + ## Event: 'online' * `worker` {cluster.Worker} diff --git a/lib/cluster.js b/lib/cluster.js index 4f7ca58170468f..69698ddeb8129f 100644 --- a/lib/cluster.js +++ b/lib/cluster.js @@ -341,9 +341,9 @@ function masterInit() { process: workerProcess }); - worker.on('message', (message, handle) => - cluster.emit('message', message, handle) - ); + worker.on('message', function(message, handle) { + cluster.emit('message', this, message, handle); + }); worker.process.once('exit', function(exitCode, signalCode) { /* diff --git a/test/parallel/test-cluster-message.js b/test/parallel/test-cluster-message.js index 427c3058903d5d..7b074b9034404c 100644 --- a/test/parallel/test-cluster-message.js +++ b/test/parallel/test-cluster-message.js @@ -84,7 +84,8 @@ else if (cluster.isMaster) { worker.on('message', function(message) { check('master', message === 'message from worker'); }); - cluster.on('message', function(message) { + cluster.on('message', function(worker_, message) { + assert.strictEqual(worker_, worker); check('global', message === 'message from worker'); });