————(2)调用多个函数———–
主程序中:
var http = require('http');
var otherfun = require("./models/otherfuns.js");//调用写函数的外部页面otherfuns.js
http.createServer(function (request, response) {
response.writeHead(200, {'Content-Type': 'text/html;chaset=utf-8;'});
if(request.url!=='/favicon.ico'){
//todo 以对象.方法名调用
otherfun.fun2(response);
otherfun.fun3(response);
//todo 以字符串调用对应函数(结果同上)
//otherfun['fun2'](response);
//otherfun['fun3'](response);
response.end('');
}
}).listen(8000);
// 终端打印如下信息
console.log('Server running at http://127.0.0.1:8000/');
}
otherfuns.js中
module.exports={
fun2:function(res){//匿名函数
console.log('fun2');
res.write('你好!,我是fun2');//在页面中输出
},
fun3:function(res){
console.log('fun3');
res.write('你好!,我是fun3');
},
......
}
四、nodejs路由初步
主程序n4_rout.js:
var http = require('http');
//引入url模块
var url = require('url');
http.createServer(function (request, response) {
response.writeHead(200, {'Content-Type': 'text/html;chaset=utf-8;'});
if(request.url!=='/favicon.ico'){
var pathname = url.parse(request.url).pathname;
pathname=pathname.replace(///,'');//替换掉前面的/
console.log(pathname);
response.end('');
}
}).listen(8000);
// 终端打印如下信息
console.log('Server running at http://127.0.0.1:8000/');在命令行cmd中执行该文件,在访问:http://localhost:8000/,在此输入路由地址,如下图,并观察命令行。

五、nodejs读取文件
主程序:
var http = require('http');
var optfile=require('./models/optfile');//导入文件
http.createServer(function (request, response) {
// 发送 HTTP 头部
// HTTP 状态值: 200 : OK
// 内容类型: text/html
response.writeHead(200, {'Content-Type': 'text/html;chaset=utf-8;'});
if(request.url!=='/favicon.ico'){//清除第2次访问
optfile.readfileSync('./views/login.html');//同步调用读取文件readfileSync()方法
//optfile.readfile('./views/login.html',response);//异步步调用读取文件readfile()方法
response.end('ok!!!!!');//todo 不写没有协议尾
console.log('主程序执行完毕!');









