-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
49 lines (44 loc) · 1.49 KB
/
server.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
41
42
43
44
45
46
47
48
49
//This code was written by Dr. Phillips and slightly adapted by Dallin Drollinger
'use strict';
let http = require('http');
let path = require('path');
let fs = require('fs');
let mimeTypes = {
'.js' : 'text/javascript',
'.map' : 'text/javascript',
'.html' : 'text/html',
'.css' : 'text/css',
'.png' : 'image/png',
'.jpg' : 'image/jpeg',
'.mp3' : 'audio/mpeg3',
'.wav' : 'audio/wav',
'.ttf' : 'font/ttf',
'.ico' : 'image/x-icon'
};
const port = 3000;
function handleRequest(request, response) {
console.log('request : ', request.url);
let lookup = (request.url === '/') ? '/index.html' : decodeURI(request.url);
let file = lookup.substring(1, lookup.length);
fs.access(file, fs.constants.R_OK, function(err) {
if (!err) {
fs.readFile(file, function(error, data) {
if (error) {
response.writeHead(500);
response.end('Server Error!');
} else {
let headers = {'Content-type': mimeTypes[path.extname(lookup)]};
response.writeHead(200, headers);
response.end(data);
}
});
} else {
console.log(`${lookup} doesn't exist`);
response.writeHead(404);
response.end();
}
});
}
http.createServer(handleRequest).listen(port, function() {
console.log(`Server is listening on port ${port}`);
});