Permalink
Browse files

support html directories

  • Loading branch information...
omphalos committed Aug 7, 2012
1 parent 80f3b1d commit f23eddb982086eb34d46525ad8fbc054351bd2bc
Showing with 43 additions and 8 deletions.
  1. +3 −1 README.md
  2. +39 −6 crud-file-server.js
  3. +1 −1 package.json
View
@@ -32,7 +32,9 @@ Server-Side Usage
Supported operations
====================
-**GET** returns a file's contents with the correct mime type, or else the contents of a directory as a JSON array.
+**GET** returns a file's contents with the correct mime type, or else the contents of a directory as html.
+
+**GET** http://localhost?dir=json returns directories as json instead of html.
**PUT** can be used to write a file.
View
@@ -79,22 +79,55 @@ exports.handleRequest = function(vpath, path, req, res, readOnly) {
if(err) { writeError(err); }
else {
if(stats.isDirectory()) {
+ res.setHeader('Last-Modified', stats.mtime);
// if it's a directory, return the files as a JSONified array
console.log('reading directory ' + relativePath);
fs.readdir(relativePath, function(err, files) {
- if(err) { writeError(err); }
+ if(err) {
+ console.log('writeError');
+ writeError(err);
+ }
else {
- res.setHeader('Last-Modified', stats.mtime);
- res.setHeader('Content-Type', 'application/json');
- res.write(JSON.stringify(files));
- res.end();
+ var results = [];
+ var search = {};
+ search.stats = function(files) {
+ if(files.length) {
+ var file = files.shift();
+ fs.stat(relativePath + '/' + file, function(err, stats) {
+ if(err) { writeError(err); }
+ else {
+ stats.name = file;
+ stats.isFile = stats.isFile();
+ stats.isDirectory = stats.isDirectory();
+ stats.isBlockDevice = stats.isBlockDevice();
+ stats.isFIFO = stats.isFIFO();
+ stats.isSocket = stats.isSocket();
+ results.push(stats);
+ search.stats(files);
+ }
+ });
+ } else {
+ if(query.dir == 'json') {
+ res.setHeader('Content-Type', 'application/json');
+ res.write(JSON.stringify(results));
+ res.end();
+ } else {
+ res.setHeader('Content-Type', 'text/html');
+ res.write('<html><body>');
+ for(var f = 0; f < results.length; f++) {
+ res.write('<p><a href="/' + url + '/' + results[f].name + '">' + results[f].name + '</a></p>');
+ }
+ res.end('</body></html>');
+ }
+ }
+ };
+ search.stats(files);
}
});
} else {
// if it's a file, return the contents of a file with the correct content type
console.log('reading file ' + relativePath);
var type = require('mime').lookup(relativePath);
- res.setHeader('Last-Modified', stats.mtime);
res.setHeader('Content-Type', type);
fs.readFile(relativePath, function(err, data) {
if(err) { writeError(err); }
View
@@ -1,6 +1,6 @@
{
"name": "crud-file-server",
- "version": "0.1.3",
+ "version": "0.1.4",
"description": "file server supporting basic create, read, update, & delete for any kind of file",
"bin": {
"crud-file-server": "./bin/crud-file-server"

0 comments on commit f23eddb

Please sign in to comment.