-
Notifications
You must be signed in to change notification settings - Fork 3
/
server.js
89 lines (78 loc) · 2.05 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
var express = require("express");
var app = express();
var winston = require("winston");
var expressWinston = require("express-winston");
// Set up error handling function
function clientErrorHandler(err, req, res, next) {
if (req.xhr) {
res.status(500).send({ error: "Something blew up!" });
} else {
next(err);
}
}
function errorHandler(err, req, res, next) {
res.status(500);
res.render("error", { error: err });
}
// I like my generated HTML pretty so I can see where I made mistakes in
// templating
app.use(function(req, res, next) {
app.locals.pretty = true;
next();
});
// Set up winston for logging
app.use(expressWinston.logger({
transports: [
new winston.transports.Console({
level: "debug",
handleExceptions: true,
json: false,
colorize: true
})
],
meta: false,
msg: "HTTP {{res.statusCode}} FROM {{req.connection.remoteAddress}} {{req.method}} {{res.responseTime}}ms {{req.url}}",
exitOnError: false
// expressFormat: true,
// colorStatus: true,
}));
// Start error logging
app.use(expressWinston.errorLogger({
transports: [
new winston.transports.Console({
json: true,
colorize: true
})
],
}));
// Set up error handling
app.use(clientErrorHandler);
app.use(errorHandler);
// Set the rendering engine (jade)
app.engine("jade", require("jade").__express);
app.set("view engine", "jade");
app.set("views", __dirname + "/views");
// Set up static asset directories
app.use(express.static(__dirname + "/public"));
// Set up routing
require('./routes')(app);
// Handle 404 errors
app.use(function(req, res, next){
res.status(404);
// respond with html page
if (req.accepts("html")) {
res.render("404", { url: req.url, title: "Page Not Found"});
return;
}
// respond with json
if (req.accepts("json")) {
res.send({ error: "Not found" });
return;
}
// default to plain-text. send()
res.type("txt").send("Not found");
});
// Start the server
var server = app.listen(3000, function() {
console.log("Listening on port %d", server.address().port);
});