-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
114 lines (98 loc) · 2.99 KB
/
app.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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
// add some annotations
var express = require('express'),
jade = require('jade'),
url = require('url'),
path = require('path'),
fs = require('fs'),
bodyParser = require('body-parser');
var count = 1685;
var index = function(req, res) {
count++;
console.log(count + ' people have visited your website!');
res.render('index');
};
var partials = function (req, res) {
var name = req.params.name;
res.render(name);
};
var app = express();
app.set('views', __dirname + '/jades');
app.set('view engine', 'jade');
app.use(bodyParser());
app.engine('jade', jade.__express);
app.get('/', index);
app.get('/jades/:name', partials);
app.get('*', function(req, res) {
var pathname = url.parse(req.url).pathname;
var filePath = __dirname + pathname;
console.log(filePath);
// var mimeType = getMimeType(pathname);
if (fs.existsSync(filePath)) {
fs.readFile(filePath, function(err, data) {
if (err) {
res.writeHead(500);
res.end();
} else {
res.setHeader("Content-Length", data.length);
// res.setHeader("Content-Type", mimeType);
res.statusCode = 200;
res.end(data);
}
});
}
});
// Start server
app.listen(8000, function(){
console.log("Express server listening on port 3000");
});
// http.createServer(function (req, res) {
// var pathname = url.parse(req.url).pathname;
// var filePath = __dirname + pathname;
// var mimeType = getMimeType(pathname);
// if (pathname == '/') {
// count ++;
// console.log(count + '人访问过你的网站');
// filePath += '/index.html';
// fs.readFile(filePath, function(err, data) {
// if (err) {
// res.writeHead(500);
// res.end();
// } else {
// res.setHeader("Content-Length", data.length);
// res.setHeader("Content-Type", 'text/html');
// res.statusCode = 200;
// res.end(data);
// }
// });
// } else if (fs.existsSync(filePath)) {
// fs.readFile(filePath, function(err, data) {
// if (err) {
// res.writeHead(500);
// res.end();
// } else {
// res.setHeader("Content-Length", data.length);
// res.setHeader("Content-Type", mimeType);
// res.statusCode = 200;
// res.end(data);
// }
// });
// } else {
// res.writeHead(500);
// res.end();
// }
// }).listen(8000, function() {
// console.log('server listen on 8000');
// });
function getMimeType(pathname) {
var validExtensions = {
".html" : "text/html",
".js": "application/javascript",
".css": "text/css",
".jpg": "image/jpeg",
".gif": "image/gif",
".png": "image/png"
};
var ext = path.extname(pathname);
var type = validExtensions[ext];
return type;
}