node. js Event mechanism

Source: Internet
Author: User
Tags emit readfile

Yesterday to today, and looked at the side of node's event module, feel very magical ~ share---

First, add to the understanding of node:

NodeJs is a single-process single-threaded application, but supports concurrency through events and callbacks, so performance is very high ~

So what is single-process single-threaded ~ (to Chinese as bad as my small partner)

Let's look at the difference between a single process and a multi-process:

1. The advantage of multi-process is that the independence of the task, such as a task alone as a process, the crash only affects their services, the other tasks are not affected. If multiple tasks are handled within the same process using multiple threads, a thread that has an unhandled exception causes the entire process to die. All the tasks are under the shadow.

2. In terms of resource allocation, multi-process programmes are more flexible and free than multithreaded programmes

3. However, the multi-tasking process is more complicated than multithreading, and it is much more difficult to make a good multi-process communication scheme than the multi-threaded communication scheme (small partners pay attention to distinguish processes and threads yo ~)

In the case of Web server, for example, I have three sites on my server, and if it is managed by a single process, site A is attacked and killed, which means that the other two sites will appear the same way. If the separate process is separate, three sites do not affect each other

In particular, what are the advantages of single process versus multi-process :

1) Early implementation is relatively simple and fast, and does not consider the workload of inter-process communication

2) singleness makes deployment and operation relatively simple (this also uses the say/eye ing)

3) memory footprint, but, now the memory is very cheap, but a penny is money!

4) Process internal communication efficiency than Ipc/scoket (multi-process data communication terminal) and so on to be efficient, I have a voice you can hear, you don't have to use the strength to put a phone

Sure, pros and cons! Otherwise, the people who spend so much money on the process are too stupid.

single-Process vs. multi-process Disadvantage ~

1) This single process becomes bloated and difficult to maintain as the complexity of business logic and demand increases in the middle and later stages. Splitting a task into multiple processes makes the logic of a single process simple and error-prone

2) in-process modules are strongly dependent on each other and need to be compiled with each other's influence is also relatively large. This is relative to the multi-process communication, the coupling degree is large (does not conform to the great idea of cohesion and low coupling), is not conducive to multi-team parallel development. Multi-process facilitates multi-lingual collaborative development.

3) Any module crashes will cause the whole process to fail, the multi-process mode is more stable and robust, the business processing program is isolated and run, a go home will not affect the other (you dare to shoot me also collapse);

4) Performance issues: If interprocess data communication is not supported, the capacity of a single process is limited, and this performance bottleneck is especially important in support of group-class services. The multi-process deployment is extremely flexible, with the ability to expand the number of machines to improve system processing performance and to avoid single points of failure from the hardware. (A person cannot afford to do so)

5) Multi-threaded in a single process difficult to debug (a gun out, a group of people fell, I have to check who was shot to give you debug)

Give me a little chestnut.

You have an object, the object is very picky, but the object only like a dish, you do to her every day to eat.

This is a single-process one-thread model, if you do not eat, the object does not eat.

But I have an object, she likes to eat 10 vegetables, I end the past 10, which day one of the vinegar put more, the object said it is terrible, today do not eat. This is the single-process multithreading model. A dish is not delicious cause the object does not eat (all lines Cheng off)

..  If I have two objects: Each object likes to eat one dish

OK, an object feel delicious, eat face round three chin, a feel not delicious perennial don't eat, skinny.

This is a multi-process single-threaded non-impact model: Multi-process Multithreading I'm not going to raise the chestnut.

Speaking of which, small partners have some understanding of single-process threading. NodeJs is a single-process single-threaded application, the process of non-impact, binding multiple events can be triggered at the same time ~ do not wait for you to finish I have action, so nodeJs performance is very high.

The NodeJs single thread resembles an event loop that enters a while (true), knowing that when no event observer is exited (an event watcher is generated for each event that is bound), the event's callback function is invoked when an event occurs.

Event Driver

NodeJs uses the event-driven model (later), when the Web server receives the request, shuts it down and processes it, and then goes to service the next Web request. It can be understood that I triggered the event by shutting down the event driver and then processing it, which I think is preventing two triggering ~ causing incorrect load and unexpected results, and 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)

