This repository has been archived by the owner on Aug 24, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
61 lines (54 loc) · 1.48 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
50
51
52
53
54
55
56
57
58
59
60
61
/**
* server.js
* Entry file for express server
*/
// Node Modules
import {config} from 'dotenv';
config();
import {exists, readFile, statSync} from 'fs';
import {createServer} from 'http';
import path from 'path';
import url from 'url';
// Constant
const PORT = process.env.PORT || 3000; // Defaults to port 3000 if env unset
createServer((request, response) => {
const parsedURL = url.parse(request.url);
let pathname = `.${parsedURL.pathname}`;
const ext = path.parse(pathname).ext || '.html';
const map = {
'.ico': 'image/x-icon',
'.html': 'text/html',
'.js': 'text/javascript',
'.json': 'application/json',
'.css': 'text/css',
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.wav': 'audio/wav',
'.mp3': 'audio/mpeg',
'.svg': 'image/svg+xml',
'.pdf': 'application/pdf',
'.doc': 'application/msword',
};
exists(pathname, (exist) => {
if (!exist) {
response.statusCode = 404;
response.end(`File ${pathname} not found`);
return;
}
if (statSync(pathname).isDirectory()) {
pathname += 'public/index' + ext;
}
readFile(pathname, (err, data) => {
if (err) {
response.statusCode = 500;
response.end(`Error retrieving file: ${err}.`);
} else {
response.setHeader('Content-type', map[ext] || 'text/plain');
response.end(data);
}
});
});
}).listen(PORT, () => {
// eslint-disable-next-line no-console
console.log(`Running server on port: ${PORT}`);
});