Node.js筆記-不使用頁面模板渲染介面

來源:互聯網
上載者:User

Node.js筆記-不使用頁面模板渲染介面

取這麼一個標題,是因為實在想不起去什麼名字
看網上的參考資料,ejs黨和jade黨勢如水火Σ( ° △ °|||)︴
但對於我等新手,暫時不想分心去瞭解模板引擎,專心於html不是挺好的嘛

——————————————————————————
本文參考了Node.js實戰的第二章,源碼附在最後

首先看核心代碼,目的是從緩衝或者硬碟中讀取html檔案:

function serveStatic(response, cache, absPath) {  if (cache[absPath]) {//檢查檔案是否在緩衝中    sendFile(response, absPath, cache[absPath]);//從記憶體中返迴文件  } else {    fs.exists(absPath, function(exists) {//檢查檔案是否存在      if (exists) {        fs.readFile(absPath, function(err, data) {//從硬碟中返迴文件          if (err) {            send404(response);          } else {            cache[absPath] = data;//加入緩衝中            sendFile(response, absPath, data);//讀取檔案並返回          }        });      } else {        send404(response);      }    });  }}

send404和sendFile函數的實現

function send404(response) {  response.writeHead(404, {'Content-Type': 'text/plain'});  response.write('Error 404: resource not found.');  response.end();}function sendFile(response, filePath, fileContents) {  response.writeHead(    200,     {"content-type": mime.lookup(path.basename(filePath))}  );  response.end(fileContents);}

接下來是建立伺服器

var server = http.createServer(function(request, response) {  var filePath = false;  if (request.url == '/') {    filePath = 'public/index2.html';  } else {    filePath = 'public' + request.url;  }  var absPath = './' + filePath;  serveStatic(response, cache, absPath);});

運行一下,應該是從csdn上扒下來的一篇博文

http://pan.baidu.com/s/1bnvYkSB

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.