static.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. var Path = require('path');
  2. var mime = require('mime-types');
  3. var ZLIB = require('zlib');
  4. var Static = {
  5. load:function(url,query,res){
  6. var ext = Path.extname(url);
  7. if(!ext||ext==''){
  8. res.writeHead(404, {'Content-Type': 'text/html'});
  9. res.end();
  10. return false;
  11. }
  12. if(ext.match(/png|jpg|jpeg|gif/)){
  13. // res.writeHead(404, {'Content-Type': 'text/html'});
  14. // res.end();
  15. return IMAGE.load(URL.parse(url,true).pathname,ext,query,res);
  16. }else if(FILE.existsSync(url)){
  17. var data;
  18. if(ext.match(/txt|js|css|html|json/)){
  19. try{
  20. data = FILE.readFileSync(url,'utf-8');
  21. }catch(err){
  22. res.writeHead(404, {'Content-Type': 'text/html'});
  23. res.end();
  24. return false;
  25. }
  26. if(ext.match(/json/)){
  27. res.writeHead(200, { "Content-Type": mime.lookup(ext)+';charset=utf-8'});
  28. res.end(data,'utf-8');
  29. }else{
  30. res.writeHead(200, { "Content-Type": mime.lookup(ext)+';charset=utf-8','Content-Encoding':'gzip'});
  31. res.end(ZLIB.gzipSync(data),'utf-8');
  32. }
  33. //console.log(query)
  34. }else if(ext.match(/json/)){
  35. }else{
  36. try{
  37. data = FILE.readFileSync(url,'binary');
  38. }catch(err){
  39. res.writeHead(404, {'Content-Type': 'text/html'});
  40. res.end();
  41. return false;
  42. }
  43. res.writeHead(200, { "Content-Type": mime.lookup(ext),"Access-Control-Allow-Origin":"*"});
  44. res.end(data,'binary');
  45. }
  46. return true;
  47. }else{
  48. res.writeHead(404, {'Content-Type': 'text/html'});
  49. res.end();
  50. return false;
  51. }
  52. }
  53. }
  54. module.exports=Static;