nodejs调用函数和模块

内部函数调用: 

//导入http
var http=require('http');
//导入模块函数

//创建
http.createServer(function (request,response) {
    response.writeHead(200,{'Content-type':'text/html;charset=utf-8'});
    if(request.url!=='/favicon.ico'){//清除二次访问
        func1(response);
        
        response.end("世界");//不写会没有协议尾部,但是写了会访问俩次
    }
}).listen(8000);
console.log('Server running at http://127.0.0.11:8000/')

//函数
function func1(res) {
    console.log(func1)
    res.write("hello,我是func1");
}

 外部模块调用:

fun2.js(单个外部函数调用)

function unc2(res) {
    console.log('我是func2');
    res.write('hello,我是func2');
    res.end("");
}
//外部引用
module.exports = unc2;//只支持一个函数
//导入http
var http=require('http');
//导入模块函数
var func2=require('../module/fun2.js');

//创建
http.createServer(function (request,response) {
    response.writeHead(200,{'Content-type':'text/html;charset=utf-8'});
    if(request.url!=='/favicon.ico'){//清除二次访问
      
        //调用外部函数
        func2(response);
        
    }
}).listen(8000);
console.log('Server running at http://127.0.0.11:8000/')

多个函数一起调用:

morefun.js

//支持多个函数
module.exports={
    htt:function(res){
        console.log("htt");
        res.write("htt");
    },
    juju:function(res){
        console.log("juju");
        res.write("juju");
    },
    lulu:function(res){
        console.log("lulu");
        res.write("lulu");
    },
}
//导入http
var http=require('http');
//导入模块函数
var morefun=require('../module/morefun.js');
//创建
http.createServer(function (request,response) {
    response.writeHead(200,{'Content-type':'text/html;charset=utf-8'});
    if(request.url!=='/favicon.ico'){//清除二次访问
        
        funcname='htt';
        morefun[funcname](response);
        morefun['juju'](response);
        morefun['lulu'](response);
        response.end("世界");//不写会没有协议尾部,但是写了会访问俩次
    }
}).listen(8000);
console.log('Server running at http://127.0.0.11:8000/')

效果:

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值