Chapter 2. Serving Simple Content

Because serving content is a web server’s reason for being, there are thousands of Node modules available to automate the various ways of doing so, or to wrap that entire set of functions up in a robust framework. Working with what Node includes natively, however, provides a beneficial illustration of how it works as a web server, and creating simple applications with its out-of-the-box utilities is fairly trivial.

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:

var http = require("http"); http.createServer(function(req, res) { var html = "<!doctype html>" + "<html><head><title>Hello ...

Get Node for Front-End Developers now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.