Вот принцип работы любого вебсервера.
let http = require('http');
let fs = require('fs');
// access dirictory static files
let filesRoot = __dirname + '/access';
// allow rule for files
let fileRules = /(png|jpg|gif|html|js|css)$/i;
// allow file mime list
let fileTypes = {
png: 'image/png',
jpg: 'image/jpg',
gif: 'image/gif',
html: 'text/html',
css: 'text/css',
js: 'text/javascript'};
// server error handler
function sendError(req, res) {
// check method for response type
res.writeHead(404, {'Content-Type': 'text/plain'});
res.end('Bas request');
}
// server file send handler
function sendFile(req, res) {
let type = fileRules.exec(req.url);
type = type.toLocaleString();
// @todo check file or send error
res.writeHead(200, {'Content-Type': fileTypes[type]});
res.end(fs.readFileSync(filesRoot + req.url));
}
// server post logic handler
function sendPostData(req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('This is result post request');
}
// server get logic handler
function sendGetData(req, res) {
if (req.url == '/' || req.url == '/home') {
res.writeHead(200, {'Content-Type': fileTypes['html']});
res.end(fs.readFileSync(filesRoot + '/home.html'));
} else {
res.writeHead(404, {'Content-Type': fileTypes['html']});
res.end(fs.readFileSync(filesRoot + '/404.html'));
}
}
// server logic handler
function sendData(req, res) {
switch(req.method.toLocaleString()) {
case 'get': sendGetData(req, res); break;
case 'post': sendPostData(req, res); break;
default: sendError(req, res);
}
}
// server request handler
function onRequestEvent(req, res) {
if (fileRules.test(req.url))
sendFile(req, res);
else
sendData(req, res);
}
let server = http.createServer();
server.on('request', onRequestEvent)
server.listen(process.env.PORT || 8000)