Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.


  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL
Help

Chapter 2. Serving Simple Content > Writing a Response Manually

2.1. Writing a Response Manually

The first thing we’ll do in any web application we write in Node is to require a module allowing us to actually serve a website. Most common server tasks are part of the http or https modules. At minimum, any web application will need to import one of these (or another module which has one or the other as a dependency) using the require function. Node’s built-in dependency management is similar to CommonJS, and require masks the complexity of searching for the desired module and avoiding redundancy.

var http = require("http");

Once the http module is available, we can create a server and ask it to begin listening for requests. The createServer() function has only one parameter: the callback that will execute whenever a request is received. The listen() function that starts the server can take several arguments, but for a simple server we just need to provide the port and, optionally, the host IP:


  

You are currently reading a PREVIEW of this book.

                                                                                        

Get instant access to over
$1 million worth of books and videos.

  

Start a Free Trial