serve.js 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. var fs = require('fs');
  2. var path = require('path');
  3. function CDN(dir){
  4. return function(req, res){
  5. if(serve(req, res)){ return } // filters GUN requests!
  6. fs.createReadStream(path.join(dir, req.url)).on('error',function(tmp){ // static files!
  7. try{ tmp = fs.readFileSync(path.join(dir, 'index.html')) }catch(e){}
  8. res.writeHead(200, {'Content-Type': 'text/html'});
  9. res.end(tmp+''); // or default to index
  10. }).pipe(res); // stream
  11. }
  12. }
  13. function serve(req, res, next){
  14. if(typeof req === 'string'){ return CDN(req) }
  15. if(!req || !res){ return false }
  16. next = next || serve;
  17. if(!req.url){ return next() }
  18. if(0 <= req.url.indexOf('gun.js')){
  19. res.writeHead(200, {'Content-Type': 'text/javascript'});
  20. res.end(serve.js = serve.js || require('fs').readFileSync(__dirname + '/../gun.js'));
  21. return true;
  22. }
  23. if(0 <= req.url.indexOf('gun/')){
  24. res.writeHead(200, {'Content-Type': 'text/javascript'});
  25. var path = __dirname + '/../' + req.url.split('/').slice(2).join('/'), file;
  26. try{file = require('fs').readFileSync(path)}catch(e){}
  27. if(file){
  28. res.end(file);
  29. return true;
  30. }
  31. }
  32. return next();
  33. }
  34. module.exports = serve;