O'Reilly logo

Smashing Node.js: JavaScript Everywhere, 2nd Edition by Guillermo Rauch

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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/

index.html  images/

Under the images directory, you have four images:

$ ls website/images/

1.jpg  2.jpg  3.jpg  4.jpg

The 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):

<h1>My website</h1>

<img src=”/images/1.jpg”>

<img src=”/images/2.jpg”>

<img src=”/images/3.jpg”>

<img src=“/images/4.jpg“>

9781119963103-fg0801.eps

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

A simple website with HTTP

As usual, you start by requiring the http module for the server and the fs module for reading ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required