-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstatic_page_server.js
More file actions
131 lines (115 loc) · 3 KB
/
static_page_server.js
File metadata and controls
131 lines (115 loc) · 3 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
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
var PORT = 8888;
var HOSTNAME = '127.0.0.1';
var http = require("http");
var url = require("url");
var path = require("path");
var fs = require("fs");
var co = require("co");
http.createServer(function (req, res) {
var Response = {
"200": function(content) {
var header = {
"Pragma": "no-cache"
, "Cache-Control": "no-cache"
}
console.log(200);
console.log(content);
res.writeHead(200, header);
res.write(content, "binary");
res.end();
}
, "404": function() {
var header = {
"Content-Type": "text/plain"
}
console.log(404);
res.writeHead(404, header);
res.write("404 Not Found\n");
res.end();
}
, "500": function(err) {
console.log(err);
var header = {
"Content-Type": "text/plain"
}
console.log(500);
res.writeHead(500, header);
res.write(err + "\n");
res.end();
}
}
var uri = url.parse(req.url).pathname;
var filename = path.join(process.cwd(), uri);
var f = function(filename, is_dir) {
var is_dir = (is_dir === undefined) ? false : is_dir;
co (function *() {
var status_code = '';
var content = '';
yield new Promise(function(resolve, reject) {
// ディレクトリの場合
if (is_dir) {
fs.readdir(filename, function(err, files) {
if (!err) {
content = filename + '\n\n';
content += files.join('\n').toString();
resolve();
} else {
reject(err);
}
});
// ファイルの場合
} else {
fs.readFile(filename, "binary", function(err, file) {
if (!err) {
content = file;
resolve();
} else {
reject(err);
}
});
}
}).then(
function onResolved() {
console.log('onRes');
status_code = 200;
}
, function onRejected(err) {
console.log('onRej');
content = err;
status_code = 500;
}
);
console.log('response!');
Response[status_code](content);
});
return ;
}
fs.stat(filename, function(err, stats) {
console.log("path: " + filename);
console.log("e: " + err);
// ファイルもディレクトリもない
if (err) {
Response["404"]();
return;
}
console.log(stats);
if (stats.isFile()) {
f (filename);
} else if (stats.isDirectory()) {
new Promise(function(resolve, reject) {
fs.stat(filename + '/index.html', function(err, stats) {
var is_dir = true;
if (!err) {
is_dir = false;
filename += '/index.html';
console.log('1' + filename);
}
resolve(is_dir);
});
}).then(function (is_dir) {
f (filename, is_dir);
});
}
});
}).listen(PORT);
console.log('Server running at http://' + HOSTNAME + ':' + PORT + '/');