Skip to content

Instantly share code, notes, and snippets.

@alandotcom
Created November 12, 2015 20:22
Show Gist options
  • Save alandotcom/821d0f2b6fdc77b6fbb4 to your computer and use it in GitHub Desktop.
Save alandotcom/821d0f2b6fdc77b6fbb4 to your computer and use it in GitHub Desktop.
Node IPC
var cluster = require('cluster');
var http = require('http');

if (cluster.isMaster) {
  var worker = cluster.fork();

  cluster.on('exit', function(worker, code, signal) {
    console.log('worker ' + worker.process.pid + ' died');
  });

  http.createServer(function(req, res) {
    var body = '';
    req.on('data', function(chunk) {
      body += chunk.toString();
    });
    req.on('end', function() {
      worker.send(JSON.parse(body));
      res.writeHead(200);
      res.end("sent\n");
    });
  }).listen(8000);
} else {
  process.on('message', function(msg) {
    console.log('WORKER: ', JSON.stringify(msg, null, 2));
  });
}
» curl -H "Content-Type: application/json" -X POST -d '{"foo":"bar"}' localhost:8000
sent

Meanwhile

WORKER:  {
  "foo": "bar"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment