<强>一、调用本js文件中的函数强>
var http=要求(“http”); http。createServer(函数(请求、响应){ 响应。writeHead(200年,{“Contet-Type”:“text/html; charset=utf - 8 '}); 如果(request.url !=='/ico的位于){ funl(响应); response.end ("); } }).listen (8000); 控制台。日志(服务器运行在http://127.0.0.1:8000); 函数funl (res) { console.log (“fun1”); res.write(“你好,我是fun1 '); }
运行结果:
<强>二、调用外部的js文件强>
函数fun2 (res) { console.log(“我是fun2”); res.write(“你好我是fun2 '); }//想把此js声明为一个函数,加下面代码,只适用于文件中只有一个函数 模块。出口=fun2; var http=要求(“http”);//ortherFun就代替了fun2 var ortherFun=要求(“/. ./otherjs/out.js。”); http。createServer(函数(请求、响应){ 响应。writeHead(200年,{“Contet-Type”:“text/html; charset=utf - 8 '}); 如果(request.url !=='/ico的位于){//funl(响应); ortherFun(响应); response.end ("); } }).listen (8000); 控制台。日志(服务器运行在http://127.0.0.1:8000); 函数funl (res) { console.log (“fun1”); res.write(“你好,我是fun1 '); }
外部js文件内有多个函数
//支持多个函数 module.exports={ fun2:函数(res) { console.log(“我是fun2 '); res.write('你的好,我是fun2”); }, fun3:函数(res) { console.log(“我是fun3 '); res.write('你的好,我是fun3”); } } var http=要求(“http”); var ortherFun=要求(“/. ./otherjs/out.js。”); http。createServer(函数(请求、响应){ 响应。writeHead(200年,{“Contet-Type”:“text/html; charset=utf - 8 '}); 如果(request.url !=='/ico的位于){//funl(响应);//ortherFun(响应); ortherFun.fun2(响应); ortherFun.fun3(响应); response.end ("); } }).listen (8000); 控制台。日志(服务器运行在http://127.0.0.1:8000); 函数funl (res) { console.log (“fun1”); res.write(“你好,我是fun1 '); }
用字符串调用对应的函数
var http=要求(“http”); var ortherFun=要求(“/. ./otherjs/out.js。”); http。createServer(函数(请求、响应){ 响应。writeHead(200年,{“Contet-Type”:“text/html; charset=utf - 8 '}); 如果(request.url !=='/ico的位于){//funl(响应);//ortherFun(响应);//ortherFun.fun2(响应);//ortherFun.fun3(响应);//用字符串调用对应的函数//ortherFun [' fun2 '](响应);//ortherFun [' fun3 '](响应);//还可以写成下面这样 funname=癴un2”; ortherFun [funname](响应); response.end ("); } }).listen (8000); 控制台。日志(服务器运行在http://127.0.0.1:8000); 函数funl (res) { console.log (“fun1”); res.write(“你好,我是fun1 '); }
以上所述是小编给大家介绍的nodejs中函数的调用实例详解,希望对大家有所帮助,如果大家有任何疑问请给我留的言,小编会及时回复大家的。在此也非常感谢大家对网站的支持!