Hello Web

Let us make a very simple web application that greets the user with a hello. Write the following code in a file, and name it helloweb.js:

var http = require("http");

http.createServer(function(request, response) {
  response.writeHead(200, {"Content-Type": "text/html"});
  response.write("<html>");
  response.write("<head><title>Node.js</title></head>");
  response.write("<body>Hello Web</body>");
  response.write("</html>");
  response.end();
}).listen(9999);

To run the previous piece of code, execute helloweb.js in Node.js:

node helloweb.js

And then open http://localhost:9999/ in your browser. You should see a page saying Hello Web. There is a lot going on here! So let us walk through the code and understand what is going on.

The very first line of code introduces us to one of the fundamental building blocks of Node.js, the module system. Node.js has a very simple module system built on CommonJS. Those familiar with frontend development using RequireJS with Asynchronous Module Definition (AMD) will immediately relate to this. All the functionality in Node.js is built as modules and you need to import it in your code using require. Node.js has several modules compiled in a binary form, called core modules, HTTP being one of them. We can also create and include our own custom or third-party modules using require. In case of file modules, there is one-to-one mapping between a file and a module; so we write every module in its own file. We will see more on writing our own modules later.

var http = require("http");

With this statement, Node.js will load the core HTTP module, and it will be available in a variable called http. The next task is to create a server using the HTTP module. This is done using the createServer method from the module. The createServer method accepts requestListener.

http.createServer([requestListener]);

The requestListener is a function that handles the incoming requests. In our case, this function is passed inline. Just like JavaScript in a browser, Node.js also runs a single process and a single thread. This is different from the traditional application servers, which create a new thread or process to handle new requests. So to scale and handle multiple requests, Node.js uses asynchronous event handling. So every request that comes in triggers an event, which is then handled by the event handler asynchronously. This is the mechanism of the event loop explained in earlier sections.

http.createServer(function(request, response) {
  response.writeHead(200, {"Content-Type": "text/html"});
  response.write("<html>");
  response.write("<head><title>Node.js JS</title></head>");
  response.write("<body>Hello Web</body>");
  response.write("</html>");
  response.end();
});

Tip

Downloading the example code

You can download the example code files for all Packt books you have purchased from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

The way createServer works is similar to any event handler in JavaScript. The event in this case is receiving a request to serve. As we can see, requestListener takes two arguments, request and response. The request object is an instance of http.ServerRequest, and will have all the information about the request, such as URL, method, headers, and data.

The response object is an instance of ServerResponse, which implements a WritableStream. It exposes various methods to write the response to the client; the ones we are most interested in, for now, are writeHead, write and end. Let us first see writeHead:

response.writeHead(statusCode, [reasonPhrase], [headers]);

Here, statusCode is the HTTP response code, reasonPhrase is the optional human-readable response phrase, and headers is the object that has the headers, which are to be sent in the response. This function should be called only once, before calling response.end. If we call response.write or response.end before this, the implicit/mutable headers will be calculated and the following function will be called automatically:

response.writeHead(200, {"Content-Type": "text/html"});

In this call, we are setting the status code to 200, that is, HTTP OK, and we are only setting the Content-Type header to text/html. The next method here is response.write, it's used to write the response content to the client. The call to this method is done as follows:

response.write(chunk, [encoding]);

In this call, chunk is the content to write and encoding is the content encoding to use. If the chunk is a string and the encoding is not specified, UTF-8 will be used by default.

response.write("<html>");
response.write("<head><title>Node.js JS</title></head>");
response.write("<body>Hello Web</body>");
response.write("</html>");

In the above code, the first time write is called, Node.js sends the response headers and the chunk of the body. But the write method can then be called multiple times. Node.js will assume that we are streaming data, and will keep sending the chunk whenever the calls are made. And the last call on the response is made to tell Node.js that we are done. This is just what response.end does.

response.end([data], [encoding]);

response.end signals to the server that all the response headers and body content have been sent and that the server should consider this message complete. We must call this method for every message.

response.end();

In our case, we call response.end without any of the optional arguments. If we do pass in the parameters, it is equivalent to calling response.write with the parameters, followed by response.end. I prefer keeping them separate, and hence, explicit.

Finally, we need to tell the HTTP server which port it should listen on. In this case, we tell it to listen on port 9999.

listen(9999);
..................Content has been hidden....................

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