node.js服務(wù)分解

字號(hào):


    上一篇文章描述了一下基本的node服務(wù)配置安裝,下面對(duì)一個(gè)node javascript服務(wù)進(jìn)行分解,并分析。
    首先說(shuō)一下,上篇文章中安裝的node,是一個(gè)javascript服務(wù)器運(yùn)行環(huán)境。其封裝了javascript寫(xiě)的包.node沒(méi)有監(jiān)聽(tīng)服務(wù)器端口,而實(shí)際是通過(guò)
    ,建立一個(gè)server.js監(jiān)聽(tīng)文件,用node進(jìn)行運(yùn)行,監(jiān)聽(tīng)對(duì)應(yīng)的端口,并執(zhí)行相關(guān)操作。
    然后說(shuō)一下,上次運(yùn)行的代碼:
    var http = require("http");//引入http請(qǐng)求模塊,以后還會(huì)有url模塊等
    http.createServer(function(request, response)
    { response.writeHead(200, {"Content-Type": "text/plain"});
    response.write("Hello World"); response.end();
    }).listen(9999);//將句柄進(jìn)行端口9999監(jiān)聽(tīng),并執(zhí)行匿名函數(shù),函數(shù)的參數(shù)為request和response
    轉(zhuǎn)換一下:
    var http = require("http");
    function listen(request.response){
    response.writeHead(200,{"Content-Type":"text/plain"});//函數(shù)發(fā)送一個(gè)HTTP狀態(tài)200和HTTP頭的內(nèi)容類(lèi)型(content-type),
    response.write("Hello World");//使用 response.write() 函數(shù)在HTTP相應(yīng)主體中發(fā)送文本“Hello World"。
    response.end();
    }
    http.createServer(listen).listen(9999);//創(chuàng)建監(jiān)聽(tīng)服務(wù),以及監(jiān)聽(tīng)處理函數(shù)
    當(dāng)運(yùn)行node server.js后,node主動(dòng)監(jiān)聽(tīng)9999端口,當(dāng)請(qǐng)求來(lái)時(shí),則會(huì)調(diào)用listen函數(shù)。這里可以將我們server.js理解為一個(gè)等待請(qǐng)求服務(wù)的程
    序。
    如何將server.js 當(dāng)做一個(gè)模塊去引入,就像php引入公共文件一樣呢?
    將上面的代碼封裝到一個(gè)函數(shù)
    var http = require("http");
    function servername(){
    function listen(request.response){
    response.writeHead(200,{"Content-Type":"text/plain"});//函數(shù)發(fā)送一個(gè)HTTP狀態(tài)200和HTTP頭的內(nèi)容類(lèi)型( content-type),
    response.write("Hello World");//使用 response.write() 函數(shù)在HTTP相應(yīng)主體中發(fā)送文本“Hello World"。
    response.write("server Caller");
    response.end();
    }
    http.createServer(listen).listen(9999);//創(chuàng)建監(jiān)聽(tīng)服務(wù),以及監(jiān)聽(tīng)處理函數(shù)
    }
    exports.start = servername;//對(duì)外接口為servername函數(shù)
    在同級(jí)文件夾 建立一個(gè)index.js文件,內(nèi)容為:
    var server = require("./server")
    server.start();
    保存index.js文件
    然后運(yùn)行 node index.js 這時(shí)候你再次訪問(wèn)9999端口,你也會(huì)看到helloworld,并且看到是server Caller.
    這就是基本的node運(yùn)行,并且通過(guò)js文件來(lái)定義自定義的服務(wù)模塊。