express-cluster
Version:
Simple drop-in for express apps to spawn multiple processes
91 lines (77 loc) • 2.46 kB
text/coffeescript
cluster = require "cluster"
os = require "os"
master = (config) ->
count = parseInt(config.count or process.env.WORKER_COUNT)
workerCount = if count > 0 then count else os.cpus().length
respawn =
if typeof config.respawn is "undefined"
true
else
Boolean config.respawn
outputStream =
if config.outputStream and typeof config.outputStream.write is "function"
config.outputStream.write
else
console.log
workers = []
if config.verbose
outputStream "Master started on pid #{process.pid}, forking #{workerCount} processes"
for i in [0 ... workerCount]
worker = cluster.fork()
if typeof config.workerListener is "function"
worker.on "message", config.workerListener
workers.push worker
cluster.on "exit", (worker, code, signal) ->
if config.verbose
outputStream "#{worker.process.pid} died with #{signal or "exit code
if respawn then ", restarting" else ""
idx = workers.indexOf worker
if idx > -1
workers.splice idx, 1
if respawn
worker = cluster.fork()
if typeof config.workerListener is "function"
worker.on "message", config.workerListener
workers.push worker
process.on "SIGQUIT", ->
respawn = false
if config.verbose
outputStream "QUIT received, will exit once all workers have finished current requests"
for worker in workers
worker.send "quit"
worker = (fn, worker) ->
server = fn(worker)
if not server
return
if typeof server.on is "function"
server.on "close", ->
process.exit()
if typeof server.close is "function"
process.on "message", (msg) ->
if msg is "quit"
server.close()
module.exports = (arg0, arg1) ->
fn = ->
config = {}
if typeof arg0 is 'function'
fn = arg0
config = arg1 || config
else if typeof arg1 is 'function'
fn = arg1
config = arg0 || config
if cluster.isMaster
master config
else
worker fn, cluster.worker