Skip to content

Commit

Permalink
Serve files from process.cwd()
Browse files Browse the repository at this point in the history
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
felixge committed Sep 29, 2012
1 parent fe7549d commit bbc98af
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 35 deletions.
48 changes: 14 additions & 34 deletions instant-markdown-d
Expand Up @@ -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;

Expand All @@ -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':
Expand Down
3 changes: 2 additions & 1 deletion package.json
Expand Up @@ -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.