Repository navigation
Expand file tree
/
Copy pathindex.js
More file actions
93 lines (82 loc) · 2.96 KB
/
Copy pathindex.js
File metadata and controls
93 lines (82 loc) · 2.96 KB
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
'use strict';
var fs = require('fs');
var path = require('path');
var qfs = require("q-io/fs");
var marked = require('marked');
var highlight = require("highlight.js");
var pointer = require("json-pointer");
var Q = require("q");
var css = fs.readFileSync(__dirname + "/style/def.css", 'utf8');
marked.setOptions({
renderer: new marked.Renderer(),
gfm: true,
tables: true,
breaks: true,
pedantic: true,
sanitize: true,
smartLists: true,
smartypants: true,
highlight: function (code) {
return highlight.highlightAuto(code).value;
}
});
module.exports = function(args){
var dir = args.path;
var allowedFilesPaths;
var list;
if (!dir) throw "Path required!";
return function(req, res, next){
init().then(function(){
if ( allowedFilesPaths[req.query.page] ){
fs.readFile(allowedFilesPaths[req.query.page], 'utf8', function(err, data){
if (err) return next();
marked(data, function (err, content) {
if (err) throw err;
res.send("<head><style>"+css+"</style></head>"+content);
});
});
} else {
var url = req.originalUrl.replace(/\?.*/, '');
res.send( "<head><style>"+css+"</style></head>" + renderList(list , "Specifications", url));
}
});
function walk(dir){
allowedFilesPaths = {};
list = {};
return qfs.listTree(dir).then(function(data){
data.map(function(point){
var pathRe = new RegExp(dir);
point = point.replace(pathRe, "");
if( (/.md/).test(point) ){
var purePoint = point.replace(/\.md/, "");
if (purePoint.indexOf('\\') !== -1) {
purePoint = purePoint.replace(/\\/g, '/')
purePoint = purePoint.replace(/[A-z]:/g, '')
}
pointer.set(list, purePoint, purePoint);
allowedFilesPaths[purePoint] = dir + point;
}
});
});
}
function renderList(list, name, url){
var html ="<h3>"+ name + "</h3><ul>";
for( var key in list){
if ( typeof list[key] == "object" ){
html += renderList(list[key], key, url);
} else {
html += '<li><a href="'+url+'?page='+list[key]+'">' + key.replace(/\..*/, "") + "</a></li>";
}
}
html += "</ul>";
return html;
}
function init(){
if ( !allowedFilesPaths || !list ){
return walk(dir).catch(function (err) { console.error(err) });
} else {
return Q();
}
}
};
};