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