您好,登錄后才能下訂單哦!
一、調(diào)用本js文件中的函數(shù)
var http = require('http'); http.createServer(function (request,response){ response.writeHead(200, {'Contet-Type':'text/html;charset=utf-8'}); if(request.url!=='/favicon.ico'){ funl(response); response.end(''); } }).listen(8000); console.log('Server running at http://127.0.0.1:8000/'); function funl(res){ console.log('fun1'); res.write('hello ,我是fun1'); }
運(yùn)行結(jié)果:
二、調(diào)用外部的js文件
function fun2(res){ console.log('我是,fun2'); res.write('你好我是fun2'); } // 想把此js聲明為一個(gè)函數(shù),加下面代碼,只適用于文件中只有一個(gè)函數(shù) module.exports = fun2; var http = require('http'); // ortherFun 就代替了fun2 var ortherFun = require('./../otherjs/out.js'); http.createServer(function (request,response){ response.writeHead(200, {'Contet-Type':'text/html;charset=utf-8'}); if(request.url!=='/favicon.ico'){ // funl(response); ortherFun(response); response.end(''); } }).listen(8000); console.log('Server running at http://127.0.0.1:8000/'); function funl(res){ console.log('fun1'); res.write('hello ,我是fun1'); }
外部js文件內(nèi)有多個(gè)函數(shù)
// 支持多個(gè)函數(shù) module.exports={ fun2:function(res){ console.log('我是fun2'); res.write('你好,我是fun2'); }, fun3:function(res){ console.log('我是fun3'); res.write('你好,我是fun3'); } } var http = require('http'); var ortherFun = require('./../otherjs/out.js'); http.createServer(function (request,response){ response.writeHead(200, {'Contet-Type':'text/html;charset=utf-8'}); if(request.url!=='/favicon.ico'){ // funl(response); // ortherFun(response); ortherFun.fun2(response); ortherFun.fun3(response); response.end(''); } }).listen(8000); console.log('Server running at http://127.0.0.1:8000/'); function funl(res){ console.log('fun1'); res.write('hello ,我是fun1'); }
用字符串調(diào)用對(duì)應(yīng)的函數(shù)
var http = require('http'); var ortherFun = require('./../otherjs/out.js'); http.createServer(function (request,response){ response.writeHead(200, {'Contet-Type':'text/html;charset=utf-8'}); if(request.url!=='/favicon.ico'){ // funl(response); // ortherFun(response); //ortherFun.fun2(response); //ortherFun.fun3(response); // 用字符串調(diào)用對(duì)應(yīng)的函數(shù) //ortherFun['fun2'](response); //ortherFun['fun3'](response); // 還可以寫成下面這樣 funname = 'fun2'; ortherFun[funname](response); response.end(''); } }).listen(8000); console.log('Server running at http://127.0.0.1:8000/'); function funl(res){ console.log('fun1'); res.write('hello ,我是fun1'); }
總結(jié)
以上所述是小編給大家介紹的nodejs中函數(shù)的調(diào)用實(shí)例詳解,希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)億速云網(wǎng)站的支持!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。