Skip to content

Instantly share code, notes, and snippets.

@wankdanker
Created November 18, 2011 16:13
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wankdanker/1376902 to your computer and use it in GitHub Desktop.
Save wankdanker/1376902 to your computer and use it in GitHub Desktop.
A simple static file server for node
var http = require('http'),
fs = require('fs'),
cwd = process.cwd();
http.createServer()
.on('request', function (request, response) {
var url = unescape(request.url);
var path = cwd + url;
console.log(request.socket.remoteAddress, path);
//stat the suggested path to see if it is a directory or file
fs.stat(path, function (err, pathStat) {
if (err) {
response.writeHead(404, {
'Content-Type' : 'text/html'
});
response.write(JSON.stringify(err));
response.end();
return false;
}
if (pathStat.isDirectory()) {
fs.readdir(path, function (err, files) {
var buffer = [], result;
if (err) {
response.writeHead(404, {
'Content-Type' : 'text/html'
});
response.write(JSON.stringify(err));
response.end();
return false;
}
//add a link to the parent directory
files.unshift('..');
//loop through all of the files
files.forEach(function (file, ix) {
//stat each file to see if it is a directory or a file
fs.stat(path + file, function (err, stats) {
if (err) {
response.writeHead(500, { 'Content-Type' : 'text/html' });
response.write(JSON.stringify(err));
response.end();
return false;
}
if (stats.isDirectory()) {
buffer.push('<tr><td><a href="' + url + file + '/">' + file + '</a></td><td align="right">-</td></tr>');
} else {
buffer.push('<tr><td><a href="' + url + file + '">' + file + '</a></td><td align="right">' + stats.size + '</td></tr>');
}
if (buffer.length == files.length) {
buffer.sort();
buffer = [ "<html>",
"<body>",
"<h2>Directory Listing for " + request.url + "</h2>",
"<hr>",
"<table width=\"25%\">",
"<tr><th align=\"left\">File</th><th align=\"right\">Size (Bytes)</th></tr>"]
.concat(buffer)
.concat([
"</table>",
"<hr>",
"</body>",
"</html>"
]);
result = buffer.join('\n');
response.writeHead(200, {
'Content-Length' : result.length,
'Content-Type' : 'text/html'
});
response.write(result);
response.end();
}
});
});
});
}
else {
fs.readFile(path, function (err, data) {
if (err) {
response.writeHead(404, {
'Content-Type' : 'text/html'
});
response.write('readfile');
response.write(JSON.stringify(err));
response.end();
return false;
}
response.writeHead(200, {
'Content-Length' : data.length
//'Content-Type' : 'text/text'
});
response.write(data);
response.end();
});
}
});
}).listen(8000);
console.log("SimpleHTTPServer Listening on port 8000");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment