作為一個從業三年左右的,並且從事過半年左右PHP開發工作的前端,對於后台,尤其是對以js語言進行開發的nodejs,那是比較有興趣的,雖然本身並沒有接觸過相關的工作,只是自己私下做的一下小實驗,但是還是記錄一下方便以后復習!
今天主要記錄一下,很久以前用nodejs制作一個簡單的服務監聽程序的一些過程!
大家都知道,通過nodejs可以對前台請求進行監聽,這里就放一個官網的hello world例子吧:
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');
以上代碼相信了解過node的童鞋應該都會比較熟悉!
那么node既然可以監聽請求,那么是不是就可以根據前台的不同請求返回不同的文件或內容?這不就是一個簡單的服務器了么!抱着這樣的想法,簡單實驗了一下,我們都知道,服務器可以根據請求的文件不同,會使用相應mine類型的!比如../index.css使用的mine類型就是text/css!那么,我們是不是應該有個常用mine類型的一個簡單配置?這里,做了個簡單的mine配置文件mine.js,用json來存放一下常用的格式:
exports.types = {
"css": "text/css",
"gif": "image/gif",
"html": "text/html",
"ico": "image/x-icon",
"jpeg": "image/jpeg",
"jpg": "image/jpeg",
"js": "text/javascript",
"json": "application/json",
"pdf": "application/pdf",
"png": "image/png",
"svg": "image/svg+xml",
"swf": "application/x-shockwave-flash",
"tiff": "image/tiff",
"txt": "text/plain",
"wav": "audio/x-wav",
"wma": "audio/x-ms-wma",
"wmv": "video/x-ms-wmv",
"xml": "text/xml"
};
當然,除了這些以外還有很多其他格式,這里就不一一舉例了!
好了,有了mine格式對應的文件配置文件,接下來就簡單了,首先得根據官網例子搭建一個監聽程序,然后在監聽程序中添加一下簡單的www.baidu.com/這個樣的鏈接默認打開文件的處理,以及相對鏈接的補全等!當然還得做一下簡單的錯誤處理,如404,500等!具體看代碼:
/*
*搭建http服務器,監聽http請求
*/
var http = require("http"),
fs = require('fs'),
path = require('path'),
mine = require('./mine').types;
url = require('url');
//定義簡單的工具
//獲取當前時間
var date = function(ms) {
var date = ms ? new Date(ms) : new Date(),
mon = date.getMonth() >= 10 + 1 ? '-' : '-0',
d = date.getDate() >= 10 ? '-' : '-0',
hour = date.getHours() >= 10 ? ' ' : ' 0',
min = date.getMinutes() >= 10 ? ':' : ':0',
sec = date.getSeconds() >= 10 ? ':' : ':0';
return date.getFullYear() + mon + (date.getMonth() + 1) + d + date.getDate() + hour + date.getHours() + min + date.getMinutes() + sec + date.getSeconds();
},
//定義輸出log日志方法,帶上時間,方便調試
DebugLog = function(mes) {
var now = date();
console.log(now + " " + mes);
};
//服務監聽
exports.server = function() {
http.createServer(function(req, res) {
var pathname = url.parse(req.url).pathname,//獲取url中的文件名
pathname = (pathname !== "/" && pathname) ? pathname : "/index.html";//處理鏈接以'/'結尾的情況
var realPath = path.join("../", path.normalize(pathname.replace(/\.\./g, ""))),//將鏈接轉換成物理路徑
ext = path.extname(realPath);
ext = ext ? ext.slice(1) : 'unknown';//獲取文件擴展名
//查找文件
fs.exists(realPath, function (exists) {
if (!exists) {//處理404
res.writeHead(404, {
'Content-Type': 'text/plain'
});
res.write("This request URL " + pathname + " was not found on this server.");
res.end();
} else {//讀取文件
fs.readFile(realPath, "binary", function (err, file) {
if (err) {//程序出錯報500錯誤
res.writeHead(500, {
'Content-Type': 'text/plain'
});
res.end(err);
} else {//正常返回文件
var contentType = mine[ext] || "text/plain";//根據mine.js中的配置設置對應的contentType
res.writeHead(200, {
'Content-Type': contentType
});
res.write(file, "binary");
res.end();
}
});
}
});
}).listen(8888, 'localhost');
tool.DebugLog("http服務啟動,開始監聽127.0.0.1:8888的http請求!");
}
ok,代碼到這里基本就結束了,當然這只是最簡單的功能,大家可以自己去豐富!本文就到這里吧,歡迎大家交流討論!
