前言
我是歌谣 微信公众号关注前端小歌谣一起学习前端知识 今天继续给大家讲解node中event的讲解
案例
const EventEmitter=require("events")
const event=new EventEmitter()
event.on("play",()=>{
console.log("事件触发了")
})
event.emit("play")
运行结果
案例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)
})
})
}