Node.js学习 - Event Loop
Node.js本身是单线程,但通过事件和回调支持并发,所以性能非常高。
Node.js的每一个API都是异步的,并作为一个独立线程运行,使用异步函数调用,并处理并发。
事件驱动程序
实例
var events = require('events'); var eventEmitter = new events.EventEmitter(); var eventHandler = function connected() { console.log('Connected successful!'); eventEmitter.emit('data_received'); #3 处理事件,触发'data_received'事件 }; eventEmitter.on('connection', eventHandler); #2 监听到'connection'事件,交给eventHandler处理事件 eventEmitter.on('data_received', function () { #4 监听到'data_received'事件,并处理事件 console.log("Received data successful!"); }); eventEmitter.emit('connection'); #1 触发'connection'事件, console.log('Program stop.');
KEEP LEARNING!