342 CHAPTER 8 Websites and services
After this lesson, you will be able to:
■■Install Node.js.
■■Create a Node.js webpage.
Estimated lesson time: 20 minutes
Installing Node.js
To install Node.js on your computer, download the version for your machine from ht tp://
nodejs.org/download/ and run the installer. For typical Windows-based, 64-bit comput-
ers at the time of this writing, this is the node-v0.8.14-x64.msi file. The installation requires
accepting the licensing agreements. By default, the Node.js files install to the C:\Program
Files\nodejs\ folder. You’ll find the node.exe file in the installation folder, which is the primary
executable for Node.js. You will also find a folder for node modules; this folder contains npm,
the node package manager. You use npm to install modules in Node.js.
The Node.js installer adds the Node.js and npm folder locations to the path environment
setting so you can open the command prompt window easily and run the program.
Creating Hello World from Node.js
After the installation completes, you can create your first Node.js website by opening the
command prompt and using your favorite text editor. Create a file called HelloWorld.js con-
taining the following.
var http = require('http');
http.createServer(function (request, response) {
response.writeHead(200, {'Content-Type': 'text/plain'});
response.end('Hello World from Node.js!\n');
console.log('Handled request');
}).listen(8080, 'localhost');
console.log('Server running at http://localhost:8080/');
This is JavaScript! The first line of code states that the http module needs to be loaded. The
http module is a core built-in, low-level module that is highly optimized for performance.
The next line uses the http module to create a server object. The createServer func-
tion accepts a single parameter that is an anonymous function and has request object and
response object parameters. Inside the function, you include all the code to run your website
or, better yet, to make calls to other functions that handle your website. This example does
nothing with the request object, but it uses the response object to write an HTTP header in
which 200 means success, and the content type tells the browser that the content is plain text.
The next line ends the response with the Hello World message and, finally, a message is sent
to the console window, stating that a request was handled.