NodeJS, a Javascript Runtime Environment Based on GoogleV8 Engine

Source: Internet
Author: User
I. Introduction to NodeJS

First, let's think about a problem: we all know that almost all mainstream modern browsers fully support the ECMAScript 5.1 standard, while the JavaScript standard is ECMAScript. Therefore, JavaScript is an interpreted programming script on the browser. So, can JavaScript be interpreted to run without the browser?The answer is yes.That is to say, JavaScript can still run in a specific environment without the browser. JavaScript has always been known as the scripting language of Web pages, but it can also be used in many non-browser environments, such as node. js or Apache CouchDB. This article is based on NodeJS.

What is NodeJS?

According to Baidu encyclopedia, Node. js is a JavaScript toolkit for compiling high-performance network servers. Node. js is a platform that can quickly build network services and applications. The platform is built based on Chrome's JavaScript runtime. That is to say, it is actually applied to the GoogleV8 engine (for Google Chrome browsers) encapsulation. V8 cited worker to execute Javascript very quickly and with very good performance.

NodeJS does not provide simple encapsulation and then provides API calls. If so, it will not be so popular. Node optimizes some special use cases and provides an alternative API to make V8 run better in a non-browser environment. For example, in a server environment, binary data processing is usually essential, but Javascript does not support this. Therefore, V8.Node adds a Buffer class to facilitate and efficient processing of binary data. Therefore, Node not only simply uses V8, but also optimizes it to make it more powerful in various environments.

Advantages of Node. js

1. High-Performance servers can be built based on V8 virtual machines

The V8 engine uses some of the latest compilation technologies. This makes the code written in scripting languages such as Javascript less efficient than the code written in advanced languages such as C, but saves development costs. The performance requirement is a key factor in Node. Javascript is an event-driven language. Node uses this advantage to write highly scalable servers. Node adopts an architecture called "event loop", which makes writing highly scalable servers easy and secure. There are a variety of techniques to improve server performance. Node selects an architecture that improves performance and reduces development complexity. This is a very important feature. Concurrent Programming is usually complex and well-structured. Node bypasses this, but still provides good performance.

2. Single thread

Node. js can still process tasks in parallel without adding additional threads-Node. js is single-threaded. It implements parallel operations through event loop. We should make full use of this to avoid blocking operations as much as possible. Instead, we should use non-blocking operations.

3. Use Javascript For background Development

Although Javascript running on the server is not unique to Node, it is a powerful function. I have to admit that the browser environment limits the freedom to select programming languages. The desire to share code between any server and increasingly complex browser client applications can only be achieved through Javascript. Although there are other platforms that support Javascript running on the server, Node has developed rapidly due to the above features and has become a real platform.

4. Non-blocking IO

Node uses a series of "non-blocking" libraries to support event loops. Essentially, it provides interfaces for resources such as file systems and databases. When sending a request to the file system, you do not need to wait for the hard disk (addressing and retrieving files). When the hard disk is ready, the non-blocking interface will notify Node. This model simplifies access to slow resources in a scalable manner, which is intuitive and easy to understand. This is especially true for users who are familiar with DOM events such as onmouseover and onclick.

5. RESTFUL API

Ii. Why contact NodeJS, our problems and solutions

I am now an intern at IBM and participate in the development of the company's cloud Office System Project. My project team is mainly responsible for the development of online workbooks. Project front-end development is based on the DOJO framework, and the background is mainly based on JAVA. The functional development of the project has been basically completed, but in the actual test phase, it is found that the system overhead is large when the big data that exceeds a certain threshold is edited, and the running efficiency cannot meet the requirements.

After a lot of tracking tests and analysis, we have two solutions based on the overall architecture of the system and to solve this performance problem: 1. Because the system now uses the open-source syntax analyzer anlr for lexical parsing, and anlr is still inefficient, we decided to conduct secondary development based on anlr and seek some improvements; 2. Create a front-end server and separate it from the back-end server. The front-end and back-end jointly maintain the same data model. The front-end server mainly solves computing requests and timely feedback the computing results to the users. Then, it sends the changes to the back-end server, some operations such as persistent storage and message distribution are performed by the background server.

Because the front-end is developed based on the DOJO framework, in order to maximize reuse of the functional Code implemented in the previous stage, we consider building a front-end server based on NodeJS, it also makes full use of some node. js features to improve the system performance.

3. Why NodeJS?

I think it's more than just Node. js. Before we want to introduce any new technology, we must clarify several issues:

    • What problems have we encountered?
    • What problems does this new technology solve?
    • Where are the advantages of this new technology in the various solutions we encounter?
    • What new problems are caused by the use of new technologies? Can we solve them if they are serious?

Server-side blocking is the biggest problem encountered by the current system. During the entire data query process, the current program process is often only waiting for the return of results, which causes the process to be blocked. For network applications with high concurrency, large computing tasks, and intensive I/O lines, on the one hand, the process is waiting for a long time, and on the other hand, new processes are constantly added to cope with new requests. Such a waste will cause the system to support QPS much less than the QPS supported by the backend data service, and thus become the bottleneck of the system. Node has always advertised itself like this:"In node, everything except code is executed in parallel.". Node. js can still process tasks in parallel without adding additional threads. Node. js is single-threaded and implements parallel operations through event loop. We should make full use of this to avoid blocking operations as much as possible. Instead, use non-blocking operations. We set up a front-end server to handle a large number of front-end company calculations and present the computing results to users in a timely manner, so we can avoid many I/O blocking operations, in this way, we can make full use of the advantages of NodeJS while meeting our needs. In addition, the front-end DOJO framework is based on JS, and the advantages of NodeJS in JavaScript processing are described earlier.

JS is suitable for blocking

To solve the blocking problem, we can introduce the event processing mechanism to solve this problem. register the response function of the Data Loading event before the query request is initiated, and submit the process immediately after the request is sent, when the data is returned, this event is triggered and the data is processed in the predefined Event Response Function. Compared with other languages, JavaScript has at least two key features that make it especially suitable for this task.

(1) JavaScript is a functional programming language. The most important mathematical foundation of a functional programming language is lambda calculus ), that is, the function object can be used as the input (parameter) and output (return value) of other function objects ). This feature makes it easy to specify callback functions for events. In particular, JavaScript also supports anonymous functions. With the help of anonymous functions, we can easily implement callback. (2) Another important language feature of JavaScript: Closures ). This feature can maintain the running context of asynchronous callback, that is, "State persistence ".

Iv. Problems and Solutions caused by NodeJS

Blocking programming wastes a lot of Process resources but waits, resulting in a lot of memory and cpu waste. In this regard, Node. js is much better, but it is precisely because some built-in JavaScript mechanisms such as closures will also lead to a waste of resources. See the following code:

Js Code:

1 function main () {2 var id = "1"; 3 var str = "... "; // here, the local variable str stores a 2 m string 4 db. query ("selcect name from persons where id =" + id, function (name) {5 output ("person id:" + id + ", name:" + name ); // call back 6 after data is returned in n seconds); 7} 8 main ();

At least during the entire Data Query Process, the 2 MB memory used by the variable str will not be released, and it may not be meaningful to keep the variable str. We have already explained the principle of closures. closures are not smart enough to pack objects that may be accessed in the future.

V. Postscript

For more information, see. As the project needs to learn about node. JS, the author will continue to share some experience and achievements in the future.

 

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.