NodeJs基础知识——函数调用

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');

三、调用外部多个函数

        在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

浏览器中显示如下:


控制台中显示如下:


  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值