Today I have released my first Node.js open source module on npm. It’s called json-socket.

It makes it easy to send JSON over TCP in Node.js using sockets.

Normally when you send data through sockets using Node’s net package, you need to worry about data chunking and multiple messages in one chunk. JsonSocket automatically takes care of all that for you.

JsonSocket works by decorating the built-in net.Socket class.

Here is a simple example where a client can connect to the server and send two numbers (a and b) that the server multiplies and sends back the result.

Server

var net = require('net'),
    JsonSocket = require('json-socket');

var port = 9838;
var server = net.createServer();
server.listen(port);
server.on('connection', function(socket) { //This is a standard net.Socket
    socket = new JsonSocket(socket); //Now we've decorated the net.Socket to be a JsonSocket
    socket.on('message', function(message) {
        var result = message.a + message.b;
        socket.sendEndMessage({result: result});
    });
});

Client

var net = require('net'),
    JsonSocket = require('json-socket');

var port = 9838; //The same port that the server is listening on
var host = '127.0.0.1';
var socket = new JsonSocket(new net.Socket()); //Decorate a standard net.Socket with JsonSocket
socket.connect(port, host);
socket.on('connect', function() { //Don't send until we're connected
    socket.sendMessage({a: 5, b: 7});
    socket.on('message', function(message) {
        console.log('The result is: '+message.result);
    });
});

Check out the readme on GitHub or install it directly using npm:

npm install json-socket

I’m going to use this module as a helper for another module that I have coming up. It’s a library that makes it easy to distribute workloads across multiple servers.

You’ll be able to write code like this:

var xxx = require('xxx'); //The new module

for (var someNumber = 1; someNumber < 100; someNumber++) {
    xxx.runFunction(performAdvancedCalculation, someNumber, function(err, result) {
        //result was calculated on another server than this one.
    });
}

function performAdvancedCalculation(someNumber, callback) {
    callback(null, somethingThatTakesUpAllCpuAndIsVeryIntensive(someNumber));
}

Which will run the function performAdvancedCalculation 100 times on different servers. All the other servers have to do is:

var xxx = require('xxx');
xxx.listen();

It’s a very handy functionality, and I use it with great success in one of my large scale Node.js projects.