What you must know to get started with Nodejs

Source: Internet
Author: User
Tags emit

About node. js

Nodejs is not a new language, and the Platform for developing languages is not the same as java,php, although he is javascript but it is not a JavaScript framework. Nodejs is a development platform that lets JavaScript run on the server side. when a transaction in one domain alone in the failure of the time will be thinking into another area , JavaScript has been unified in recent years, the front-end of the lake, so has begun to enter the field of service. node. JS is a platform built on the chrome JavaScript runtime, written in C + +, which is actually encapsulated with the Google Chrome V8 engine, which is used primarily to create fast, scalable Web applications. node. JS employs 事件驱动 and 非阻塞I/O模型 makes it light and efficient, making it ideal for building data-intensive real-time applications running on distributed devices.

What can node. js do
    • There was no logical code involved in JavaScript before, but the advent of node allowed JavaScript to do some responsible logic code
    • JavaScript is client-side and node is network-born
    • Asynchronous way, suitable for concurrent large applications
Why does node. js appear

No one used to think of JavaScript as their Web server. Because JavaScript is relatively slow and chaotic
-The V8 engine solves the slow JavaScript problem
-Commonjs solved the problem of chaos
-node is characterized by event-driven
-To compensate for JavaScript on the server side of the blank

Synchronous I/O and asynchronous i/o1. Synchronous I/O (blocking (synchronous) I/O)

When the computer dispatches the thread to do I/O operation command, because the file read or write or network communication takes a long time to operate, the operating system in order to make full use of the CPU, this time will be suspended to the current I/O thread of the CPU control (so called synchronous is blocking I/O), the cup resources to other thread resources, When the I/O thread completes the operation, the operating system resumes the I/O thread at this point so that the current I/O thread regain control of the cup and proceed with other operations.

var fs   require("fs");//readFileSync表示同步读取var data = fs.readFileSync("text.js","utf-8");console.log(data);console.log("end");
2. Asynchronous I/O (non-blocking (asynchronous) I/O)

The blocking policy is not used for all I/O operations, and when a thread encounters an I/O operation, it does not wait for the completion of the I/O operation or the return of the data in a blocking manner, but only the IO request is sent to the operating system, continuing with the next statement, notifying the thread performing the IO operation as an event when the operating , the thread will handle the event at a particular time, and in order to handle the asynchronous IO, the thread must have an event loop, constantly checking for unhandled events, and then processing them sequentially.

var fs  require("fs");//默认是采用异步式I/Ofs.readFile(‘text.js‘,‘utf-8‘,function(err,data){    if(err){        console.log(err);    }else{        console.log(data);    }})console.log("end");

The result of the output is:

endread me  //text.js文件里面的内容
3. Differences between synchronous I/O and asynchronous I/O

