Skip to content

Using Multiple CPU Cores

tuxychandru edited this page Jun 3, 2011 · 2 revisions

Node.js being single threaded, cannot utilize mutliple CPU cores on a server. However, tools like Cluster allow you to easily start multiple node.js processes and load-balance between them to use all the cores available on your server. Cluster uses the OS to handle load-balancing and is good enough if you want to use multiple CPU cores without any special load-balancing needs.

Starting with version 0.3.3, Grasshopper allows you to setup all your routes without actually starting the HTTP server yourself. This allows you to use it with tools like cluster which expect an unbound http.Server instance.

Creating the Application

To create an app and start it with cluster, create a file named app.js with the below content.

var gh = require('grasshopper');

gh.get('/', function() {
    this.renderText('Hello world!');
});

module.exports = gh.serve();

Note that we do not specify a port to the serve() function. This keeps the http.Server instance created by grasshopper unbound to any port allowing it to be used with cluster.

Starting with Cluster

Install cluster using, npm install cluster. To start an instance of node on all cores available and handle requests on port 8080, create a file named server.js with the below content.

require('cluster')('./app').listen(8080);

Start the application using node server.js. For more details on configuring cluster, visit its home page.

Clone this wiki locally