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 ...
Get Node.js, MongoDB, and AngularJS Web Development now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.