第一种调用js内部的函数:
var http = require('http');//node.js自带http服务
http.createServer(function(req, res){
res.writeHead(200, {'Content-Type': 'text/plain; charset=utf-8'});
if(req.url != '/favicon.ico'){//清除掉,防止第二次访问
console.log("访问");
fun1(res);//调用内部函数
res.end('');//结束请求,不写则没有结束
}
}).listen(8090);//端口
console.log('服务器已启动... http://localhost:8090/');
function fun1(res){
res.write("我是内部js里面的函数,fun1");
}
运新程序访问
第二种调用外部js里面的函数:
1.调用单个函数:
外部otherfun.js
function fun2(res){
res.write("我是外部js里面的函数,fun2");
}
module.exports = fun2;//支持单个函数
funcall.js
var http = require('http');//node.js自带http服务
var otherFun = require("./otherfun.js");
http.createServer(function(req, res){
res.writeHead(200, {'Content-Type': 'text/plain; charset=utf-8'});
if(req.url != '/favicon.ico'){//清除掉,防止第二次访问
console.log("访问");
otherFun(res);//调用外部函数
res.end('');//结束请求,不写则没有结束
}
}).listen(8090);//端口
console.log('服务器已启动... http://localhost:8090/');
运行访问结果
2.调用多个函数:
外部otherfun.js
module.exports ={
fun2:function(res){
res.write("我是外部js里面的函数,fun2");
},
fun3:function(res){
res.write("我是外部js里面的函数,fun3");
},
fun4:function(res){
res.write("我是外部js里面的函数,fun4");
}
}
funcall.js
var http = require('http');//node.js自带http服务
var otherFun = require("./otherfun.js");
http.createServer(function(req, res){
res.writeHead(200, {'Content-Type': 'text/plain; charset=utf-8'});
if(req.url != '/favicon.ico'){//清除掉,防止第二次访问
console.log("访问");
//otherFun.fun2(res);//调用外部函数
//otherFun.fun3(res);//调用外部函数
//otherFun.fun4(res);//调用外部函数
//或者用下面这种方式
otherFun["fun2"](res);
otherFun["fun3"](res);
otherFun["fun4"](res);
res.end('');//结束请求,不写则没有结束
}
}).listen(8090);//端口
console.log('服务器已启动... http://localhost:8090/');
运行结果