Serving Static Files

The most basic type of HTTP server is one that serves static files. To serve static files from Node.js, you need to first start the HTTP server and listen on a port. Then, in the request handler, you need to open the file locally, using the fs module, and then write the file contents to the response.

Listing 7.1 shows the basic implementation of a static file server. Notice that line 5 creates the server using createServer() and also defines the request event handler shown in lines 6–15. Also notice that the server is listening on port 8080 by calling listen() on the Server object.

Inside the request event handler on line 6, url.parse() method parses the URL so that you can use the pathname attribute when specifying the path for the file in line 7. The static file is opened and read using fs.readFile(), and in the readFile() callback, the contents of the file are written to the response object, using res.end(data), on line 14.

Listing 7.1 http_server_static.js: Implementing a basic static file webserver


01 var fs = require('fs'),
02 var http = require('http'),
03 var url = require('url'),
04 var ROOT_DIR = "html/";
05 http.createServer(function (req, res) {
06   var urlObj = url.parse(req.url, true, false);
07   fs.readFile(ROOT_DIR + urlObj.pathname, function (err,data) {
08     if (err) {
09       res.writeHead(404);
10       res.end(JSON.stringify(err));
11       return;
12     }
13     res.writeHead(200);
14     res.end(data);
15   });
16 }).listen(8080);


To test the code in Listing 7.1, you can use any web browser and hit the URL localhost:8080.

Listing 7.2 shows a basic implementation of an HTTP client that sends a GET request to the server to retrieve the file contents. Notice that the options for the request are set in lines 2–6, and then the client request is initiated in lines 16–18.

When the request completes, the callback function uses the on('data') handler to read the contents of the response from the server and then the on('end') handler to log the file contents to a file. Figure 7.2 shows the output of the HTTP client as well as the static file being accessed from a web browser.

Listing 7.2 http_client_static.js: A basic web client retrieving static files


01 var http = require('http'),
02 var options = {
03     hostname: 'localhost',
04     port: '8080',
05     path: '/hello.html'
06   };
07 function handleResponse(response) {
08   var serverData = '';
09   response.on('data', function (chunk) {
10     serverData += chunk;
11   });
12   response.on('end', function () {
13     console.log(serverData);
14   });
15 }
16 http.request(options, function(response){
17   handleResponse(response);
18 }).end();


Image

Figure 7.2 Implementing and accessing a basic static file webserver.

..................Content has been hidden....................

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