获取路由(访问路径)
6_path.js代码:
var http = require(‘http‘); var url = require(‘url‘); var router = require(‘./6_router.js‘); http.createServer(function (request, response) { response.writeHead(200, {‘Content-Type‘: ‘text/html; charset=utf-8‘}); if(request.url!=="/favicon.ico"){ //清除第2此访问 var pathname = url.parse(request.url).pathname; console.log(pathname); pathname = pathname.replace(/\//, ‘‘);//替换掉前面的/ console.log(pathname); router[pathname](request,response); response.end(‘‘); } }).listen(8000); console.log(‘Server running at http://localhost:8000‘);
统计目录6_router.js代码:
module.exports={ login:function(req,res){ res.write("我是login方法"); }, register:function(req,res){ res.write("我是注册方法"); }, index:function(req,res){ res.write("我是index方法"); } }
读写文件
7_readFile.js代码:
var http = require(‘http‘); var optfile = require(‘./7_optfile.js‘); http.createServer(function (request, response) { response.writeHead(200, {‘Content-Type‘: ‘text/html; charset=utf-8‘}); if(request.url!=="/favicon.ico"){ //清除第2此访问 function closeResponse(res){ res.write(‘<br/>‘); res.end(‘完毕!‘); } console.log(‘访问‘); response.write(‘文件操作:‘); //异步读取文件 //optfile.readfile(response,"D:\\text.txt",function(){closeResponse(response);}); //同步读取文件 //optfile.readfileSync(response,"D:\\text.txt"); //closeResponse(response); //异步写文件 //optfile.writefile(response,"D:\\text.txt","bbbbbbbbbbbbbb",function(){closeResponse(response);}); //同步写文件 //optfile.writeFileSync(response,"D:\\text.txt","ccccccccccccccccccccccccc"); //closeResponse(response); } }).listen(8000); console.log(‘Server running at http://localhost:8000/‘);
统计目录7_optfile.js代码:
var fs= require(‘fs‘); module.exports={ readfile:function(res,path,callBack){ //异步执行 fs.readFile(path, function(err,data) { if(err){ res.write(err); }else{ res.write(data.toString()); } res.write("123"); callBack(); }); console.log("异步方法执行完毕"); }, readfileSync:function(res,path){ //同步读取 var data = fs.readFileSync(path,‘utf-8‘); res.write(data.toString()); console.log("同步方法执行完毕"); return data; },// appendFile 如果文件不存在,会自动创建新文件 // writeFile 会删除旧文件,直接写新文件 writefile:function(res,path,data,callBack){ //异步方式 fs.writeFile(path,data,function (err) { if(err){ res.write(err); }else{ res.write("写入文件【"+data+"】成功!"); } callBack(); }); }, writeFileSync:function(res,path,data){ //同步方式 fs.writeFileSync(path,data); res.write("写入文件【"+data+"】成功!"); } }