@@ -15,10 +15,10 @@ var server = require('http').createServer(httpHandler),
1515// directory of the open file!
1616if (process.env.INSTANT_MARKDOWN_OPEN_TO_THE_WORLD) {
1717 // Listen on any interface.
18- server.listen(8090, onListening);
18+ server.listen(8090, onListening).once( ' error ' , onServerError) ;
1919} else {
2020 // Listen locally.
21- server.listen(8090, ' 127.0.0.1' , onListening);
21+ server.listen(8090, ' 127.0.0.1' , onListening).once( ' error ' , onServerError) ;
2222}
2323
2424var md = new MarkdownIt({
@@ -37,7 +37,13 @@ var md = new MarkdownIt({
3737 }
3838});
3939
40- function writeMarkdown(input) {
40+ var lastWrittenMarkdown = ' ' ;
41+ function writeMarkdown(body) {
42+ lastWrittenMarkdown = md.render(body);
43+ io.sockets.emit(' newContent' , lastWrittenMarkdown);
44+ }
45+
46+ function readAllInput(input, callback) {
4147 var body = ' ' ;
4248 input.on(' data' , function(data) {
4349 body += data;
@@ -46,7 +52,7 @@ function writeMarkdown(input) {
4652 }
4753 });
4854 input.on(' end' , function () {
49- io.sockets.emit( ' newContent ' , md.render( body) );
55+ callback( body);
5056 });
5157}
5258
@@ -103,7 +109,7 @@ function httpHandler(req, res) {
103109 break ;
104110
105111 case ' PUT' :
106- writeMarkdown (req);
112+ readAllInput (req, writeMarkdown );
107113 res.writeHead(200);
108114 res.end ();
109115 break ;
@@ -114,8 +120,9 @@ function httpHandler(req, res) {
114120
115121io.sockets.on(' connection' , function(sock){
116122 process.stdout.write(' connection established!' );
117- writeMarkdown(process.stdin);
118- process.stdin.resume ();
123+ if (lastWrittenMarkdown) {
124+ sock.emit(' newContent' , lastWrittenMarkdown);
125+ }
119126});
120127
121128
@@ -126,4 +133,27 @@ function onListening() {
126133 else { // assume unix/linux
127134 exec(' xdg-open http://localhost:8090' );
128135 }
136+ readAllInput(process.stdin, function(body) {
137+ writeMarkdown(body);
138+ });
139+ process.stdin.resume ();
140+ }
141+
142+ function onServerError(e) {
143+ if (e.code === ' EADDRINUSE' ) {
144+ readAllInput(process.stdin, function(body) {
145+ // Forward to existing instant-markdown-d server.
146+ require(' http' ).request({
147+ hostname: ' localhost' ,
148+ port: 8090,
149+ path: ' /' ,
150+ method: ' PUT' ,
151+ }).end(body);
152+ });
153+ process.stdin.resume ();
154+ return ;
155+ }
156+
157+ // Another unexpected error. Raise it again.
158+ throw e;
129159}
0 commit comments