It is executed once for master and once for the fork, which is why it is executed twice.
If you only want it to execute once you could do it like this:
var cluster = require('cluster');
if (cluster.isMaster) {
var shared = require('./shared');
cluster.fork();
} else {
process.exit(0);
}
You can also add the cluster.isMaster
check within the shared
file.
Additions regarding your edit
The easiest way to handle logging of your workers is to let the master process handle it. I usually do it by sending messages from the worker to the master, like this:
const cluster = require('cluster');
if (cluster.isMaster) {
const worker = cluster.fork();
const pid = worker.process.pid;
worker.on('message', function(msg) {
switch (msg.type) {
case 'uncaughtException':
// Handle uncaught exception from worker
// Perhaps fork it again?
break;
case 'console':
// Handle console logging from worker
// Add winston code here
break;
}
});
} else {
process.on("uncaughtException", function (err) {
process.send({ type: "uncaughtException", data: { message: err.message, stack: err.stack } });
process.exit(1);
});
// Override console
console.log = function () {
process.send({ type: "console", method: "log", data: [].slice.call(arguments, 0) });
};
console.error = function () {
process.send({ type: "console", method: "error", data: [].slice.call(arguments, 0) });
};
console.info = function () {
process.send({ type: "console", method: "info", data: [].slice.call(arguments, 0) });
};
console.warn = function () {
process.send({ type: "console", method: "warn", data: [].slice.call(arguments, 0) });
};
console.debug = function () {
process.send({ type: "console", method: "debug", data: [].slice.call(arguments, 0) });
};
}