Asynchronous: A thread is always performing a compute operation, and the CPU core utilization used by this thread is always 100%,io as an event notification.
Synchronous: Multithreading tends to improve system throughput because one thread blocks and other threads are working, and multithreading allows the CPU to be wasted by threads that are not blocked (throughput: The average amount of data that can be successfully delivered per unit of time on a communication channel. In short, it means how fast the system can handle it.
This is obvious, although the efficiency of the synchronous type is not as asynchronous as the synchronous type wastes the event in the blocking recovery.

ID Synchronous io (blocking) Asynchronous IO (non-blocking)
1 Using multithreading to deliver throughput Single thread for high throughput
2 Leveraging multi-core CPUs through event slice segmentation and thread scheduling Using multi-core through functional partitioning
3 Requires multi-core CPU to be used by the operating system to schedule multithreading Can bind a single thread to a single core CPU
4 Hard to make full use of CPU resources Can take full advantage of CPU resources
5 Large memory track, weak data locality Small memory track, strong data locality
6 Line-up programming thinking does not conform to traditional programming thinking

Here are some of the most difficult to understand:
First understand what scheduling is,
Dispatch: It is simple to specify two parameters 工作 and 触发器 , for example, eat after five minutes, eat is work, five minutes is the trigger

1. Synchronous is to improve throughput by opening up multithreading, asynchronous through continuous requests to improve the throughput of 2. Synchronous is through the segmentation of the event slices and the ready-made scheduling of the CPU, asynchronous is by dividing the function to take advantage of the CPU (there is a function to start the request) 5. Memory Trace Osashi is open up a number of threads, Memory changes are relatively large; data locality if the data is scattered, the thread can not contact, so the data is more scattered node. JS Programming Primer

This is based on the premise that the node environment has been installed;

1.hello World

Hit a text editor in which to enter

console.log(‘Hello World‘);

and save it as helloworld.js. Open a DOS window to enter the directory of the file to run
node helloworld.jsexecution can see the output of the HelloWorld

2.node.js command-line tools
node  -v  版本node -e      eval scipt    eval(“console.log(‘呵呵‘)”); 例:node -e "console.log(‘hello world‘)";   直接执行        node 直接进入编译模式    console.log("111")    第一行是输出、第二行是返回值
3. Establishing an HTTP server
varrequire(‘http‘);http.createServer(function(request,reponse){    //回送一个head头部,返回值是200    reponse.writeHead(200,{‘Content-Type‘:‘text/html‘});    //内容信息    reponse.write("thisd i strue");    //请求结束    reponse.end();}).listen(5353);//监听的是5353端口console.log("end"

The diagram on the page is shown below

4. Debugging the Code

Corresponding to the server created above, if each change must be run manually once this will certainly be very cumbersome, we can install a plug-in can not be rerun every time the server
npm install -supervisor -g
To install this plugin to the global
And then through supervisor Xx.js can listen to change

How node's event-driven 1.Node event works
    1. Binding an event to an object (bound by the On method) can also be understood to observe the action of an object by adding one or more observers (through the callback setting event, called the callback method).
    2. This object triggers an event in a state or operation, or activates the observer behavior (activating a class of events or observers via emit)
    3. The event being activated performs the appropriate processing (execution of the callback method)
2.EventEmitter objects

Eventemitter is the core object of events in node. js, and all the events are basically built from this object!

var eventEmit  require(‘events‘).EventEmitter;var event      new eventEmit();//定义一个事件event.on(‘newEvent‘,function () {    console.log("this is zidingyi event");});//通过emit方法来触发这个事件event.emit("newEvent");
3. Event Loops

This is also the most important point, when it comes to the event loop to talk about the operation of JavaScript, JavaScript is a single-threaded language, single-threaded means that can only perform one task at a time, then when encountered multiple tasks what to do? What else can I do in line?
But if the task is more or the time-consuming task is running, queuing this way will appear in the Web page "suspended animation" situation, because JavaScript has not stopped.
If you run into a task that is very resource-intensive, such as when multiple I/O operations are involved, use the principle of "queuing" (not one to run the next): From the first start of a task request (for example, an HTTP request, a file read request), It's time to wait until the file responds to the next task, where waiting for a file response to be relative to a task request can be a lengthy [1], as in the following diagram:

Because I/O operations are slow, most events are the result of waiting for I/O operations to return.
This is the reason that node appears, which is based on node 事件循环 . Official website The definition of the event loop is this: the a programming construct that waits for and dispatches events or messages in a program general meaning is to set up two processes in the program, one is responsible for the program itself 主进程 , the other is responsible 主进程 and 其他进程之间的通信 (like in the HTTP request, file requests and so on I/O operations).
To understand the point is that the above diagram of the operation is 辅助进程 done, each time I am encountered I/O operation, the main thread will let the event loop to notify the response of the I/O program, and then the byte down, wait until the I/O program operation completes, the event loop in the results returned to the main process. Naturally there is no waiting time.
This mechanism is equivalent to the following figure (the picture is very ugly, do not spray):

This is also the non-blocking I/O implemented by node

This is a series of node, you can see in this column other about node article, will be updated, there are questions please leave a message below

What you must know to get started with Nodejs

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.