zoukankan      html  css  js  c++  java
  • node.js调用函数

    首先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");
        }
    
    }

       

  • 相关阅读:
    九度OJ 1283 第一个只出现一次的字符
    九度OJ 1514 数值的整数次方【算法】
    九度OJ 1512 用两个栈实现队列 【数据结构】
    九度OJ 1513 二进制中1的个数
    九度OJ 1510 替换空格
    九度OJ 1511 从尾到头打印链表
    dom4J使用笔记
    XML的学习
    jaxp使用笔记
    json-lib使用笔记
  • 原文地址:https://www.cnblogs.com/xingyue1988/p/8847293.html
Copyright © 2011-2022 走看看