-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathrouter.js
71 lines (59 loc) · 2.09 KB
/
router.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
var router = require('express').Router();
var fs = require('fs');
var path = require('path');
var marked = require('marked')
var config = require('./config');
var utils = require('./utils');
marked.setOptions({headerIds: true});
var renderer = {
heading(text, level) {
var escapedText = text.replace(/[\s]+/g, '-');
return '<h' + level + '><a name="' +
escapedText +
'" class="anchor" href="#' +
escapedText +
'">' +
text + '</a></h' + level + '>';
}
};
marked.use({ renderer });
router.get("*", function(req, res){
//get path from uri
var contentPath = req.url.match('^[^?]*')[0];
//join root path to content to uri path
var fullPath = path.join(config.contentRootPath, contentPath);
console.log('GET: ' + fullPath);
//use README.md as default document in path if one is not specified
if(!path.extname(fullPath)){
fullPath = path.join(fullPath, 'README.md')
}
//check if file exists
if (!fs.existsSync(fullPath)) {
return res.sendStatus(404);
}
//read file contents
var file = fs.readFileSync(fullPath);
//check file extension is markdown
if (utils.isFileExtensionMatch(fullPath, config.markdownFileExtensions)){
//if markdown, return html rendered markdown
var data = marked(file.toString());
var page_type;
if( path.basename(fullPath) === 'README.md' ) {
page_type = 'front';
} else {
page_type = 'content';
}
return res.render('index', { page_type:page_type, markdown:data })
} else if (utils.isFileExtensionMatch(fullPath, config.nativeRenderFileExtensions)){
//if native file (e.g. pdf), render directly - TODO: fix pdf rendering
return res.send(file)
} else {
//all other files, render as code block
var fileName = path.basename(fullPath);
var fileExt = path.extname(fullPath);
var data = marked('```' + fileExt + '\n' + file.toString() + '```');
return res.render('index', { title:fileName, markdown:data })
}
res.render
});
module.exports = router;