Simple image host.
Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

index.js 1.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. var http = require("http");
  2. var https = require("https");
  3. var fs = require("fs");
  4. var Context = require("./lib/context.js");
  5. var Db = require("./lib/db.js");
  6. var conf = JSON.parse(fs.readFileSync("conf.json"));
  7. var endpoints = {
  8. "/": "index.html",
  9. "/404": "404.html",
  10. "/viewer": "viewer.node.js"
  11. }
  12. //Prepare endpoints
  13. var errs = false;
  14. Object.keys(endpoints).forEach(function(i) {
  15. try {
  16. //The endpoint is a function if the file ends with .node.js
  17. if (/\.node\.js$/.test(endpoints[i])) {
  18. endpoints[i] = require("./"+conf.webroot+"/"+endpoints[i]);
  19. //If it doesn't end with .node.js, it's a regular text file and will
  20. //just be served as is
  21. } else {
  22. endpoints[i] = fs.readFileSync(conf.webroot+"/"+endpoints[i], "utf8");
  23. }
  24. //Errors will usually be because an endpoint doesn't exist
  25. } catch (err) {
  26. if (err.code == "ENOENT") {
  27. console.log(err.toString());
  28. errs = true;
  29. } else {
  30. throw err;
  31. }
  32. }
  33. });
  34. //No need to proceed if some endpoints don't exist
  35. if (errs) process.exit();
  36. //Prepare all templates
  37. var templates = {};
  38. fs.readdirSync("templates").forEach(function(f) {
  39. templates[f.replace(/\.html$/, "")] = fs.readFileSync("templates/"+f, "utf8");
  40. });
  41. //Function to run on each request
  42. function onRequest(req, res) {
  43. console.log("Request for "+req.url);
  44. var ep = endpoints[req.url];
  45. //If the file doesn't exist, we 404.
  46. if (!ep) {
  47. ep = endpoints["/404"];
  48. res.writeHead(404);
  49. }
  50. //Execute if it's a .node.js, or just respond with the contents of the file
  51. if (typeof ep == "function") {
  52. ep(new Context(req, res, templates, conf));
  53. } else {
  54. res.end(ep);
  55. }
  56. }
  57. //Initiate a postgresql client
  58. var db = new Db(conf.db, function(err) {
  59. if (err) throw err;
  60. //Create HTTP or HTTPS server
  61. var server;
  62. if (conf.use_https) {
  63. server = https.createServer(conf.https, onRequest);
  64. } else {
  65. server = http.createServer(onRequest);
  66. }
  67. server.listen(conf.port);
  68. console.log("Listening on port "+conf.port+".");
  69. });