node.js函式呼叫
阿新 • • 發佈:2018-11-30
首先建立web服務,官網上有現成的demo,建議還是自己瞭解寫一遍。新建一個stratServer.js檔案,
//require方法匯入nodejs的一個物件http var http = require("http"); //http新建一個web服務,其中function包含兩個物件,request是瀏覽器向服務端傳送請求的物件,response是服務端向瀏覽器寫回的物件 http.createServer(function(request,response){ //響應頭,200表示成功狀態碼,輸出型別是html型別,編碼格式為utf-8 response.writeHead(200,{'Content-Type':'text/html; charset=utf-8'}); //消除在頁面重新整理一次後dos視窗總會出現兩次“訪問” if(request.url!="/favicon.ico"){ //在dos視窗輸出 console.log('訪問'); //網頁上輸出 response.write('Hello World!'); //有響應頭就需要有響應尾,否則頁面一直載入不結束 response.end(); } //監聽8000埠 }).listen(8000); //web服務建立成功,dos視窗輸出 console.log('Server running at http://127.0.0.1:8000/');
函式內部呼叫
直接在建立web服務的文件後面接著寫需求函式,在內部呼叫。唯一修改的地方就是在原本網頁上輸出的地方,不在直接輸出文字,而是呼叫定義好的函式。
var http = require('http'); http.createServer(function(request,response){ response.writeHead(200,{'Content-Type':'text/html; charset=utf-8'}); if(request.url!="/favicon.ico"){ fun1(response); response.end(); } }).listen(8000); console.log('Server running at http://127.0.0.1:8000/'); function fun1(res){ console.log("fun1"); res.write("本地呼叫函式!"); }
函式外部呼叫
新建一個資料夾,其中放入startServer.js 和 otherfun.js 。先在otherfun.js 中定義外部的函式,如下程式碼這種寫法可支援多種函式的呼叫,
//支援呼叫多個函式
module.exports={
fun2:function(res){
console.log("我是fun2");
res.write("fun2");
},
fun3:function(res){
console.log("我是fun3");
res.write("fun3");
}
}
startServer.js文件中,需要呼叫外部的函式,得先獲取它的位置,因為兩檔案同屬一個目錄下,所以require匯入的地址 ./ 表示當前目錄,將其儲存在定義的變數中,呼叫時 變數名.函式名(引數)。
var http = require('http');
var otherfun = require("./otherfun.js");
http.createServer(function(request,response){
response.writeHead(200,{'Content-Type':'text/html; charset=utf-8'});
if(request.url!="/favicon.ico"){
otherfun.fun2(response);
otherfun.fun3(response);
response.end();
}
}).listen(8000);
console.log('Server running at http://127.0.0.1:8000/');
字串呼叫對應函式
上面程式碼大致不變,主要修改其中的呼叫語句。
funname = 'fun2'
otherfun[funname](response); //用字串呼叫對應的函式
將函式名傳給定義的變數,otherfun.fun2 和 otherfun['fun2'] 效果是一樣的,這樣的寫法更加常用。