Node.js调用函数

调用当前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"){
        res.write('<h1>Node.js</h1>');
        console.log("running...");
        fun1(res);
        res.end('<p>Hello World!!</p>');
    }

}).listen(3000);

console.log("HTTP server is listening at port 3000.");


function fun1(res){
    console.log("fun1");
    res.write("hello,我是fun1");
}

我们在当前js脚本内写了一个fun1()函数,并在当前脚本中调用了。运行如下:
这里写图片描述
这里写图片描述

在另一个js文件的函数

在当前js文件目录下,新建一个文件夹,在新建一个js文件
这里写图片描述
otherfun.js里面加入新方法。

function fun2(res){
    console.log("fun2");
    res.write("hello,我是fun2");
}

module.exports = fun2;  //只支持一个函数

在js文件中调用另一个js文件的函数:

var http = require('http');
var otherfun = require("./module/otherfun.js");

http.createServer(function(req,res){
    res.writeHead(200,{'Content-Type' : 'text/html; charset=utf-8'});
    if(req.url !== "/favicon.ico"){
        res.write('<h1>Node.js</h1>');
        console.log("running...");
        otherfun(res);//调用函数
        res.end('<p>Hello World!!</p>');
    }

}).listen(3000);

console.log("HTTP server is listening at port 3000.");

运行结果:
这里写图片描述
这里写图片描述
调用另一个js文件中的函数,需要使用module.exports = fun,例如上面的中的module.exports = fun2;但这种方法只支持一个函数。
下面这种方法可以支持多个函数:
otherfun.js

//支持多个函数
module.exports = {

    fun2 : function(res){
        console.log("fun2");
        res.write("hello,我是fun2");
    },
    fun3 : function(res){
        console.log("fun3");
        res.write("hello,我是fun3");
    }
}
var http = require('http');
var otherfun = require("./module/otherfun.js");

http.createServer(function(req,res){
    res.writeHead(200,{'Content-Type' : 'text/html; charset=utf-8'});
    if(req.url !== "/favicon.ico"){
        res.write('<h1>Node.js</h1>');
        console.log("running...");
        otherfun.fun2(res);//利用otherfun变量去调用函数
        otherfun.fun3(res);
        res.end('<p>Hello World!!</p>');
    }

}).listen(3000);

console.log("HTTP server is listening at port 3000.");

另一种调用方式:

var http = require('http');
var otherfun = require("./module/otherfun.js");

http.createServer(function(req,res){
    res.writeHead(200,{'Content-Type' : 'text/html; charset=utf-8'});
    if(req.url !== "/favicon.ico"){
        res.write('<h1>Node.js</h1>');
        console.log("running...");
        otherfun['fun2'](res);
        otherfun['fun3'](res);
        res.end('<p>Hello World!!</p>');
    }

}).listen(3000);

console.log("HTTP server is listening at port 3000.");

这种方法可以把调用的方法名作为变量functionName,传入otherfun[functionName],这样可以实现动态调用函数。

运行结果:
这里写图片描述
这里写图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值