Hello, World

To introduce you to the world of writing JavaScript outside the browser, you are going to start with a classic Hello, World program. Create a new file named index.js within your chattrbox folder and type the following, which we will explain after you have entered it:

var http = require('http');

var server = http.createServer(function (req, res) {
  console.log('Responding to a request.');
  res.end('<h1>Hello, World</h1>');
});
server.listen(3000);

On the first line, you used Node’s built-in require function to access the http module included with Node. This module provides a number of tools for working with HTTP requests and responses, such as the http.createServer function.

http.createServer takes in one argument, a function. This function is called for every HTTP request. You may recognize this as the callback pattern you used with browser events – except that in this case it is a server-side event (receiving an HTTP request) that triggers the callback.

In your callback, you log a message to the console and write some HTML text to the response. In Node, it is common to use req and res as the variable names for HTTP request and response objects.

Finally, you tell the server to listen on port 3000 using server.listen. This is commonly referred to as “binding to a port.”

Save your files. To see your Node server in action, run the command npm start. The terminal results are shown in Figure 15.6.

Figure 15.6  Running index.js via npm start

Running index.js via npm start

Next, open your browser to http://​localhost:3000. Your results will look like Figure 15.7. (Note that in some browsers other than Chrome, you may see your HTML as plain text. These browsers are expecting either a doctype or an extra piece of metadata in the response declaring that the response should be interpreted as HTML. You will address this as one of the challenges at the end of the chapter.)

Figure 15.7  Accessing your Node server in a browser

Accessing your Node server in a browser

Unlike when you ran Ottergram and CoffeeRun, there is no JavaScript to see in the browser. By the time you see this page, your JavaScript code has already done its work on the server.

Return to your terminal. You should see that console.log printed Responding to a request when the request was received (Figure 15.8).

Figure 15.8  console.log when request arrives

console.log when request arrives
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.75.217