EventEmitter锛歯odeJs浜嬩欢瑙﹀彂鏈哄埗

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了EventEmitter锛歯odeJs浜嬩欢瑙﹀彂鏈哄埗相关的知识,希望对你有一定的参考价值。

鏍囩锛?a href='http://www.mamicode.com/so/1/time' title='time'>time   姝f槸   浣跨敤   app   prot   娣诲姞   message   out   璇锋眰   

Node.js 鎵€鏈夌殑寮傛 I/O 鎿嶄綔鍦ㄥ畬鎴愭椂閮戒細鍙戦€佷竴涓簨浠跺埌浜嬩欢闃熷垪

Node.js 閲岄潰鐨勮澶氬璞¢兘浼氬垎鍙戜簨浠讹細涓€涓?net.Server 瀵硅薄浼氬湪姣忔鏈夋柊杩炴帴鏃惰Е鍙戜竴涓簨浠讹紝 涓€涓?fs.readStream 瀵硅薄浼氬湪鏂囦欢琚墦寮€鐨勬椂鍊欒Е鍙戜竴涓簨浠躲€?鎵€鏈夎繖浜涗骇鐢熶簨浠剁殑瀵硅薄閮芥槸 events.EventEmitter 鐨勫疄渚?/p>

NodeJs浜嬩欢鐩戝惉瑙﹀彂鏈哄埗渚濊禆 events 鏍稿績妯″潡锛?/em>

events 妯″潡鍙彁渚涗簡涓€涓璞★細 events.EventEmitter銆侲ventEmitter 鐨勬牳蹇冨氨鏄簨浠惰Е鍙戜笌浜嬩欢鐩戝惉鍣ㄥ姛鑳界殑灏佽

鎴戜滑鏉ョ湅鐪嬪畠鐨勫熀鏈敤娉?/em>

const EventEmitter = require(鈥榚vents鈥?span style="color: #000000">).EventEmitter
//瀹炰緥鍖朎ventEmitter绫?/span>
const event = new EventEmitter()

//error鏄壒娈婁簨浠讹紝绯荤粺鑷姩瑙﹀彂锛屽鏋滅▼搴忔病鏈夎缃洃鍚櫒鐨勮瘽锛岀郴缁熼亣鍒伴敊璇細鎶涘嚭锛岀粓姝唬鐮佽繍琛?/span>
event.on(鈥榚rror鈥? err => {
    console.log(err)
})
//娣诲姞浜嬩欢鐩戝惉
event.on(鈥榠nit鈥? () => {
    console.log(`鍒濆鍖?..`)
})

//鍙互缁欎竴涓簨浠惰璁剧疆澶氫釜鐩戝惉鍣?/span>
event.on(鈥榙ata鈥?span style="color: #000000">, reciveData)
event.on(鈥榙ata鈥?span style="color: #000000">, processData)

//榛樿鏈€澶氫负涓€涓簨浠惰缃?0涓洃鍚櫒锛屽彲浠ラ€氳繃浠ヤ笅鏂规硶淇敼
// event.setMaxListeners(11)

event.on(鈥榗lose鈥? () => {
    console.log(`缁撴潫..`)
})

//绉婚櫎鐩戝惉鍣?/span>
event.removeListener(鈥榙ata鈥?span style="color: #000000">,reciveData)

function reciveData(data){
    console.log(`鏀跺埌鏁版嵁: ${data}`)
}
function processData(data){
    console.log(`澶勭悊鏁版嵁: ${data}`)
}

event.emit(鈥榠nit鈥?span style="color: #000000">)

setTimeout(()=>{
    //瑙﹀彂浜嬩欢锛屽鏋滀簨浠舵病琚洃鍚繑鍥?false
    event.emit(鈥榙ata鈥?鈥楢BCDEFG鈥?span style="color: #000000">)
},1000)
setTimeout(()=>{
    //瑙﹀彂浜嬩欢
    event.emit(鈥榗lose鈥?span style="color: #000000">)
},2000)

浠ヤ笂浠g爜浠嬬粛浜唀ventEmitter鐨勫叏閮ㄧ敤娉曪紝鍙兘鎴戜滑浼氶棶杩欎釜eventEmitter鏈変粈涔堝嵉鐢ㄥ悧锛?/p>

澶у鏁版椂鍊欐垜浠笉浼氱洿鎺ヤ娇鐢?EventEmitter锛岃€屾槸鍦ㄥ璞′腑缁ф壙瀹?/p>

渚嬪鎴戜滑甯哥敤鐨勬柟娉?http.get 鏂规硶锛岃鏂规硶浼犲叆涓や釜鍙傛暟

鍙傛暟1锛氶渶瑕佽姹倁rl

鍙傛暟2锛歨ttp.IncomingMessage瀹炰緥锛岃€岃繖涓璞℃鏄户鎵?eventEmitter 瀵硅薄

涓嬮潰浠g爜澶ф妯℃嫙浜嗕簡http.get宸ヤ綔鍘熺悊

const EventEmitter = require(鈥榚vents鈥?span style="color: #000000">).EventEmitter
var myHttp = {}
myHttp.incomingMessage = function(statusCode, headers){
    this.statusCode = statusCode
    this.headers = headers
}
myHttp.incomingMessage.prototype = new EventEmitter()

myHttp.get = function(url, fn){
    //浼唬鐮侊細鑾峰彇url鍐呭
    var im = new this.incomingMessage(200,{鈥榗ontent-type鈥? 鈥榡son/application鈥?span style="color: #000000">})
    fn(im)
    im.emit(鈥榙ata鈥?span style="color: #000000">,`鏉ヨ嚜${url}鐨勬暟鎹甡)
}

module.exports = myHttp

浣跨敤

const myHttp = require(鈥?/event.js鈥?span style="color: #000000">)

myHttp.get(鈥榟ttp://www.baidu.com鈥? res => {
    console.log(res)
    res.on(鈥榙ata鈥? data => {
        console.log(data)
    })
})

 

以上是关于EventEmitter锛歯odeJs浜嬩欢瑙﹀彂鏈哄埗的主要内容,如果未能解决你的问题,请参考以下文章

浜嬩欢鐨勫啋娉″拰榛樿琛屼负

.net寰俊鍏紬鍙峰紑鍙戔€斺€旀秷鎭笌浜嬩欢

AWR涓殑涓昏浜嬩欢鍒嗘瀽绮捐

Android 寮€婧愭鏋?( 涓?) 浜嬩欢鎬荤嚎---EventBus

Android 鑷畾涔塋istView鍗曞嚮浜嬩欢澶辨晥