Chapter 8: Connect
Node.js provides basic APIs for common network applications. So far, you have looked at the basic APIs for TCP servers and an API for HTTP that builds on top of it.
Most real-world applications, however, perform a series of common tasks that you probably don’t want to re-implement on top of primitive APIs over and over again.
Connect is a toolkit that sits on top of the HTTP server to provide a new way of organizing code that interfaces with request and responses, around units called middleware.
To illustrate the benefits of code reuse through middleware, assume this sample structure for a website:
$ ls website/
Under the images directory, you have four images:
$ ls website/images/
1.jpg 2.jpg 3.jpg 4.jpg
index.html simply displays the four images, and you want to access the website through
http://localhost as in other examples (see Figure 8-1):
Figure 8-1: A simple static website demonstrating Connect’s capabilities
To show the simplicity Connect offers for the world of HTTP applications, this chapter shows how to write this simple website with the native
http API and later with the
A simple website with HTTP
As usual, you start by requiring the
http module for the server and the
fs module for reading ...