Although this code is not terribly long we can see that it is doing multiple jobs. It's doing http work and file work.
const server = http.createServer((req, res) => {
	fs.readFile(path, (err, contents) => {
		res.write(contents);
		res.end();
	});
});
	
server.listen(port);
  • In project dir
  • Create file "file-server-tool.js"
  • Copy provided code into file and save

Keywords:

//file-server-tool.js

const fs = require('fs');

class FileServerTool {

	static serveTo(path, response) {
		//Read file and serve to response object
		fs.readFile(path, (err, contents) => {
			if (err) throw err;
			response.write(contents);
			response.end();
		});
	}

}

//--------------------------------
exports.FileServerTool = FileServerTool;
  • In project dir
  • Create a new file "serve-file-2.js"
  • Copy provided code into file and save.

We now only have two lines of code.

Keywords:

//serve-file-2.js

const
	http = require('http'),
	httpStatusCodes = require('http-status-codes'),
	{FileServerTool} = require('./file-server-tool.js'),
	path = 'views/hello.html',
	htmlType = {'Content-Type': 'text/html'},
	port = 3000;

const callbackFct = (req, res) => {
	res.writeHead(httpStatusCodes.OK, htmlType);
	FileServerTool.serveTo(path, res);
}

const webServer = http.createServer(callbackFct);
webServer.listen(port);
As always, we test it out.

First start the server.
>node serve-file-2
Again, open the browser.


http://localhost:3000/

A Warm Hello to You


References




Navigation