Training Guide: Programming in HTML5 with JavaScript and CSS3 Ebook

(Nora) #1

Lesson 1: Getting started with Node.js CHAPTER 8 343


When the createServer function is executed, a server object is returned. The server object
calls the listen function, in which port 8080 is specified as the port to listen on, and the IP
address is set to localhost, which is 127.0.0.1. As long as you have an operating network
adapter installed on your computer, this web server should start listening for incoming web
requests.
The last statement uses the console object to write a message to the screen to let you
know that the server is waiting for requests.
After you save this file, run the following from the command prompt to start running your
web server.
Node HelloWorld.js

Leave the command prompt open and open the browser. Navigate to the following URL.
http://localhost:8080/

When the request is received, a response is sent, and a message is logged to the console
window, as shown in Figure 8-1.

FIGURE 8-1 he running HelloWorld website responding with a messageT

Congratulations! You have installed Node.js and written your first Node.js website. To stop
running, you don’t need to close the command prompt window; you can just press Ctrl+C to
cancel.
Of course, the next thing you want to do is process the request data to produce a response
based on the request. For that, you can require the url module, which provides help for pars-
ing the QueryString. The url object has a parse method that accepts the actual URL, and the
second parameter is a flag by which passing a value of true parses the QueryString. The fol-
lowing code reads the name from the QueryString and creates a personalized response.
Free download pdf