取這麼一個標題,是因爲實在想不起去什麼名字
看網上的參考資料,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上扒下來的一篇博文