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

    以上。

      

  • 相关阅读:
    [原]将工程由VC6迁移到VS2005
    [原]DirectDraw视频播放要点
    [原]代码优化学习笔记
    [原]Linux文件交换
    [原]计划
    [原]写在2006年的最后一天
    [原]技术发展规划
    FindBugs的安装和使用
    VirtualBox常用命令
    eclipse中统计代码行数
  • 原文地址:https://www.cnblogs.com/jolee/p/5980368.html
Copyright © 2020-2023  润新知