This repository was archived by the owner on Oct 6, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathserver.js
93 lines (87 loc) · 2.65 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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
var http = require("zed/http");
var fs = require("zed/fs");
var configFs = require("zed/config_fs");
var ui = require("zed/ui");
var mimeTypes = require("./mime_types");
// TODO: make this configurable
function getContentType(path) {
var parts = path.split('.');
var ext = parts[parts.length - 1];
return mimeTypes[ext] || "application/octet-stream";
}
function serveFileListing() {
return fs.listFiles().then(function(allFiles) {
var html = "<body><h1>File listing</h1><ul>";
allFiles.forEach(function(path) {
html += "<li><a href='" + path + "'>" + path + "</a></li>";
});
html += "<ul></body>";
return {
status: 200,
headers: {
"Content-Type": "text/html",
},
body: html
};
});
}
function requestHandler(fs, prefix, req) {
var path = req.path;
var pathParts = path.split('/');
var isDir = path[path.length - 1] === '/' || pathParts[pathParts.length - 1].indexOf('.') === -1;
if (isDir) {
// Let's normalize the path a bit
if (path[path.length - 1] === "/") {
path = path.substring(0, path.length - 1);
}
return fs.readFile(prefix + path + "/index.html", true).then(function(content) {
return {
status: 200,
headers: {
"Content-Type": "text/html"
},
body: content
};
}, function() {
return serveFileListing();
});
} else {
return fs.readFile(prefix + path, true).then(function(content) {
return {
status: 200,
headers: {
"Content-Type": getContentType(path)
},
body: content
};
}, function() {
return {
status: 404,
headers: {
"Content-Type": "text/plain"
},
body: "Not found"
};
});
}
}
module.exports = function(info) {
switch (info.action) {
case 'start':
http.startServer("staticserver", "Tools:Static Server:Request").then(function(url) {
console.log("Listening on", url);
ui.openUrl(url);
});
break;
case 'request':
var fs_ = fs;
if(info.fs === "config") {
fs_ = configFs;
}
var prefix = info.prefix || "";
return requestHandler(fs_, prefix, info.request);
case 'stop':
http.stopServer("staticserver");
break;
}
};