forked from Mermade/shins
-
Notifications
You must be signed in to change notification settings - Fork 0
/
arapaho.js
96 lines (83 loc) · 2.7 KB
/
arapaho.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
'use strict';
const fs = require('fs');
const path = require('path');
const express = require('express');
const ejs = require('ejs');
const compression = require('compression');
const args = require('tiny-opts-parser')(process.argv);
const shins = require('./index.js');
let includesModified = false;
let lastGenTime = {};
if (args.p) args.preserve = true;
let app = express();
app.use(compression());
app.set('view engine', 'html');
app.engine('html', ejs.renderFile);
fs.watch('source/includes', function(eventType, filename) {
includesModified = true;
});
function getLastGenTime(fpath) {
if (lastGenTime[fpath]) return lastGenTime[fpath];
return 0;
}
function check(req,res,fpath) {
fpath = fpath.split('/').join('');
var srcStat = fs.statSync(path.join(__dirname,'source',fpath+'.md'));
var dstStat = {mtime:getLastGenTime(fpath)};
if (!args.preserve) {
try {
dstStat = fs.statSync(path.join(__dirname,fpath));
}
catch (ex) { }
}
if (includesModified || (srcStat.mtime>dstStat.mtime)) {
includesModified = false;
lastGenTime[fpath] = new Date();
console.log('Rebuilding '+fpath);
let source = path.join(__dirname,'source',fpath+'.md');
fs.readFile(source,'utf8',function(err,markdown){
if (markdown) {
let options = {};
if (req.query.customcss) {
options.customCss = true;
}
if (req.query.inline) {
options.inline = true;
}
if (req.query.minify) {
options.minify = true;
}
options.source = source;
shins.render(markdown,options,function(err,html){
if (err) {
console.warn(err);
res.send(err);
}
else {
res.send(html);
if (!args.preserve) {
fs.writeFile(path.join(__dirname,fpath),html,'utf8',function(){});
}
}
});
}
});
}
else {
res.render(path.join(__dirname,fpath));
}
}
app.get('/', function(req,res) {
check(req,res,'index.html');
});
app.get('*.html', function(req,res) {
check(req,res,req.path);
});
app.use("/", express.static(__dirname));
var myport = process.env.PORT || 4567;
if (args._.length>2) myport = args._[2];
var server = app.listen(myport, function () {
var host = server.address().address;
var port = server.address().port;
console.log('Arapaho server listening at http://%s:%s', host, port);
});