-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathserver.js
More file actions
56 lines (47 loc) · 1.66 KB
/
Copy pathserver.js
File metadata and controls
56 lines (47 loc) · 1.66 KB
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
const http = require("http");
const url = require("url");
const path = require("path");
const fs = require("fs");
const port = process.argv[2] || 3000;
const contentTypes = {
'.html': "text/html",
'.css': "text/css",
'.js': "text/javascript"
};
http.createServer((req, res) => {
let uri = url.parse(req.url).pathname;
if (uri.indexOf('/api/getall') > -1 ) {
// simulate database delay
setTimeout(() => {
res.writeHead(200, {"Content-Type": "application/json"});
res.write(JSON.stringify({id: 10}));
res.end();
}, 1000);
}
else {
let filename = path.join(process.cwd(), uri);
fs.exists(filename, exists => {
if(!exists) {
res.writeHead(404, {"Content-Type": "text/plain"});
res.write("404 Not Found\n");
res.end();
return;
}
if (fs.statSync(filename).isDirectory()) filename += '/index.html';
fs.readFile(filename, "binary", (err, file) => {
if (err) {
res.writeHead(500, {"Content-Type": "text/plain"});
res.write(err + "\n");
res.end();
return;
}
let headers = {},
contentType = contentTypes[path.extname(filename)];
if (contentType) headers["Content-Type"] = contentType;
res.writeHead(200, headers);
res.write(file, "binary");
res.end();
});
});
}
}).listen(parseInt(port, 10), () => console.log(`server running @ localhost:${port}`));