Node JS是單線程應(yīng)用程序,但它通過事件和回調(diào)概念,支持并發(fā)。 由于Node JS每一個API是異步的,作為一個單獨的線程,它使用異步函數(shù)調(diào)用,以保持并發(fā)性。Node JS使用觀察者模式。Node線程保持一個事件循環(huán),每當任何任務(wù)得到完成,它觸發(fā)這標志著該事件偵聽器函數(shù)執(zhí)行相應(yīng)的事件。
Node.js大量使用事件,這也是為何Node.js是相當快相對于其他類似的技術(shù)。當Node啟動其服務(wù)器,它可以簡單地啟動它的變量,聲明的函數(shù),然后簡單地等待發(fā)生的事件。
在事件驅(qū)動的應(yīng)用中,通常主循環(huán)監(jiān)聽事件,然后觸發(fā)回調(diào)函數(shù)時被檢測到這些事件之一。
盡管事件似乎類似于回調(diào)。不同之處在于如下事實,當異步函數(shù)返回其結(jié)果的回調(diào)函數(shù)被調(diào)用的地方作為對觀察者模式的事件處理。 監(jiān)聽事件的功能作為觀察員。每當一個事件被觸發(fā),它的監(jiān)聽函數(shù)就開始執(zhí)行。Node.js具有多個內(nèi)置通過事件模塊和用于將事件綁定和事件偵聽,如下EventEmitter類可用事件:
// Import events module var events = require('events'); // Create an eventEmitter object var eventEmitter = new events.EventEmitter();
以下為事件處理程序綁定使用事件的語法:
// Bind event and even handler as follows eventEmitter.on('eventName', eventHandler);
我們可以通過編程觸發(fā)一個事件,如下所示:
// Fire an event eventEmitter.emit('eventName');
創(chuàng)建一個名為具有以下代碼main.js一個js文件:
// Import events module var events = require('events'); // Create an eventEmitter object var eventEmitter = new events.EventEmitter(); // Create an event handler as follows var connectHandler = function connected() { console.log('connection succesful.'); // Fire the data_received event eventEmitter.emit('data_received'); } // Bind the connection event with the handler eventEmitter.on('connection', connectHandler); // Bind the data_received event with the anonymous function eventEmitter.on('data_received', function(){ console.log('data received succesfully.'); }); // Fire the connection event eventEmitter.emit('connection'); console.log("Program Ended.");
現(xiàn)在讓我們試著運行上面的程序作為檢查的輸出:
$ mnode main.js
這將產(chǎn)生以下結(jié)果:
connection succesful. data received succesfully. Program Ended.
在Node應(yīng)用程序,任何異步函數(shù)接受回調(diào)作為最后的參數(shù)和回調(diào)函數(shù)接受錯誤的第一個參數(shù)。我們再看一下前面的例子了。創(chuàng)建一個名為input.txt的有以下內(nèi)容的文本文件
Yiibai Point is giving self learning content to teach the world in simple and easy way!!!!!
創(chuàng)建一個名為具有以下代碼的main.js一個js文件:
var fs = require("fs"); fs.readFile('input.txt', function (err, data) { if (err){ console.log(err.stack); return; } console.log(data.toString()); }); console.log("Program Ended");
這里fs.readFile()是一個異步函數(shù),其目的是要讀取文件。如果在文件的讀出發(fā)生了錯誤,則er對象將包含相應(yīng)的錯誤,否則數(shù)據(jù)將包含該文件的內(nèi)容。readFile傳遞err和數(shù)據(jù),回調(diào)函數(shù)后,文件讀取操作完成,并最終打印的內(nèi)容。
Program Ended Yiibai Point is giving self learning content to teach the world in simple and easy way!!!!!