Skip to Content
Node: Up and Running
book

Node: Up and Running

by Tom Hughes-Croucher, Mike Wilson
April 2012
Intermediate to advanced
204 pages
5h 42m
English
O'Reilly Media, Inc.
Content preview from Node: Up and Running

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. ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Node.js in Practice

Node.js in Practice

Marc Harter, Alex Young
Building APIs with Node.js

Building APIs with Node.js

Caio Ribeiro Pereira

Publisher Resources

ISBN: 9781449332235Supplemental ContentErrata