rashadb rashadb - 1 month ago 19
Node.js Question

How do you deploy Throng or Cluster with Angular Fullstack?

The documentation looks super simple for implementing Throng to create additional webworkers with Heroku. Having said that, it has left me with a couple of questions:

1) Do I also need to install Cluster; from what I read Throng is an abstraction of Cluster but I don't see Cluster included in the download. Did I miss something or is Throng ready to go out of the box?

2) Where I do put these few lines of code? Angular Fullstack has a server directory and an app.js file within the server directory. This is my best bet but I could imagine that maybe it is better placed within the config directory or maybe even somewhere else.

3) In what order do I need to require Throng? I understand that if things are out of order that can mess things up. If app.js is the right place to put var throng = require('throng').

The following link is my reference with the directions on Throng:
https://github.com/goodeggs/heroku-web-cluster

I put the following code in my app.js file beneath 'start server':

var throng = require('throng');
var WORKERS = process.env.WEB_CONCURRENCY || 1;
var start = function(){
process.on('SIGTERM', function() {
console.log('Worker exiting');
process.exit();
});
}
throng(start, {
workers: 1,
lifetime: Infinity,
});


When I do this I receive a quickly repeating error in my terminal when it is deployed locally:

Error: bind EADDRINUSE
at exports._errnoException (util.js:746:11)
at cb (net.js:1178:33)
at rr (cluster.js:592:14)
at Worker.<anonymous> (cluster.js:563:9)
at process.<anonymous> (cluster.js:692:8)
at process.emit (events.js:129:20)
at handleMessage (child_process.js:324:10)
at Pipe.channel.onread (child_process.js:352:11)
Debugger listening on port 5889
events.js:85
throw er; // Unhandled 'error' event

^

Answer
var express = require('express');
var cluster = require('cluster'); //no need to download anything
var os = require('os'); //no need to download anything

if(cluster.isMaster) {
   var numWorkers = os.cpus().length;
   console.log('Master cluster setting up ' + numWorkers + ' workers...');

   for(var i = 0; i < numWorkers; i++) {
       cluster.fork();
   }

   cluster.on('online', function(worker) {
       console.log('Worker ' + worker.process.pid + ' is online');
   });

   cluster.on('exit', function(worker, code, signal) {
       console.log('Worker ' + worker.process.pid + ' died with code: ' + code + ', and signal: ' + signal);
       console.log('Starting a new worker');
       cluster.fork();
   });
} else {
   var app = require('express')();
   var server = require('http').createServer(app);
   require('./config/express')(app);
   require('./routes')(app);

   // Start server
   server.listen(config.port, config.ip, function () {
     console.log('Express server listening on %d, in %s mode', config.port, app.get('env'));
   });
}