Nodejs中調用函數的方式有多種,可以在內部調用普通函數,還可以調用外部單個函數以及調用外部多個函數等。普通內部函數可以直接調用,外部函數需要先使用module.exports=fun將函數導出,然后就可以直接調用了。
nodejs調用函數的方法如下:
一、內部調用普通函數
保存d2_function1.js,代碼如下:
var http = require('http'); http.createServer(function (req, res) { res.writeHead(200, {'Content-type':'text/html; charset=utf-8'}); if (req.url !== '/favicon.ico') { //調用普通內部函數 fun1(res); console.log('ok....'); } }).listen(3000); console.log('running localhost:3000'); //普通內部函數 function fun1(res) { res.write('test function....'); res.end(); }
二、調用外部單一函數
新建一個名為functions的文件夾,保存other_fun1.js,代碼如下:
function other_fun1(res) { res.write('this is other_fun1...'); res.end(); } //只能調用一個函數 module.exports = other_fun1;
保存d2_function2.js,代碼如下:
var http = require('http'); var other_fun1 = require('./functions/other_fun1');//引用外部文件 http.createServer(function (req, res) { res.writeHead(200, {'Content-type':'text/html; charset=utf-8'}); if (req.url !== '/favicon.ico') { //調用外部單個函數 other_fun1(res); console.log('ok....'); } }).listen(3000); console.log('running localhost:3000');
廣州品牌設計公司https://www.houdianzi.com PPT模板下載大全https://redbox.wode007.com
三、調用外部多個函數
在functions文件夾中保存other_fun2.js,代碼如下:
//導出多數函數供外部調用 module.exports = { fun1:function (res) { res.write('more functions..'); }, fun2:function (a, b) { var sum = a + b; return sum; } }
保存d2_function3.js,代碼如下:
var http = require('http'); //引入外部函數文件,調用多個函數 var o_func = require('./functions/other_fun2'); http.createServer(function (req, res) { if (req.url !== '/favicon.ico') { res.writeHead(200, {'Content-type':'text/html; charset=utf-8'}); console.log('ok...'); //調用函數1 o_func.fun1(res); //調用函數2 console.log(o_func.fun2(3, 9)); //另一種方式調用函數 o_func['fun1'](res); var fun_name = 'fun2'; console.log(o_func[fun_name](23, 9)); res.end(); } }).listen(3000); console.log('running localhost:3000'); cmd中運行 node d2_function3.js