node.js学习第二天

node.js调用函数

调用当前页面的函数

var http = require("http");
http.createServer(function(request,response){
    response.wireHead("Content-Type":"text/html;charset=utf-8");
     if(request.url!=='/favicon.ico'){
         fun1(response);
        response.end('');
    }
}).listen(8000);

console.log("server running http://127.0.0.1:8000");

funtion fun1(res){
 console.log("fun1");
  res.write("hello,fun1");
}

调用本地js文件(fun2.js)中的函数

只有一个函数

1 funtion fun2(res){
2    res.write("hello,fun2");
3    console.log("fun2");
4 }
5 //该函数想要被调用 需引入
6 module.exports=fun2;//只支持一个函数
View Code

调用函数的页面

 1 //引入js文件
 2 var otherfun=require(./fun2.js);
 3 var http = require("http");
 4 http.createServer(function(request,response){
 5     response.writeHead(200,{"Content-Type":"text/html;charset=utf-8"});
 6     if(request.url!=='/favicon.ico'){
 7     
 8 //调取本地js文件的函数
 9     otherfun(response);
10          response.end("");
11     }
12 }).listen(8000);
13 console.log("server running at http://127.0.0.1:8000/");

多个函数的fun2.js的写法

module.exports={
    fun2:function(res){
       console.log("fun2");
       res.write("hello,fun2");
    },
    fun3:function(res){
        console.log("fun3");
        res.write("hello,fun3");
    }
}

调用的时候

otherfun.fun2(response);

或者用字符串调用对应的函数即 otherfun['fun2'](response);

 

以上。

  

posted @ 2016-10-20 12:11  jolee  阅读(123)  评论(0编辑  收藏  举报