-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathquickie.js
82 lines (67 loc) · 1.89 KB
/
quickie.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
var http = require('http');
var Router = require('routes-router');
var st = require('st');
var fs = require('fs');
module.exports = {
site: function(options) {
return new QuickySite(options);
}
}
var QuickySite = function(options) {
var self = this;
if(typeof(options) == 'string') {
self.options = {
dirname: options
};
} else {
self.options = options;
}
self.dirname = self.options.dirname;
self.staticPrefix = self.options.assets || 'public/';
self.pagePrefix = self.options.tempaltes || 'templates/';
self.renderer = self.options.render || null;
self.extension = self.options.extension || '.html';
self.app = Router();
self.addRoute = function(match, callback) {
return self.app.addRoute(match, callback);
}
self.renderPage = function(markup, data) {
if(self.renderer) {
return self.renderer(markup.toString(), data);
} else {
return markup;
}
}
self.sendPage = function(req, res, pageName, data) {
var path = self.pagePrefix + pageName + self.extension;
fs.readFile(path, function (err, markup) {
if (err) {
console.log('404: ')
res.end("404! We can't find that page.");
} else {
res.writeHead(200, {'Content-Type': 'text/html'});
res.end(self.renderPage(markup, data));
}
});
}
self.initialize = function() {
self.addRoute("/public/*", st({
path: self.dirname + "/public",
url: "/public"
}));
self.addRoute('/:pageName', function(req, res, opts){
return self.sendPage(req, res, opts.params.pageName);
});
self.addRoute('/', function(req, res){
return self.sendPage(req, res, 'index');
});
}
self.listen = function(port) {
var port = port || 3000;
self.initialize();
var server = http.createServer(self.app);
server.listen(port);
console.log('Server listening at '+port);
}
return self;
}