zoukankan      html  css  js  c++  java
  • 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);

    以上。

      

  • 相关阅读:
    Centos Another app is currently holding the yum lock
    Centos 重置密码
    Effective c#学习笔记(1)
    浅谈计算机编码
    mongodb java spring data
    VS2013 好用的插件
    xml存储bug
    VS 2008 生成操作中各个选项的差别
    程序权限控制
    给钛度产品的一些建议(Note)
  • 原文地址:https://www.cnblogs.com/jolee/p/5980368.html
Copyright © 2011-2022 走看看