前言
nodejs调用函数主要是调用本js内部的函数,还有就是外部的函数,而调用外部函数主要的方式就是调用的函数开放可以让主函数调用,废话不说,下面开始详细讲解node.js的调用函数的具体使用。
内容
环境
- 下载node-v8.9.0-x64.msi
- 使用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函数
- 其他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("这个路由");
结语
刚刚接触,有什么好的建议请在我博客中留言,感谢诸位!