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

       

  • 相关阅读:
    这个 bug 让我更加理解 Spring 单例了
    SpringBoot
    codeblocks笔记
    https://docs.platformio.org/en/latest/boards/index.html
    外部存储的烧写
    嵌入式AI
    python的一些库
    语音芯片及解决方案
    神奇的调试值“DEADBEEF”
    【12月】+我与rt_thread的“江湖恩怨”
  • 原文地址:https://www.cnblogs.com/xingyue1988/p/8847293.html
Copyright © 2011-2022 走看看