- Implement rudimentary static web server
- Use the fs (file system) module which will serve some HTML file like Apache or Nginx web server
- Create index.html that will be served by the Node server
Every web page on the Internet is served by some HTTP web server. For this simple reasons, building web servers is an important skill to have. Single-page applications and static web pages (static files) which don't require server-side logic, can be served by static HTTP web servers like Apache, or Nginx.
In this lab, you'll build a static file server to serve static files over the HTTP protocol.
- Create file
server.js
- Implement an HTTP server with
http
- Read
request.url
to get the file name. - Boot the server with the value from a command-line argument or if not set value 3000.
- Read the file and serve it to the client. Handle the errors accordingly when reading files (404 Not Found).
- Server must send back 200 on success (along with the file content) and 404 when file not found along with
404 Not Found\n
body. - Run tests with
npm install && npm test
, or justnpm test
.
Here are some hints:
- To read
request.url
to get the file name, usepath.join()
. - To boot the server with the value from command-line argument or if not set value 3000, use
port = process.argv[2] || 3000
. - To read the file and serve it to the client, use
binary
mode as infs.readFile(filename, 'binary', function(error, file) {...}
You can score bonus points for playing with the your code using debugger. There are multiple way to do so. You can use next (n
) or step (s
), but in most cases you would have to look at many statements if you want to get to the callback (i.e., request handler). The easiest way to do it, is to put a debugger
statement in the callback, start the server in debug mode and submit a request with CURL or browser.
To put a debugger
statement, simply type debugger
in the server.js
file and save it. To start the server in debug mode, use node debug server
, then press c
for continue (n
is better, because you can move to the next statement). The server will listen for incoming requests. Now, submit your request with CURL, Postman or just by going to the browser. This will stop the debugger at your breakpoint. You can use repl
or any other commands now. Enjoy the show!