首页 > 技术文章 > node的function函数和路由代码的小例子

dreamtown 2020-07-17 10:32 原文

1、node事件循环

事件:

const events=require("events");
emt=new events.EventEmitter();

function eventHandler(){
    console.log("111");
    console.log("222")
}
emt.on("eventName",eventHandler);
emt.emit("eventName");

2、模块自定义

function show(){
    this.name='user1';
    this.say=function(){
        console.log("my name is "+this.name);
    }

}
module.exports=new show();

3、function函数,分为常用函数和匿名函数

1)、常用函数,如

         Function show(){

      Console.log(“123”);

}

2)、匿名函数,如

         Show=function(){

     Console.log(“123”);

}

Show();

4、node路由

代码示例如下:

const http=require("http");
const url=require("url");

cs=function(req,res){
    ur=req.url;
    if(ur!=="/favicon.ico"){
        //arr=url.parse(ur);
        //路由
        path=url.parse(ur).pathname;
        switch(path){
            case "/user/add":
                res.write("<h1>use add</h1>");
                break;
            case "/user/delete":
                res.write("<h1>use delete</h1>");
                break;
            case "/user/select":
                res.write("<h1>use select</h1>");
                break;
            default:
                res.write("<h1>hello~</h1>")    
        }
    }
    //console.log(arr);
    res.write("hello world");
    res.end();

}

http.createServer(cs).listen(888);
console.log("server is ok");

 

推荐阅读