Front-end song - Lesson 4 - event module of node's http module

Preface

I am GAYO. Follow the front-end GAYO on the WeChat public account and learn front-end knowledge together. Today I will continue to explain to you the explanation of events in node.

Case

const EventEmitter=require("events")

const event=new EventEmitter()

event.on("play",()=>{
    console.log("事件触发了")
})

event.emit("play")

operation result

Insert image description here

Case 1

var http=require("http")
var url=require("url")
var https=require("https")
const EventEmitter=require("events")
var event=null
http.createServer((req,res)=>{
     var urlobj=url.parse(req.url)
     res.writeHead(200,{
        "content-Type":"application/json;charset=utf-8",
        "access-control-allow-origin":"*"
     })
     switch(urlobj.pathname){
        case "/api/aaa":
            event=new EventEmitter()
            event.on("play",(data)=>{
                res.end(data)
            })
              httpget()
            break
        default:
            res.end("404")
     }
}).listen(3000)

function httpget(){
    var data=""
    https.get(`https://i.maoyan.com/api/mmdb/movie/v3/list/hot.json`,(res)=>{
        res.on("data",(chunk)=>{
           data+=chunk
        })
        res.on("end",()=>{
        //    console.log(data)
           event.emit("play",data)
        //    response.end(data)
        })
    })
}

operation result

Insert image description here

Supongo que te gusta

Origin blog.csdn.net/qq_41632427/article/details/134030183
Recomendado
Clasificación