// 建立一个 test.js 文件,代码如下:
var http = require("http");
http.createServer(function(req, res) {
res.writeHead( 200 , {"Content-Type":"text/html;charset=utf-8"});
fun1(res);// hello, 我是fun1
}).listen(8000);
console.log("HTTP server is listening at port 8000.");
function fun1(res){
res.write('hello, 我是fun1');
}
引入外部文件
先建立一个fun2.js文件,代码为:
function fun2(res){
console.log('我是fun2');
res.write('hello, 我是fun2');
}
// 模块接口(但是只支持一个函数)
module.exports = fun2;
var http = require("http");
var xxx = require('./fun2.js');// 引入 fun2.js
http.createServer(function(req, res) {
res.writeHead( 200 , {"Content-Type":"text/html;charset=utf-8"});
if (req.url !== '/favicon.ico') {//清除第二次访问
xxx(res);// hello, 我是fun2
res.end();
}
}).listen(8000);
console.log("HTTP server is listening at port 8000.");
// 支持多个函数
module.exports = {
fun2 : function(res){
console.log('我是fun2');
res.write('hello, 我是fun2');
},
fun3 : function(res){
console.log('我是fun3');
res.write('hello, 我是fun3');
}
};
再次更改 test.js
var http = require("http");
var xxx = require('./fun2.js');// 引入 fun2.js
http.createServer(function(req, res) {
res.writeHead( 200 , {"Content-Type":"text/html;charset=utf-8"});
if (req.url !== '/favicon.ico') {//清除第二次访问
xxx.fun2(res);// hello, 我是fun2
xxx.fun3(res);// hello, 我是fun3 也可以这样写 xxx['fun3'](res);
res.end();
}
}).listen(8000);
console.log("HTTP server is listening at port 8000.");