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

       

  • 相关阅读:
    Retrofit2.0+OkHttp设置统一的请求头(request headers)
    Retrofit、Okhttp使用小记(cookie,accesstoken,POST
    quartz持久化部署实现
    支付宝支付-常用支付API详解(查询、退款、提现等)
    支付宝支付-提现到个人支付宝
    Git 版本还原命令
    CEF JS实现获取剪贴板图片的DataURL
    CEF 自定义用户协议(scheme)实现以二进制流的方式显示图片、视频、音频
    CEF C++调用前端js方法展示传递过来的图片数据
    C++读写图片数据转成Base64格式
  • 原文地址:https://www.cnblogs.com/xingyue1988/p/8847293.html
Copyright © 2020-2023  润新知