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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access