-
Notifications
You must be signed in to change notification settings - Fork 0
/
server-2.js
40 lines (37 loc) · 1.36 KB
/
server-2.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
var http = require('http');
var fs = require('fs');
var path = require('path');
var hostname = 'localhost';
var port = 3000;
var server = http.createServer(function(req, res){
console.log('Request for ' + req.url + ' by method ' + req.method);
if (req.method == 'GET') {
var fileUrl;
if (req.url == '/') fileUrl = '/index.html';
else fileUrl = req.url;
var filePath = path.resolve('./public'+fileUrl);
var fileExt = path.extname(filePath);
if (fileExt == '.html') {
fs.exists(filePath, function(exists) {
if (!exists) {
res.writeHead(404, { 'Content-Type': 'text/html' });
res.end('<html><body><h1>Error 404: ' + fileUrl + ' not found</h1></body></html>');
return;
}
res.writeHead(200, { 'Content-Type': 'text/html' });
fs.createReadStream(filePath).pipe(res);
});
}
else {
res.writeHead(404, { 'Content-Type': 'text/html' });
res.end('<html><body><h1>Error 404: ' + fileUrl + ' not a HTML file</h1></body></html>');
}
}
else {
res.writeHead(404, { 'Content-Type': 'text/html' });
res.end('<html><body><h1>Error 404: ' + req.method + ' not supported</h1></body></html>');
}
});
server.listen(port, hostname, function(){
console.log('Server running at http://'+hostname+':'+port+'/');
});