Node.js入门(二)——调用函数方式小结

前言

nodejs调用函数主要是调用本js内部的函数,还有就是外部的函数,而调用外部函数主要的方式就是调用的函数开放可以让主函数调用,废话不说,下面开始详细讲解node.js的调用函数的具体使用。

内容

环境

  1. 下载node-v8.9.0-x64.msi
  2. 使用nodepad++,或者其他的文本编辑器
    测试node.js安装成功使用命令,出现node的版本号即安装成功

node -v

这里写图片描述

调用本地函数

var http=require("http");
http.createServer(function(request,response){
    response.writeHead(200,{'Content-Type':'text/html;charset=utf-8'});
    console.log('访问');
    response.write('hello world');
    if(request.url!="/favicon.ico"){ //清楚第二次访问
        fun(response);
        response.end();
    }

}).listen(8000)

console.log('server running at http://172.0.0.1:8000');

function fun(res){
    console.log('fun1');
    res.write("hello,我的是fun1");
}

调用外部js函数

  1. 其他js文件导出
module.exports={
    fun2:function(res){
        res.write("你好,我是fun2");
        },
    fun3:function(res){
        res.write("你好,我是fun3");
    }
}

2.主文件引入js文件,方式主要分为两种:字符串调用方式,方法名调用
字符串调用方式,这种方式主要用于外部方法名比较少的情况

var http=require("http");
var otherfun=require("./module/otherfun.js");//引入其他文件
http.createServer(function(request,response){
    response.writeHead(200,{'Content-Type':'text/html;charset=utf-8'});
    console.log('访问');
    response.write('hello world');
    if(request.url!="/favicon.ico"){ //清楚第二次访问
        //--------运用字符串调用对应的函数-----
        otherfun['fun2'](response);
        otherfun['fun3'](response);
        response.end();
    }

}).listen(8000)

console.log('server running at http://172.0.0.1:8000');

方法名调用,这种方法涉及路由的知识,路径传过来什么你就调用哪一种方法,提高了封装性,不需要知道外部js到底是什么内容

var http=require('http');
var url=require('url');
var route=require('./module/route');
http.createServer(function(request,response){
    response.writeHead(200,{'Content-Type':'text/html;charset=utf-8'});
    if(request.url!="/favicon.ico"){//清除第二次访问
        var pathname=url.parse(request.url).pathname;
        pathname=pathname.replace(/\//,''); //替换掉前面的/
        console.log(pathname);
        route[pathname](request,response);
        response.end('');
    }
}).listen(8000);

console.log("这个路由");

结语

刚刚接触,有什么好的建议请在我博客中留言,感谢诸位!

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 14
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 14
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值