nodejs如何调用函数?


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


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM