Repository navigation
Expand file tree
/
Copy pathserver.js
More file actions
executable file
·66 lines (57 loc) · 1.57 KB
/
Copy pathserver.js
File metadata and controls
executable file
·66 lines (57 loc) · 1.57 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
57
58
59
60
61
62
63
64
65
66
"use strict";
const PORT = 3000;
const http = require('http');
const fs = require('fs');
function serveIndex(path, res) {
fs.readdir('public' + path, function(err, files) {
if(err) {
console.error(err);
res.statusCode = 404;
res.end("Server Error");
}
fs.access('index.html', 'r', (err, fd) => {
serveFile(path, res);
});
var html = "<p>Index of " + path + "</p>";
html += "<ul>";
html += files.map(function(item){
console.log(path);
if(path != "/") {
return "<li><a href='" + path + '/' + item + "'>" + item + "</a></li>";
}
return "<li><a href='" + item + "'>" + item + "</a></li>";
}).join("");
html += "</ul>";
res.end(html);
});
}
function serveFile(path, res) {
fs.readFile('public' + path, function(err, data) {
if(err) {
console.error(err);
res.statusCode = 404;
res.end("File could not be found.");
return;
}
res.end(data);
});
}
function handleRequest(req, res) {
console.log(req.url);
fs.stat('public' + req.url, function(err, stats) {
if(err) {
res.statusCode = 404;
res.end("File could not be found.");
}
else if(!stats.isFile()) {
serveIndex(req.url, res);
}
else {
serveFile(req.url, res);
}
})
}
var server = http.createServer(handleRequest);
server.listen(PORT, function(){
console.log("Listening on port " + PORT);
});