Node study notes (c) - blocking, non-blocking event loop

Blocking code

// 导入文件模块
let fs=require('fs')
// 读取input.txt 文件中数据
let data=fs.readFileSync('input.txt')
console.log(data.toString())  // 先执行
console.log("程序结束") // 后执行

Non-blocking codes

let fs=require('fs')
fs.readFile('./input.txt',(err,data)=>{
    if(err) return console.log(err);
    console.log(data.toString()) // 后执行
})
console.log("程序结束") // 先执行

阻塞是按顺序执行的,而非阻塞是不需要按顺序的,如果需要处理回调函数的参数,我们就需要写在回调函数内

Event Loop

  • Node.jsEvent-driven model, when web serverreceiving the request, and then processed to put it off, and then next to a service webrequest.

  • In the event-driven model, will generate a main loop to monitor events, triggers a callback function when an event is detected.

    // 导入events模块
    let events=require('events');
    // 定义eventEmitter对象
    let eventEmitter=new events.EventEmitter();
    // 创建链接连接成功时触发的函数
    let connectHandler=function connected(){
        console.log('链接成功') // 第一步执行
        // 链接成功后才触发数据接收事件
        eventEmitter.emit('data_received')
    }
    // 绑定触发链接时执行函数
    eventEmitter.on('connection',connectHandler)
    // 创建数据接收成功后触发的函数
    eventEmitter.on('data_received',()=>{
        console.log('数据接收成功') // 第二步执行
    })
    // 触发链接事件
    eventEmitter.emit('connection');
    console.log("程序执行完毕")  // 第三步执行
    

EventEmitter class

  • eventsModule provides only one object: events.EventEmitter. EventEmitterThe core of the package is event-triggered and event listener function.
  • EventEmitterIf an error occurs when an object is instantiated, it will trigger erroran event. When adding a new listener, newListenerevent fires when the listener is removed, the removeListenerevent is triggered.
  • EventEmitterEach event consists of a name and an event consisting of several parameters, event name is a string that usually express certain semantics. For each event, EventEmitterit supports several event listener. When an event is triggered, registered to this event listeners in turn is invoked, the event parameters as callback parameter.
method
  1. addListener(event, listener)Tail add a listener for a specified event to listener array.

  2. on(event, listener)Register a listener for a specified event, accepts a string eventand a callback function.

    server.on('connection', function (stream) {
      console.log('someone connected!');
    });
    
  3. once(event, listener)Register a single listener for a specified event that will trigger a listener most immediately release the listener after the trigger.

    server.once('connection', function (stream) {
      console.log('Ah, we have our first user!');
    });
    
  4. removeListener(event, listener)Removal of a specified event listener, the listener must be an event has been registered listeners. It accepts two arguments, the first is the name of the event, the second is a callback function name.

    var callback = function(stream) {
      console.log('someone connected!');
    };
    server.on('connection', callback);
    // ...
    server.removeListener('connection', callback);
    
  5. removeAllListeners([event])Remove all listeners for all events, if a specified event, then remove all specified event listeners.

  6. setMaxListeners(n), EventEmittersIf you add listeners over 10 will output a warning message. setMaxListenersThe default function is used to increase the limit on the number of listeners.

  7. listeners(event)Returns the specified event listener arrays.

  8. emit(event, [arg1], [arg2], [...]), The order of execution of each listener listener, if there is an event listeners registered to return true, otherwise false.

Class Methods
  • listenerCount(emitter, event), Returns the specified number of events listener.

    events.emitter.listenerCount(eventName) //推荐
    
event
  1. newListenerThe first argument event- string, the event name, the second parameter listener- processing function event, the event is triggered when you add a new listener.

  2. removeListenerThe first argument event- string, the event name, the second parameter listener- processing event function, remove a listener from the specified listener array. It should be noted that this will change in the index that the listener after listener was deleted.

不会直接使用 EventEmitter,而是在对象中继承它。包括 fs、net、 http 在内的,只要是支持事件响应的核心模块都是 EventEmitter 的子类。

Examples
let events =require('events')
let eventEmitter=new events.EventEmitter()
let listener_first=function (){
    console.log("listener_first执行") // 第二步执行 || 第四步执行
}
let listener_second=function (){
    console.log("listener_second执行") // 第三步执行
}
eventEmitter.addListener('connection',listener_first)
eventEmitter.on('connection',listener_second)
let eventListeners=eventEmitter.listenerCount("connection")
console.log(eventListeners) // 第一步执行
eventEmitter.emit('connection')
eventEmitter.removeListener('connection',listener_second)
eventEmitter.emit('connection')
let eventListeners1=eventEmitter.listenerCount('connection')
console.log(eventListeners1) // 第五步执行
Published 122 original articles · won praise 6 · views 10000 +

Guess you like

Origin blog.csdn.net/weixin_44876003/article/details/104783187