Let’s Build Twitter
The previous example shows how easy it is to write something extremely
real-time with Node, but often you just want to write a web application.
Let’s try to create something similar to Twitter with Node so we can see
what it’s like to make a web application. The first thing we should do is
install the Express module (Example 2-13). This web
framework for Node makes it much easier to create web applications by
adding support for common tasks, such as MVC, to the existing http
server.
Example 2-13. Installing the Express module
Enki:~ $ npm install express
express@2.3.12 ./node_modules/express
├── mime@1.2.2
├── connect@1.5.1
└── qs@0.1.0
Enki:~ $Installing Express is easy using the Node Package Manager
(npm). Once we have the framework installed, we can make a
basic web application (Example 2-14). This
looks a lot like the application we built in Chapter 1.
Example 2-14. A basic web server with Express
var express = require('express')
var app = express.createServer()
app.get('/', function(req, res) {
res.send('Welcome to Node Twitter')
})
app.listen(8000)This code looks pretty similar to the basic web server code from
Chapter 1. Instead of including the http module, however, we include express. Express is actually getting http behind the scenes, but we don’t have to get
that ourselves, because Node will automatically resolve the dependencies.
Like with http and net, we call createServer() to make a server and call ...