diff --git a/src/node.js b/src/node.js index 63465290a0c351..1339fb33311567 100644 --- a/src/node.js +++ b/src/node.js @@ -71,6 +71,17 @@ } else { // There is user code to be run + // If this is a worker in cluster mode, start up the communication + // channel. This needs to be done before any user code gets executed + // (including preload modules). + if (process.argv[1] && process.env.NODE_UNIQUE_ID) { + var cluster = NativeModule.require('cluster'); + cluster._setupWorker(); + + // Make sure it's not accidentally inherited by child processes. + delete process.env.NODE_UNIQUE_ID; + } + // Load any preload modules if (process._preload_modules) { var Module = NativeModule.require('module'); @@ -87,16 +98,6 @@ var path = NativeModule.require('path'); process.argv[1] = path.resolve(process.argv[1]); - // If this is a worker in cluster mode, start up the communication - // channel. - if (process.env.NODE_UNIQUE_ID) { - var cluster = NativeModule.require('cluster'); - cluster._setupWorker(); - - // Make sure it's not accidentally inherited by child processes. - delete process.env.NODE_UNIQUE_ID; - } - var Module = NativeModule.require('module'); if (global.v8debug && diff --git a/test/fixtures/cluster-preload-test.js b/test/fixtures/cluster-preload-test.js new file mode 100644 index 00000000000000..43d3887b0daf01 --- /dev/null +++ b/test/fixtures/cluster-preload-test.js @@ -0,0 +1,7 @@ +var cluster = require('cluster'); +if (cluster.isMaster) { + cluster.fork(); // one child + cluster.on('exit', function(worker, code, signal) { + console.log('worker terminated with code ' + code); + }); +} diff --git a/test/fixtures/cluster-preload.js b/test/fixtures/cluster-preload.js new file mode 100644 index 00000000000000..651fc480e8b84a --- /dev/null +++ b/test/fixtures/cluster-preload.js @@ -0,0 +1,3 @@ +var cluster = require('cluster'); +cluster.isMaster || process.exit(42 + cluster.worker.id); // +42 to distinguish +// from exit(1) for other random reasons diff --git a/test/parallel/test-preload.js b/test/parallel/test-preload.js index aef778b5873073..643edfb1d970cc 100644 --- a/test/parallel/test-preload.js +++ b/test/parallel/test-preload.js @@ -72,3 +72,11 @@ child_process.exec(nodeBinary + ' ' if (err) throw err; assert.equal(stdout, 'A\nB\nhello\n'); }); + +child_process.exec(nodeBinary + ' ' + + '--require ' + fixture('cluster-preload.js') + ' ' + + fixture('cluster-preload-test.js'), + function(err, stdout, stderr) { + if (err) throw err; + assert.ok(/worker terminated with code 43/.test(stdout)); + });