Quick Index
Example


Initialize the project in the normal way, and install "http-status-codes"
>npm init
>npm install http-status-codes
  • In a file browser
  • Create a project sub-directory "views"
  • In the sub-dir, create a new file "hello.html"
  • Copy the HTML shown into the file and save
<!DOCTYPE html>
<html>
	<body>
		<h1>A Warm Hello to You</h1>
	</body>
</html>
Type in the code shown.

Save the code as file "serve-file.js".

Complexity Note!
When possible, we write single-purpose code to simplify understanding and maintenance. Here we are doing multiple things (i.e., http and file work). We make a note (we'll revisit and simplify).
//serve-file.js

const
	http = require('http'),
	fs = require('fs'),
	httpStatusCodes = require('http-status-codes'),
	path = 'views/hello.html',
	port = 3000;

const server = http.createServer((req, res) => {
	res.writeHead(httpStatusCodes.OK, {'Content-Type': 'text/html'});
	fs.readFile(path, (err, contents) => {
		if (err) throw err;
		res.write(contents);
		res.end();
	});
});
	
server.listen(port);
Run in the normal way. This starts the web server, which is now waiting for requests.
>node serve-file
  • Open web browser
  • Enter server url as shown
  • Request is sent to server
  • Server responds with html content
  • Browser displays content


http://localhost:3000/

A Warm Hello to You


References




Navigation