Skip to main content


Showing posts from December, 2013

A Very Simple Network Connection with Node

Let’s say we want a very simple NodeJS server that listens on a specified port and writes the data it receives from TCP connections to a file. How easy can we code this up? Turns out this is fairly simple with NodeJS.
Require the necessary modules and instantiate a server. varserver=require('net').createServer();varfs=require('fs');server.listen(14300,serverReady);Start listening on a port, call function ‘serverReady’ when the server’s bound and ready to start receiving incoming connections. functionserverReady(){server.on('connection',handleConnection);}Assign an event handler on the server to call ‘handleConnection’ whenever a client connects to the bound server. The handler will receive the socket object for an argument. functionhandleConnection(socket){socket.setEncoding('utf8');socket.on('data',writeData);}When we get a connection, set the socket to utf8 encoding so that we simply receive strings for data rather than Buffer objects. When dat…