Chapter 11. Node: JavaScript on the Server

The dividing line between “old” and “new” JavaScript occurred when Node.js (referred to primarily as just Node) was released to the world. Yes, the ability to dynamically modify page elements was an essential milestone, as was the emphasis on establishing a path forward to new versions of ECMAScript, but it was Node that really made us look at JavaScript in a whole new way. And it’s a way I like—I’m a big fan of Node and server-side JavaScript development.

Note

I won’t even attempt to cover all there is to know about Node on an introductory level in one chapter, so I’m focusing primarily on the interesting bits for the relative newbie. For more in-depth coverage, I’m going to toot my own horn and recommend my book, Learning Node (O’Reilly).

At a minimum, this chapter does expect that you have Node installed in whatever environment you wish, and are ready to jump into the solution examples.

Responding to a Simple Browser Request

Problem

You want to create a Node application that can respond to a very basic browser request.

Solution

Use the built-in Node HTTP server to respond to requests:

// load http module
var http = require('http');

// create http server
http.createServer(function (req, res) {

  // content header
  res.writeHead(200, {'content-type': 'text/plain'});

  // write message and signal communication is complete
  res.end("Hello, World!\n");
}).listen(8124);

console.log('Server running on 8124/');

Discussion

The simple text message web server response ...

Get JavaScript Cookbook, 2nd Edition 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.