调用当前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]
,这样可以实现动态调用函数。
运行结果: