nodejs学习笔记三 调用函数

来源:互联网 发布:武术机器人 算法 编辑:程序博客网 时间:2024/06/17 14:57

一、调用本地函数

      调用本地的函数可以直接写一个函数,然后直接调用就行了,和其他语言类似。

     

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此访问          function1(response);        response.end('hell,世界');//不写则没有http协议尾,但写了会产生两次访问      }  }).listen(8080);  console.log('Server  running  at  http://127.0.0.1:8080/');  function function1(res){      console.log('我是function1');        res.write('我是function1');    }

 



二、调用外部函数

可以再文件中写入多个函数:

第一种方式调用:

a.js

var  http  =  require('http');  var    otherfun    =    require('./modue.js');  http.createServer(function  (request,  response)  {      response.writeHead(200,  {'Content-Type':  'text/html;  charset=utf-8'});      if(request.url!=="/favicon.ico"){  //清除第2此访问  otherfun.function2(response);otherfun.function3(response);        response.end('hell,世界');//不写则没有http协议尾,但写了会产生两次访问      }  }).listen(8080);  console.log('Server  running  at  http://127.0.0.1:8080/');  


modue.js

module.exports={    function2:function(res){        console.log("我是function2");        res.write("我是function2");    },    function3:function(res){        console.log("我是function3");        res.write("我是function3");    }}


第二种方调用函数:

var functionname="function2";      定义一个字符串类型,存放函数的名称,

otherfun[functionname](response);      再通过字符串调用这个,函数,以后会经常用到


原创粉丝点击