Skip to content

Instantly share code, notes, and snippets.

@JBreit
Created March 20, 2017 17:25
Show Gist options
  • Save JBreit/a1e14d75cf706ce4ec74927819da34c2 to your computer and use it in GitHub Desktop.
Save JBreit/a1e14d75cf706ce4ec74927819da34c2 to your computer and use it in GitHub Desktop.
var fs = require('fs');
exports.GET = function (path, respond) {
'use strict';
fs.stat(path, function (error, stats) {
if (error && error.code === "ENOENT") {
respond(404, "File not found");
} else if (error) {
respond(500, error.toString());
} else if (stats.isDirectory()) {
fs.readdir(path, function (error, files) {
if (error) {
respond(500, error.toString());
} else {
respond(200, files.join("\n"));
}
});
} else {
respond(200, fs.createReadStream(path), require("mime").lookup(path));
}
});
};
function respondErrorOrNothing(respond) {
'use strict';
return function (error) {
if (error) {
respond(500, error.toString());
} else {
respond(204);
}
};
}
exports.DELETE = function (path, respond) {
'use strict';
fs.stat(path, function (error, stats) {
if (error && error.code === "ENOENT") {
respond(204);
} else if (error) {
respond(500, error.toString());
} else if (stats.isDirectory()) {
fs.rmdir(path, respondErrorOrNothing(respond));
} else {
fs.unlink(path, respondErrorOrNothing(respond));
}
});
};
exports.POST = function (path, respond, req) {
'use strict';
req.on('data', function (chunk) {
console.log(chunk);
});
req.on();
};
exports.PUT = function (path, respond, req) {
'use strict';
var outStream = fs.createWriteStream(path);
outStream.on("error", function (error) {
respond(500, error.toString());
});
outStream.on("finish", function () {
respond(204);
});
req.pipe(outStream);
};
var http = require("http"),
config = require('./config'),
methods = require('./methods'),
host = config.host,
port = config.port;
var handleRequest = function (request, response) {
'use strict';
var method = request.method,
url = request.url;
var respond = function (code, body, type) {
if (!type) {
type = "text/plain";
}
response.writeHead(code, {"Content-Type": type});
if (body && body.pipe) {
body.pipe(response);
} else {
response.end(body);
}
};
var urlToPath = function (url) {
var join = require('path').join;
return join(process.cwd(), '/public', require('url').parse(url).pathname);
};
if (methods[method]) {
methods[method](urlToPath(url), respond, request);
} else {
respond(405, "Method " + request.method + " not allowed.");
}
};
var server = http.createServer(handleRequest);
server
.on('listening', function () {
'use strict';
console.log('> Server listening at ' + host + ':' + port);
})
.listen(port, host);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment