• Node.js—学习


    一、Node.js

    1. Hello World

    var  http  =  require('http');  
    http.createServer(function(request,  response)  {  
        response.writeHead(200,{'Content-Type':'text/html;charset=utf-8'});  
        if(request.url!=="/favicon.ico"){  //清除第2此访问  
            console.log('访问');  
            response.write('hello,world');  
            response.end('hell,世界');//不写则没有http协议尾,但写了会产生两次访问  
        }  
    }).listen(8000);  
    console.log('Server  running  at  http://127.0.0.1:8000/');  
      
    /*  
    启动服务  
    cmd下执行:  
    node  n1_hello.js  
    浏览器访问:http://localhost:8000  
    */                  
    

    2. 函数调用

    //---服务器node.js---
    var http = require('http');    
    var otherfun = require('./models/otherfuns.js');      
    http.createServer(function(request,response){      
    	response.writeHead(200,{'Content-Type':'text/html;charset=utf-8'});      
        if(request.url!=="/favicon.ico"){    //清除第2此访问  
            fun1(response);
    		otherfun.controller(request,response);  
            otherfun.call(response); 
            //---使用字符串调用对应的函数---
            funcname = "addContent"
            otherfun[funcname](response);
            otherfun['getVisit'](response);
            response.end('');    
        }  
    }).listen(8000);      
    console.log('Server running at http://127.0.0.1:8000/');    
    //---普通函数---      
    function  fun1(res){      
        res.write("你好,我是fun1");      
    }     
    
    //---/models/otherfuns.js---
    function  controller(req,res){      
        res.write("发送");      
        call('hello',req,res);      
        res.end("");      
    }      
    function  call(res){      
        console.log('call');      
    }      
    module.exports  =  controller;    //只支持一个函数     
    
    //只支持多个函数     
    module.exports={      
        getVisit:function(){      
        return  visitnum++;      
        },      
        addContent:function(a,b){      
        return  a+b;      
        }      
    }      
    

    3. 模块调用

    //---node.js---
    var http = require('http');    
    //var User = require('./models/User');
    var Teacher = require('./models/Teacher');
    http.createServer(function(request,response){        
    	response.writeHead(200,{'Content-Type':'text/html;charset=utf-8'});        
    	if(request.url!=="/favicon.ico"){        //清除第2此访问
            //实例化teacher对象
    		teacher  =  new  Teacher(1,'李四',30);
    		teacher.teach(response);
    		response.end('');    
    	}
    }).listen(8000);   
    
    //---User.js--
    function  User(id,name,age){
        this.id=id;
        this.name=name;
        this.age=age;
        this.enter=function(){
            console.log("进入图书馆");
        }
    }
    module.exports = User;
    
    //---models/Teacher.js---
    var User = require('./User');
    function Teacher(id,name,age){
        //没有构造方法,继承父类
    	User.apply(this,[id,name,age]);
        this.teach=function(res){
            res.write(this.name+"老师讲课");
        }
    }
    module.exports = Teacher;
    

    4. 路由

    //---node.js---
    var http = require('http');
    var url = require('url');
    var router = require('./router');
    http.createServer(function(request,response){
    	response.writeHead(200,{'Content-Type':'text/html;charset=utf-8'});
    	if(request.url!=="/favicon.ico"){
            //获取url的路径
            var pathname = url.parse(request.url).pathname;
            //替换掉路径前面的 /
            pathname = pathname.replace(///,'');
            router[pathname](request,response);
    		response.end('');
    	}
    }).listen(8000);
    
    //---router.js---
    module.exports={
    	login:function(req,res){
            res.write("我是login方法");
        },
        zhuce:function(req,res){
            res.write("我是注册方法");
        }
    }
    

    5. 文件读取

    //---node.js---
    var http = require("http");
    var optfile = require("./models/optfile");
    http.createServer(function(request,response){
        response.writeHead(200,{'Content-Type':'text/html';charset=utf-8'});
    	if(request.url!=="/favicon.ico"){
            //闭包函数;防止异步操作时,已经end了,再进行write报错
            function recall(data){
                response.write(data);
                response.end('ok')
            }
            optfile.readfile('./views/login.html',recall);
            console.log('主程序执行完毕');
        }
    }).listen(8000)
    
    //---/models/optfile---
    var fs = require('fs');
    module.exports={
        //同步读取
        readfileSync:function(path){
            var data = fs.readFileSync(path,'utf-8');
            console.log("同步方法执行完毕");
            return data;
        },
        //异步读取
        readfile:function(path,recall){
            fs.readFile(path,function(err,data){
                if(err){
                    console.log(err);
                }else{
                    console.log(data.toString());
                    recall(data);
                }
            })
        }
    }
    
    //---修改后路由---
    //---node.js---
    var http = require('http');
    var url = require('url');
    var router = require('./router');
    var optfile = require("./models/optfile");
    http.createServer(function(request,response){
        response.writeHead(200,{'Content-Type':'text/html';charset=utf-8'});
    	if(request.url!=="/favicon.ico"){
    		//获取url的路径
            var pathname = url.parse(request.url).pathname;
            //替换掉路径前面的 /
            pathname = pathname.replace(///,'');
            router[pathname](request,response);
            console.log('主程序执行完毕');
        }
    }).listen(8000)
    
    //---router.js---
    var optfile = require("./models/optfile");
    module.exports={
    	login:function(req,res){
            function recall(data){
    			res.write(data);
            	res.end("");
            }
    		optfile.readfile('./views/login.html',recall);
        },
        zhuce:function(req,res){
            function recall(data){
    			res.write(data);
            	res.end("");
            }
    		optfile.readfile('./views/zhuce.html',recall);
        }
    }
    

    6. 文件写入

    //---node.js---
    var http = require('http');
    var url = require('url');
    var router = require('./router');
    var optfile = require("./models/optfile");
    http.createServer(function(request,response){
        response.writeHead(200,{'Content-Type':'text/html';charset=utf-8'});
    	if(request.url!=="/favicon.ico"){
    		//获取url的路径
            var pathname = url.parse(request.url).pathname;
            //替换掉路径前面的 /
            pathname = pathname.replace(///,'');
            router[pathname](request,response);
            console.log('主程序执行完毕');
        }
    }).listen(8000)
    
    //---/models/optfile---
    var fs = require('fs');
    module.exports={
        //同步写入
        writefileSync:function(path,data){
            fs.writeFileSync(path,data);
            console.log("同步方法执行完毕");
        },
        //异步读取
        writefile:function(path,data,recall){
            fs.writeFile(path,data,function(err){
                if(err){
                    throw err;
                }else{
    				console.log("It is saved!");
                    recall('写文件成功')
                }
            })
        }
    }
    
    //---router.js---
    var optfile = require("./models/optfile");
    module.exports={
    	login:function(req,res){
            function recall(data){
    			res.write(data);
            	res.end("");
            }
    		optfile.readfile('./views/login.html');
        },
        writefile:function(req,res){
            function recall(data){
    			res.write(data);
            	res.end("");
            }
    		optfile.writefile('./views/one.txt','hello world',recall);
        }
    }
    

    7. 读取图片

    //---node.js---
    var http = requrie('http');
    var optfile = require('./models/optfile');
    http.createServer(function(request,response){
        //读取图片需要时二进制流格式
        response.writeHead(200,{'Content-Type':'image/jpeg'});
        if(request.url!='/favicon.ico'){
            optfile.readImg('./imgs/pig.png',response);
        }
    }).listen(8000);
    
    //---/models/optfile---
    var fs = require('fs');
    module.exports={
        readImg:function(path,res){
            //默认为string,binary是二进制
            fs.readFile(path,'binary',function(err,filedata){
                if(err){
                    console.log(err);
                    return;
                }else{
                    res.write(filedata,'binary');
                    res.end();
                }
            })
        }
    }
    

    8. 异常处理

    //同步捕获异常
    pathname = url.parse(request.url).pathname;
    pathname = pathname.replace(///,'');
    try{
        router[pathname](request,response);
    }catch(err){
        console.log("error="+err);
        response.writeHead(200,{'Content-Type':'text/html';charset='utf-8'});
        response.write(err.toString());
        response.end('');
    }
    
    //---node.js---
    var http = require('http');                                        
    var url = require('url');        
    var router = require('./router');    
    var exception = require('./models/Exception');
    http.createServer(function  (request,response){                                        
    	if(request.url!=="/favicon.ico"){//清除第2此访问                
    		pathname=url.parse(request.url).pathname;        
    		pathname = pathname.replace(///,'');//替换掉前面的/        
    		try{        
    		//router[pathname](request,response);    
    			data  =  exception.expfun(0);
    			response.write(data);
    			response.end('');
    		}catch(err){        
    			console.log('aaaaa='+err);    
    			response.writeHead(200,{'Content-Type':'text/html;charset=utf-8'});        
    			response.write(err.toString());        
    			response.end('');
    		}
    		console.log("server执行完毕");
    	}
    }).listen(8000);                                        
    
    //---Exception.js---
    module.exports={      
        expfun:function(flag){      
            if(flag==0){      
                //抛出异常
                throw  '我是例外';      
            }      
            return  "success";      
        }      
    }
    

    9. 参数接收

    <form action='./login' method='get'>
        <input type='text' name='email'/>
        <input type='password' name='pwd'/>
        <input type='submit' value='登录'>
    </form>
    
    //---node.js---
    var http = require('http');                          
    var url = require('url');          
    var router = require('./router');        
    http.createServer(function(request,response){                          
    	if(request.url!=="/favicon.ico"){                //清除第2此访问              
    		pathname=url.parse(request.url).pathname;          
    		pathname = pathname.replace(///,'');//替换掉前面的/          
    		try{          
    			router[pathname](request,response);      
    		}catch(err){          
    			console.log('出错='+err);        
    			response.writeHead(200,{'Content-Type':'text/html;charset=utf-8'});          
    			response.write(err);          
    			response.end('');      
    		}      
    		console.log("server执行完毕");      
    	}                          
    }).listen(8000);                                    
    
    //---router.js--
    var  optfile  =  require('./models/optfile');    
    var  url  =  require('url');    
    var  querystring  =  require('querystring');  //post需导入    
    module.exports={      
    	login:function(req,res){      
            //--------get方式接收参数----------------           
            var rdata = url.parse(req.url,true).query;      
    		console.log(rdata);    
            if(rdata['email']!=undefined){  
    			console.log(rdata['email']);      
                                    }     
            
            //-------post方式接收参数----------------      
    		var  post  =  '';//定义了一个post变量,用于暂存请求体的信息   
            //通过req的data事件监听函数,每当接受到请求体的数据,就累加到post变量中      
    		req.on('data',  function(chunk){
                post  +=  chunk;      
            });      
            
            //-------注意异步-------------  
    		//在end事件触发后,通过querystring.parse将post解析为真正的POST请求格式,然后向客户端返回。 
            req.on('end',  function(){ 
                post  =  querystring.parse(post);      
                console.log('email:'+post['email']+'
    ');        
    			console.log('pwd:'+post['pwd']+'
    ');
            });      
            //---------------------------------------      
            data  =  optfile.readfileSync('./views/login.html');      
            res.write(data);      
            res.end();      
        }      
    }
    
    
  • 相关阅读:
    perl shell交换示例
    python语法测试
    python使用带汉字的正则表达式
    【zz】Perl数字与字符串间的自动转换
    python完成文件按行拆分按列重组。
    转载 python每次读入文件一行的问题(血的教训啊)
    工程总结
    perl 语言学习——从C/C++到perl
    perl双层哈希求长度
    visual studio 代码分析利器 FxCop
  • 原文地址:https://www.cnblogs.com/hq82/p/10841421.html
Copyright © 2020-2023  润新知