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浜嬩欢瑙﹀彂鏈哄埗的主要内容,如果未能解决你的问题,请参考以下文章