Skip to content
Browse files

Serve files from process.cwd()

This allows to render markdown files that include relative links to
images or other files hosted on Github.

The patch also replaces the file serving code that was used with the
'send' module, which is the static file serving module that is used by
connect in order to simplify the code.
  • Loading branch information...
1 parent fe7549d commit bbc98afd0e2a893d89a9bacaa8b377b81d852af0 @felixge felixge committed Sep 29, 2012
Showing with 16 additions and 35 deletions.
  1. +14 −34 instant-markdown-d
  2. +2 −1 package.json
View
48 instant-markdown-d
@@ -4,8 +4,7 @@ var server = require('http').createServer(httpHandler),
spawn = require('child_process').spawn,
exec = require('child_process').exec,
io = require('socket.io').listen(server),
- fs = require('fs'),
- path = require('path'),
+ send = require('send'),
server,
socket;
@@ -15,39 +14,20 @@ function httpHandler(req, res) {
switch(req.method)
{
case 'GET':
- var filePath = __dirname + req.url;
- if (filePath == __dirname + '/'){
- filePath = __dirname + '/index.html';
+ // Example: /my-repo/raw/master/sub-dir/some.png
+ var githubUrl = req.url.match(/\/[^\/]+\/raw\/[^\/]+\/(.+)/);
+ if (githubUrl) {
+ // Serve the file out of the current working directory
+ send(req, githubUrl[1])
+ .root(process.cwd())
+ .pipe(res);
+ return;
}
- var extname = path.extname(filePath);
- var contentType = 'text/html';
- switch (extname) {
- case '.js':
- contentType = 'text/javascript';
- break;
- case '.css':
- contentType = 'text/css';
- break;
- }
-
- path.exists(filePath, function(exists) {
- if (exists) {
- fs.readFile(filePath, function(error, content) {
- if (error) {
- res.writeHead(500);
- res.end();
- }
- else {
- res.writeHead(200, { 'Content-Type': contentType });
- res.end(content, 'utf-8');
- }
- });
- }
- else {
- res.writeHead(404);
- res.end();
- }
- });
+
+ // Otherwise serve the file from the directory this module is in
+ send(req, req.url)
+ .root(__dirname)
+ .pipe(res);
break;
// case 'HEAD':
View
3 package.json
@@ -11,6 +11,7 @@
},
"dependencies": {
"socket.io": "",
- "docter": "https://github.com/suan/Docter/tarball/master"
+ "docter": "https://github.com/suan/Docter/tarball/master",
+ "send": "~0.1.0"
}
}

0 comments on commit bbc98af

Please sign in to comment.
Something went wrong with that request. Please try again.