Chapter 2. Doing Interesting Things
The programming trends of the last few years have made it progressively easier to write more complex applications with ease. It’s important that we don’t lose that, but Node is specifically focused on solving the problem of building network applications—that is, applications that do a lot of input/output (I/O). Let’s build a few I/O-type apps and see how easy it is to do this with Node in a way that really scales.
Building a Chat Server
In a world that’s increasingly real-time, what is more real-time than chat? So where should we begin? Let’s start with a TCP-based chat server we can connect to with Telnet. Not only is it a simple place to start, but it’s also something we can write 100% in Node.
The first thing we need to do is include the TCP libraries from Node and create a new TCP server (see Example 2-1).
Example 2-1. Creating a new TCP server
var net = require('net')
var chatServer = net.createServer()
chatServer.on('connection', function(client) {
client.write('Hi!\n');
client.write('Bye!\n');
client.end()
})
chatServer.listen(9000)First, we include the net module.
This contains all the TCP stuff for Node. From that, we can
create a TCP server by calling the net.createServer() method. Now that we have a server, we want it to do stuff.
So we add an event listener by using the on() method. Whenever the connection event happens, the event listener will call the function we gave
it. A connection event happens when a new client connects to the server. ...