首先EditPlus編輯器,開啟新建的文字文件,另存為副本
呼叫函式分為呼叫本地函式,和其他檔案的函式
1、呼叫本地函式
var http = require('http');
http.createServer(function (request, response) {
response.writeHead(200, {'Content-Type': 'text/html; charset=utf-8'});
if(request.url!=="/favicon.ico"){ //清除第2此訪問 fun1(response); //呼叫函式 response.end('');
}
}).listen(8000);
console.log('Server running at http://127.0.0.1:8888/'); //本地函式
function fun1(res){ //res形參 是給客戶端傳輸響應資料的response
console.log("fun1");
res.write("hello,我是fun1");
}
2、呼叫其他函式
通過上面新建的文字文件 -再次另存為副本 建立n2_otherfuncall.js檔案
n2_funcall.js 中引用n2_otherfuncall.js檔案
var http = require('http');
var other = require('./n2_otherfuncall.js');
http.createServer(function (request, response) {
response.writeHead(200, {'Content-Type': 'text/html; charset=utf-8'});
if(request.url!=="/favicon.ico"){ //清除第2此訪問 //fun1(response); //呼叫函式 other(response);//呼叫其他函式 //呼叫多個函式的寫法
other.fun2(response);
other.fun3(response);
//或者
other['fun2'](response);
other['fun3'](response); response.end('');
}
}).listen(8888);
console.log('Server running at http://127.0.0.1:8888/');
n2_otherfuncall.js檔案
function fun2(res){
console.log("fun2");
res.write("你好,我是fun2");
}
//module.exports 物件是由模組系統建立的。
//在我們自己寫模組的時候,
//需要在模組最後寫好模組介面,
//宣告這個模組對外暴露什麼內容,
//module.exports 提供了暴露介面的方法
module.exports = fun2;//module.exports只支援一個函式 //下面是支援多個函式的寫法
module.exports = {
fun2:function(res){
console.log("我是fun2");
res.write("你好,我是fun2");
},
fun3:function(res){
console.log("我是fun3");
res.write("你好,我是fun3");
} }