static.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. /**
  2. * @Author HonorLee (dev@honorlee.me)
  3. * @Version 1.0 (2018-05-04)
  4. * @License MIT
  5. */
  6. 'use strict'
  7. //TODO Rewrite
  8. var Static = {
  9. load:function(assetFile,req,res){
  10. let ext = Path.extname(assetFile);
  11. if(!ext||ext==''){
  12. res.writeHead(404, {'Content-Type': 'text/html'});
  13. res.end();
  14. return;
  15. }
  16. if(ext.match(/png|jpg|jpeg|gif|ico/)){
  17. IMAGE.load(URL.parse(assetFile,true).pathname,ext,req,res);
  18. }else if(FILE.existsSync(assetFile)){
  19. var data;
  20. if(ext.match(/txt|js|css|html|json/)){
  21. try{
  22. data = FILE.readFileSync(assetFile,'utf-8');
  23. }catch(err){
  24. res.writeHead(404, {'Content-Type': 'text/html'});
  25. res.end();
  26. return false;
  27. }
  28. res.writeHead(200, { "Content-Type": MIME.lookup(ext)+';charset=utf-8'});
  29. res.end(data,'utf-8');
  30. //console.log(query)
  31. }else{
  32. try{
  33. data = FILE.readFileSync(assetFile,'binary');
  34. res.writeHead(200, { "Content-Type": MIME.lookup(ext),"Access-Control-Allow-Origin":"*"});
  35. res.end(data,'binary');
  36. }catch(err){
  37. res.writeHead(404, {'Content-Type': 'text/html'});
  38. res.end();
  39. }
  40. }
  41. }else{
  42. res.writeHead(404, {'Content-Type': 'text/html'});
  43. res.end();
  44. }
  45. }
  46. }
  47. module.exports=Static;