Maybe some of the small partners will ask, what is the event-driven model?

In fact, before we know about event-driven, we can look at the three main elements of event-driven:

1) Event Source: Who will accept external events

2) Listener: An object capable of receiving event source notifications

3) Event handlers: for handling events

Well, it's a complete event driver that contains the above three points.

Give me a chestnut.

If one day you walk on the road accidentally by the sky fell the vase hit, and dizzy dead past. Then the whole process is actually an event processing process, and we can easily analyze the three elements of the event-driven model that we just mentioned.

1. The person who was knocked unconscious is actually the source of the event, because he is able to accept the source of external events.

2. The listener is the brain of this person because it senses pain.

3. The event handler is the person who fainted in the past.

In the event-driven model, a main loop is generated to listen for events and trigger a callback function when an event is detected.

The entire event-driven process is so simple. Somewhat like the Observer pattern, the event is equivalent to a subject (Subject), and all the processing functions registered to the event are equivalent to the Observer (Observer).

Having said so much, how to write event bindings.

In node, there is an event module events, which we can bind by instantiating the events object.

On the code:

var event = require (' events '); Introducing the Event module

var eventObj = new event (); Instantiate an Event object

Eventobj.on (' Wake Up ', function () {//Bind event and event callback

Console.log (' Wash your face and brush ');

});

Eventobj.emit (' Get up '); Ways to trigger events

The results of the operation are as follows ~

The results are in line with expectations.

But one thing to note is that when you want to remove an event, Eventobj.removelistener (' Get up ') directly

Then various errors ~

In fact, the correct way to remove the event is this ~

On the code:

var event = require (' events '); Introducing the Event module

var eventObj = new event (); Instantiate an Event object

function GetUp () {

Console.log (' Wash your face and brush ');

}

Eventobj.on (' Get Up ', getup);

Eventobj.emit (' Get up ');

Eventobj.removelistener (' Get Up ', getup);

Eventobj.emit (' Get up ');

Successfully removed events ~

Node also provides a way to trigger only a single event ~

Eventobj.once (' Wake Up ', GetUp)

And the removal of all events!

EVENTOBJ. removealllisteners (GetUp), as I have specified the GetUp event, remove all listeners that triggered the event.

The Eventobj.setmaxlisteners (n) parameter is a number, because node defaults to a binding event of up to 10, and more than 10 times a warning. Set the maximum number of listeners if you don't want to be warned

Eventobj.listeners (even) returns the listener array for the specified event

EVENTOBJ. emit (getup, [arg1], [arg2], [...])

The event is executed in the order of the arguments, and the return value is true or false. This listener event will return true.

Do not know the small partners have no doubts, I clearly have the events module loaded over, why also to use the instantiation of it ~

Most of the time we don't use eventemitter directly, but we inherit it from the object. Including FS, NET, HTTP, as long as the core modules that support event response are Eventemitter subclasses.

Why did you do it? There are two reasons:

First, an object implementation event with an entity function conforms to the semantics (you can name it Yourself (# ' o′)), and the listener and launch of the event should be the method of an object.

Secondly, the object mechanism of JavaScript is based on prototype, supporting partial inheritance, inheriting Eventemitter does not disturb the original inheritance relationship of the object.

How does the Node application work?

In the Node application, the function that performs the asynchronous operation takes the callback function as the last parameter, and the callback function receives the error object as the first argument.

Let's take a look at the previous example and create a input.txt with the following file contents:

123456123123

Create the Main.js file with the following code:

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 execution Complete");

The above program Fs.readfile () is an asynchronous function used to read the file. If an error occurs during the reading of the file, the error Err object will output an error message.

If no error occurs, ReadFile skips the output of the Err object, and the contents of the file are output through the callback function.

Execute the above code and execute the result as follows:

123456123123

Next we delete the Input.txt file, and the execution results are as follows:

Program execution complete error:enoent, open ' input.txt '

The error message is output because the file input.txt does not exist.

OK, well, almost, I hope to learn something with my little friends (a pseudo-learning year to share a fool's note)

node. js Event mechanism

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.