-
Notifications
You must be signed in to change notification settings - Fork 1
/
markdown-watch.js
149 lines (72 loc) · 2.47 KB
/
markdown-watch.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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
/**
* Module Dependencies
*
* fs filesystem access
* path domain + folder + extension manipulation
* http http server
*
* _ array + collection tools
* program cli tools to parse arguments, etc.
* marked markdown to html parser
* Handlebars HTML templating module
* HTMLtemplate Easy function to compile + return the html template
* FileSocketCollection Object that stores all sockets and file watchers
* info package.json file as an object
*
*/
var fs = require('fs'),
path = require('path'),
http = require('http'),
_ = require('lodash'),
program = require('commander'),
marked = require('marked'),
Handlebars = require('handlebars'),
HTMLtemplate = Handlebars.compile( fs.readFileSync(path.join(__dirname, 'http/index.html'), {encoding: 'utf8'}) ),
FileSocketCollection = require('./lib/FileSocketCollection'),
info = require('./package.json');
var LiveFiles = new FileSocketCollection;
program
.version( info.version )
.option('-p --port <n>', 'HTTP listening port', parseInt, 8080);
program.parse(process.argv);
var server = http.createServer(function (req, res) {
var filepath = path.join(process.cwd(), req.url)
.replace(path.extname(req.url), '')
.concat('.md'),
data = { port: program.port };
if ( fs.existsSync(filepath) ) {
res.statusCode = 200; // OK (202)
var markdown = marked( fs.readFileSync(filepath, {encoding: 'utf8'}) );
data.body = new Handlebars.SafeString( markdown );
}
else res.statusCode = 404; // Not Found (404)
res.setHeader('Content-Type', 'text/html');
res.end( HTMLtemplate(data) );
});
/** Setup the socket.io server that all
* clients will use to be notified of
* relevant file changes to trigger a
* page reload when file is changed.
*/
var socketIO = require('socket.io').listen(server, {log: false});
socketIO.on('connection', function (socket) {
/** When client connects, it sends a 'watch'
* event with a relative path to the desired
* file.
*/
socket.on('watch', function (filepath) {
filepath = path.join(process.cwd(), filepath)
.replace(path.extname(filepath), '')
.concat('.md');
try {
LiveFiles.add(filepath, socket);
}
catch (error) {
//socket.disconnect();
socket.emit('reload'); // Reload will display 404 page. A bit hacky, but works for now...
}
});
});
server.listen(program.port, function () {
console.log('Listening on port %s...', program.port);
});