Node JS Installation + callback function + Event

Source: Internet
Author: User
Tags emit event listener readfile

/*Download from website https://nodejs.org/zh-cn/9.4. version 0 Download the installation installation directory is D:\ApacheServer\node all the way to the default installation after the installation of the CMD command line input path in the results displayed to find out if there are D:\ApacheServer\node has a statement that the environment variable already contains the D:\ApacheServer\node\ can be used in CMD directly using node This command, such as on the current command line input node-- Version display v9.4.0 current NODEJS versions ========================= output Hello World before writing code to understand node runtime if you use PHP to write back-end code, you need Apache or Nginx http server, with MOD_PHP5 modules and php-cgi. From this perspective, the entire "Receive HTTP request and provide WEB page" requirement does not need PHP to handle at all. But for node. JS, the concept is completely different. When you use node. js, you are not only implementing an application, but also implementing the entire HTTP server (the request gets returned, the listening port). First understand what parts of a node. JS application are introduced into the required module: You can use the Require directive to load the node. JS module. Two create server: The server can listen to the client's request, similar to Apache, Nginx and other HTTP server. Three receive requests and response requests: The server is easy to create, the client can use the browser or terminal to send HTTP requests, the server receives the request and returns the response data. *///=============================== The following code is the contents of the Test.js file ==========================================//Step one, introduce the required module, use the Require directive to load the HTTP module, and assign the instantiated HTTP value to the variable HTTPvarHTTP = require (' http ');//Step Two, create the server//Use the Http.createserver () method to create the server and bind port 8888 using the Listen method. The function uses the Request,response parameter to receive and respond to data. Http.createserver (function(Request, response) {//Send HTTP Header    //HTTP Status value: 200:ok    //content Type: Text/plainResponse.writehead (200, {        ' Content-type ': ' Text/plain '    }); //Send response data "Hello World"Response.End (' Hello world ' haha \ n ');}). Listen (8888);//information printed by the terminal (here is the cmd command line) after executing the JS fileConsole.log (' Server running at http://127.0.0.1:8888/');//=============================== The above code is the contents of the Test.js file ==========================================/*The encoded file is saved in D:\ApacheServer\web\test\test.js in CMD switch to the encoded directory D:CD apacheserver/web/test execute test.js file node Test.js the page can be opened in the browser at this time, the cmd command line cannot be closed, otherwise the execution file terminates, the browser cannot access the http://127.0.0.1:8888/*//*=========================node.js callback function The immediate manifestation of the asynchronous programming of node. JS is callback. Asynchronous programming relies on callbacks to implement, but it cannot be said that the program is asynchronous after using the callback. The callback function is called when the task is completed and node uses a large number of callback functions, and all node APIs support the callback function. For example, you can read the file while executing other commands, returning the file content as a parameter to the callback function after the file read is complete. This will not block or wait for file I/O operations when executing code. This greatly improves the performance of node. JS and can handle a large number of concurrent requests. The following code example differs between synchronous and asynchronous + callback methods*///Create a file input.txt, content: This is a test content//=============================== The following code is the contents of the Main.js file ==========================================//first, block code instances (synchronous sequential execution)varFS = require ("FS");vardata = Fs.readfilesync (' Input.txt '); Console.log (data.tostring ()); Console.log ("Program execution is over!");//=============================== The above code is the contents of the Main.js file ==========================================/*Execute main.jsnode main.js output: This is a test content program execution end!*///=============================== The following code is the contents of the Main.js file ==========================================//non-blocking Code instance (asynchronous + callback execution)varFS = require ("FS");//the second parameter of the ReadFile method is the callback function, which reads the Input.txt file and then calls the following method and passes the arguments .Fs.readfile (' Input.txt ',function(err, data) {if(err) {returnConsole.error (ERR); } console.log (Data.tostring ());}); Console.log ("Program execution is over!");//=============================== The above code is the contents of the Main.js file ==========================================/*Execute main.jsnode main.js output: Program execution is over! This is a test. The above two instances show the difference between blocking and non-blocking calls. The first instance executes the following code after the file has finished reading. The second instance does not need to wait for the file to be read so that the next code can be executed while the file is being read, greatly improving the performance of the program. As a result, blocking is performed sequentially, not blocking is not required in order, so if you need to handle the parameters of the callback function, you need to write it inside the callback function. *///=========================node.js Events and Event loops/*node. JS is a single-process single-threaded application, but it supports concurrency through events and callbacks, so performance is very high. Every API (pre-defined function) of node. JS is asynchronous and runs as a standalone thread, using asynchronous function calls to handle concurrency. node. js basically all of the event mechanisms are implemented using the Observer pattern in design mode. The node. JS single thread resembles an event loop that enters a while (true) until it exits without an event observer, and each asynchronous event generates an event watcher that invokes the callback function if an event occurs. Event driver node. JS uses the event-driven model when the Web The server receives the request, shuts it down and processes it, and then goes to service the next Web request. When this request is completed, it is put back into the processing queue, and when the request is sorted to the beginning of the queue, the result is returned to the user. This model is very efficient and extensible because webserver always accepts requests without waiting for any read and write operations. (This is also known as non-blocking IO or event-driven IO) in the event-driven model, a main loop is generated to listen for events and trigger a callback function when an event is detected. node. JS has several built-in events that can be used to bind and listen to events by introducing the events module and instantiating the Eventemitter class, and the events module provides only one class object: Events. Eventemitter. The core of Eventemitter is the encapsulation of event triggering and event listener functionality. The steps are as follows://Introduce the events module var events = require (' events ');//Create Eventemitter object var eventemitter = new events. Eventemitter ();//A listener handler that binds events and events, eventname a custom event name, EventHandler1 and EventHandler2 variables each represent a custom function, Here represents a listener for the EventName event, the same event can be bound to multiple listeners, when the event is triggered, all the listeners that bind will execute the following instance in turn to have a specific application Eventemitter.on (' EventName ', eventHandler1 ); Eventemitter.on (' EventName ', eventHandler2);//Trigger Event Eventemitter.emit (' EventName ');// The EventName event-bound Eventhandler1,eventhandler2 two listener functions areEach event that executes Eventemitter consists of an event name and several parameters, which is a string that usually expresses a certain semantics. For each event, Eventemitter supports a number of event listeners. An error event is triggered when an Eventemitter object occurs when the instance is instantiated. When a new listener is added, the Newlistener event is triggered and when the listener is removed, the RemoveListener event is triggered. Many objects in node. JS Distribute Events: A Net.server object distributes an event every time a new connection is made, and an Fs.readstream object emits an event when the file is opened. All the objects that generated the event are events. An instance of Eventemitter.*///Example//=============================== The following code is the contents of the Main.js file ==========================================//Introducing the Events modulevarEvents = require (' Events ');//Create a Eventemitter objectvarEventemitter =Newevents. Eventemitter ();//The above two sentences can also be changed to write/*var eventemitter = require (' Events '). Eventemitter;var eventemitter = new Eventemitter ();*///To create an event handlervarConnecthandler =functionconnected () {Console.log (' Connection succeeded. ‘); //Triggering data_received EventsEventemitter.emit (' data_received ', ' arg1 parameter ', ' arg2 parameter '));}//binding Connection Event handlersEventemitter.on (' Connection ', Connecthandler);//binding data_received events with anonymous functionsEventemitter.on (' data_received ',function(Arg1, arg2) {Console.log (' Data received successfully. ' +arg1+arg2);});//Triggering connection EventsEventemitter.emit (' Connection '); Console.log ("The program has finished executing. ");//=============================== The above code is the contents of the Main.js file ==========================================/*Execute main.jsnode main.js output: Connection successful. Data received successfully. ARG1 parameter arg2 parameter program execution is complete. *///more Eventemitter Object Examples//Example//=============================== The following code is the contents of the Main.js file ==========================================varEvents = require (' Events ');varEventemitter =Newevents. Eventemitter ();//Listener #1varListener1 =functionListener1 () {Console.log (' Listener listener1 execution. ‘);}//Listener #2varListener2 =functionListener2 () {Console.log (' Listener listener2 execution. ‘);}//Listener #3varListener3 =functionListener3 () {Console.log (' Listener Listener3 execution. ‘);}//AddListener (event, listener) adds a listener to the tail of the listener array for the specified event. //bind connection event, handler function is Listener1Eventemitter.addlistener (' Connection ', listener1);//On (event, listener) registers a listener for the specified event, accepting a string event and a callback function. //There is no difference between eventemitter.on () and Eventemitter.addlistener (), and an event can bind multiple callback functions. //bind connection event, handler function is Listener2Eventemitter.on (' Connection ', listener2);//once (event, listener) registers a single listener for the specified event, that is, the listener is fired at most once, and the listener is released immediately after the trigger. //bind connection event, handler function is Listener3Eventemitter.once (' Connection ', Listener3);//Get connection event bound by several listenersvarEventlisteners = require (' Events '). Eventemitter.listenercount (eventemitter, ' connection ')); Console.log (Eventlisteners+ "Listener listens for connection events. ");varEventlistenerarr = eventemitter.listeners (' connection ')); Console.log (Eventlistenerarr);//Handling Connection EventsEventemitter.emit (' Connection ');//RemoveListener (event, listener) removes a listener for a specified event, and the listener must be a listener for which the event has already been registered. It takes two parameters, the first is the event name, and the second is the name of the callback function. //removealllisteners ([Event]) removes all listeners for all events, and if the event is specified, removes all listeners for the specified event (the brackets [] here indicate dispensable, not an array). //Remove the Listener1 function from the supervisor bindingEventemitter.removelistener (' Connection ', Listener1); Console.log ("Listener1 is no longer subject to monitoring. ");//Triggering connection EventsEventemitter.emit (' Connection '); Eventlisteners= Require (' Events '). Eventemitter.listenercount (eventemitter, ' connection ')); Console.log (Eventlisteners+ "Listener listens for connection events. "); Console.log ("The program has finished executing. ");//Eventemitter defines a special event error that contains the semantics of the error, and we usually trigger an error event when we encounter an exception. //eventemitter.emit (' error ');//=============================== The above code is the contents of the Main.js file ==========================================/*perform Main.jsnode main.js output: 3 Listeners listen for connection events. [[Function:listener1], [Function:listener2], [Function:listener3]] listener listener1 execution. Listener Listener2 execution. Listener Listener3 execution. Listener1 is no longer subject to monitoring. Listener Listener2 execution. 1 Listeners listen for connection events. Execution of the program is complete. */

Node JS Installation + callback function + Event

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.