nodejs 本地php服务器,Nodejs搭建本地http服务器
由于不做php相關(guān)的東西,懶得裝apache,干脆利用nodejs搭建一個(gè)本地的服務(wù)器用于測(cè)試。
nodejs這玩意兒吧,對(duì)做前端的介入后端簡(jiǎn)直就是一把利器。而且目前,nodejs也越來(lái)越有商用價(jià)值。
nodejs其實(shí)是非常底層的,從功能上說(shuō),它既是apache也是php。像搭建http服務(wù)器這種功能,本來(lái)是apache已經(jīng)封裝好的,但nodejs需要我們手動(dòng)來(lái)搭建。其實(shí)在實(shí)際應(yīng)用中,我們可以使用現(xiàn)成的框架。但這里,我想手動(dòng)搭建,也加深一下對(duì)http服務(wù)器的理解。
我們node執(zhí)行下面這個(gè)文件,我命名為http.js,它將創(chuàng)建一個(gè)httpServer并監(jiān)聽(tīng)3000端口。
var PORT = 3000;
var http = require('http');
var url=require('url');
var fs=require('fs');
var mine=require('./mine').types;
var path=require('path');
var server = http.createServer(function (request, response) {
var pathname = url.parse(request.url).pathname;
var realPath = path.join("assets", pathname);
//console.log(realPath);
var ext = path.extname(realPath);
ext = ext ? ext.slice(1) : 'unknown';
fs.exists(realPath, function (exists) {
if (!exists) {
response.writeHead(404, {
'Content-Type': 'text/plain'
});
response.write("This request URL " + pathname + " was not found on this server.");
response.end();
} else {
fs.readFile(realPath, "binary", function (err, file) {
if (err) {
response.writeHead(500, {
'Content-Type': 'text/plain'
});
response.end(err);
} else {
var contentType = mine[ext] || "text/plain";
response.writeHead(200, {
'Content-Type': contentType
});
response.write(file, "binary");
response.end();
}
});
}
});
});
server.listen(PORT);
console.log("Server runing at port: " + PORT + ".");
上面我們還引入了一個(gè)mine.js,這是我自己寫(xiě)的,里面存儲(chǔ)的是名值對(duì),用于定義不同后綴的文件所對(duì)應(yīng)的返回方式:
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"
};
fs模塊是用于讀取文件的,提供讀取文件的方法,其實(shí)仔細(xì)研究文檔會(huì)發(fā)現(xiàn),它有同步和異步兩種讀取方式。fs.exists這個(gè)方法網(wǎng)上很多文章寫(xiě)作path.exists,,現(xiàn)在推薦寫(xiě)作fs.exists這個(gè)方法。否則會(huì)報(bào)警:
需要注意的是,不僅瀏覽器訪問(wèn)html文件會(huì)形成一次訪問(wèn),里面鏈接的js,css等外部文件也會(huì)分別形成一次http訪問(wèn)。所以,http.createServer的回調(diào)其實(shí)是在一次頁(yè)面訪問(wèn)中執(zhí)行了多次的。我們console.log(realPath)一下就可以看到:
這里并沒(méi)有加入默認(rèn)訪問(wèn)index.html的功能,所以訪問(wèn)地址要寫(xiě)全http://127.0.0.1:3000/index.html
Node.js 的詳細(xì)介紹:請(qǐng)點(diǎn)這里
Node.js 的下載地址:請(qǐng)點(diǎn)這里
總結(jié)
以上是生活随笔為你收集整理的nodejs 本地php服务器,Nodejs搭建本地http服务器的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: php.ini settimelimit
- 下一篇: php无法用mail函数发送邮件之原因