node.js--靜態檔案請求模組

來源:互聯網
上載者:User

標籤:blog   http   io   使用   ar   java   檔案   sp   div   

【實現一個靜態資源管理模組】

 

/**  *static_module.js  */var BASE_DIR = __dirname,   //絕對路徑    CONF = BASE_DIR + ‘/conf/‘,    //conf檔案的路徑    STATIC = BASE_DIR + ‘/static‘,  //靜態檔案的路徑    mmieConf;  //用來儲存mmie json//檔案及其相關mmie類型儲存在mmie_type.json裡,讀取這個jsonvar getMmieConf = function(){  var conf = {};  try{    var confStr = fs.readFileSync(CONF + ‘mmie_type.json‘, ‘utf8‘);//同步讀取檔案    conf = JSON.parse(confStr);  }catch{    util.debug(‘JSON parse fails‘);  }  return conf;};var util = require(‘util‘),    fs = require(‘fs‘),    http = require(‘http‘),    url = require(‘url‘),    path = require(‘path‘);mmieConf = getMmieConf();//擷取靜態檔案的介面//pathname:靜態檔案相對路徑   req:requset對象   res:response對象exports.getStaticFile = function(pathname,  req,   res){  var extName = path.extname(pathname);  //path模組的extname方法可以擷取url的檔案尾碼,例如‘.html‘  extName = extName ? extName.slice(1) : ‘‘; //‘html‘  var realPath = STATIC + pathname;  var mmieType = mmieConf[extName] || ‘text/plain‘;    fs.exists(realPath, function(exsit){ //判斷檔案是否存在    if( !exsit ){//如果不存在,返回404      res.writeHead(404, {‘Content-Type‘: ‘text/plain‘});      res.write(‘the file in‘ + pathname + ‘was not found‘);      res.end();    }else{//如果檔案存在,判斷檔案是否符合緩衝條件,如果符合就返回304,不符合就讀取靜態檔案返回      var fileInfo = fs.statSync(realPath); //fs.statSync擷取檔案相關資訊,返回的是一個json,其中mtime屬性記錄了檔案的最後修改時間      var lastModifiedTime = fileInfo.mtime.toUTCString();      //設定緩衝相關的頭            if(mmieConf[extName]){        var date = new Date();        res.setHeader(‘expires‘, date.toUTCString());//設定到期時間        res.setHeader(‘Cache-Control‘, ‘max-age=‘ + 60*60*24*365);      }      //判斷是否到期,如果未到期就304,已到期就讀取檔案      if(req.headers[‘if-modified-since‘] && lastModifiedTime = req.header[‘if-modified-since‘]){//req對象中的header有記錄檔案的最後修改時間,如果和服務                                                         //器的最後修改時間一致說明檔案一直沒有被改動過,304就好了        res.writeHead(304, ‘not modified‘);        res.end();      }else{//讀取靜態檔案        fs.readFile(realPath, ‘binary‘, function(err, file){          if(err){//讀取檔案出錯啦            res.writeHead(500, ‘Content-Type:plain‘);            res.end(err);          }else{            res.setHeader(‘Last-Modified‘, lastModifiedTime);            res.writeHead(‘200‘, {‘Content-Type‘: mmieType});            res.write(file, ‘binary‘);            res.end();          }        })      }    }  });}

  

 

使用這個模組:

var staticModule = require(‘./static_module‘);http.createServer(function(res, req){    var pathname = url.parse(req.url).pathname;//擷取相對路徑    if( pathname == ‘/favicon.ico‘){        return;    }else if( pathname == ‘/index‘ || pathname == ‘/‘ ){        gotoIndex();    }else{        staticModule.getStaticFile(pathname, req, res);    }});                

  

  

node.js--靜態檔案請求模組

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.