Initial knowledge of Nodejs, a JavaScript runtime environment based on the GOOGLEV8 engine

Source: Internet
Author: User

Thinking

First, let's consider a question: we all know that almost all modern mainstream browsers fully support the ECMAScript 5.1 standard, while the JavaScript standard is ECMAScript. Then it is easy to assume that JavaScript is a browser-side interpretive programming script. So is JavaScript still able to explain the run out of the browser? The answer is Yes, that is, out of the browser, JavaScript still works in a given environment. JavaScript has always been known as the scripting language of Web pages, but it can now be used in many non-browser environments, such as node. js or Apache CouchDB. This article is based on the Nodejs to explore.

What is Nodejs?

According to Baidu Encyclopedia, node. JS is a set of JavaScript toolkits for writing high-performance Web servers. node. JS is a platform that can quickly build Web services and applications based on the Chrome's JavaScript runtime, which means that it is actually encapsulated in the GOOGLEV8 engine (applied to Google Chrome). The V8 engine executes JavaScript very fast and performs very well.

Nodejs does not provide a simple encapsulation and then provides API calls, and if so then it will not be so hot now. Node optimizes some of the special use cases, providing an alternative API that allows V8 to run better in a non-browser environment. For example, in a server environment, it is often necessary to process binary data, but JavaScript has insufficient support for this, so V8. Node adds the buffer class for easy and efficient processing of binary data. As a result, node not only uses V8, but also optimizes it to make it more resilient in all environments.

Advantages of node. js

1, based on V8 virtual machine, can build high-performance server

The V8 engine itself uses some of the latest compilation techniques. This makes the code written in JavaScript scripting languages comparable to code written in high-level languages such as C, but saves development costs. Demanding performance is a key element of node. JavaScript is an event-driven language, and node takes advantage of this to write a highly scalable server. Node uses a schema called Event loop, which makes it both easy and secure to write servers that are highly scalable. There are a variety of techniques to improve server performance. Node chooses a architecture that improves performance and reduces development complexity. This is a very important feature. Concurrent programming is often complex and mine-infested. Node bypasses these, but still provides good performance.

2. Single Thread

node. js can still process tasks in parallel without adding additional external threads--node.js is single-threaded. It implements parallel operations through event polling, which we should take advantage of--avoid blocking operations as much as possible and use non-blocking operations instead.

3, can use JavaScript for background development

While it is not unique to node to run JavaScript on the server side, it is one of the most powerful features. We have to admit that the browser environment limits our freedom to choose a programming language. The desire to share code between any server and an increasingly complex browser client application can be achieved only through JavaScript. While there are other platforms that support JavaScript running on the server side, because of these features, node has grown rapidly and become a de facto platform.

4. Non-blocking IO

Node uses a series of "non-blocking" libraries to support the way events loop. Essentially, it provides interfaces for resources such as file systems and databases. When sending a request to the file system, there is no need to wait for the hard drive (addressing and retrieving the files) and the non-blocking interface notifies node when the hard disk is ready. The model simplifies access to slow resources in an extensible way, intuitive and understandable. Especially for the familiar with onmouseover, onclick and other DOM events users, there is a sense of déjà vu.

5. RESTFUL API

Second, why contact Nodejs, our problems and solutions

I am now in IBM internship, participate in the company's Cloud Office System project development, my project team is mainly responsible for online spreadsheet development work. Project front-end development is based on the Dojo framework, and the background is primarily Java based. The functional development of the project has been basically completed, but in the actual testing stage, it is found that the system overhead is large and the operation efficiency cannot meet the requirements when editing big data exceeding a certain threshold value.

After extensive follow-up testing and analysis, based on the overall architecture of the system and solve the performance problem, we have two sets of solutions: 1, because the system lexical analysis is using the open source parser ANTLR, and ANTLR in the efficiency of a slight shortage, so we decided to ANTLR based on two development, to seek some improvement; 2. Set up front-end server and detach from background server. Front-end and the background to maintain a consistent data model, the front-end server mainly solve the operation of the request and the results of timely feedback users, and then send the changes to the background server, the background server for persistent disk, message distribution and other operations.

Because the front-end is based on the development of the Dojo framework, in order to maximize the reuse of the function code implemented in the previous phase, we consider building a front-end server based on Nodejs, and make full use of some features of Nodejs to improve the performance of the system.

Third, why Choose Nodejs

I think it's not just node. js, we have to figure out a few things before we introduce any new technology:

      • What problems have we encountered?
      • What problems does this new technology solve, and does it fit with the problems we encounter?
      • What are the advantages of the current new technology in the various solutions that we encounter problems?
      • What are the new problems that can be solved by using new technology?

Server-side blocking is the biggest problem that the current system encounters. During the entire data query process, the current program process is often just waiting for the result to return, which causes the process to block. For network applications with high concurrency, large computational tasks, and I/O intensive lines, the process is waiting for a long time on one hand, and new processes are constantly being added to cope with new requests. This waste can cause the system to support QPS far less than the back-end data service can support the QPS, become the bottleneck of the system. Node has always advertised his own: "Everything is executed in parallel in node except for code ." This means that node. js can still process tasks in parallel without adding an additional external thread. node. js is single-threaded, and it uses event polling to implement parallel operations, so we should take advantage of this, avoid blocking operations as much as possible, and use non-blocking operations instead. We set up front-end servers to handle a large number of front-end corporate computing and to present the results to the user in a timely manner, so I can avoid many I/O blocking operations, so that we can take full advantage of the advantages of NODEJS and can meet our needs. In addition, our front-end based on the Dojo framework is JS-based, and the advantages of NODEJS in the processing of JavaScript has been described earlier, here no longer repeat.

JS is suitable for solving blocking problems

Resolving blocking can introduce an event handling mechanism to solve this problem, register the response function of the data Load event before the query request is initiated, hand over the process immediately after the request is issued, and then trigger the event after the data is returned and continue processing the data in the scheduled event response function. JavaScript, in contrast to other languages, has at least two key features that determine its suitability for accomplishing this task.

(a) JavaScript is a functional programming language, and the most important mathematical basis for a functional programming language is the lambda calculus (lambda calculus), which is the input (parameter) and output (return value) of the function object as other function objects. This feature makes it easy to specify a callback function for an event. In particular, JavaScript also supports anonymous functions, and with the aid of anonymous functions, we can easily implement callbacks. (ii) Another important language feature of javascript: Closures (Closures). This attribute allows the run context of the asynchronous callback to persist, that is, state hold.

Iv. problems and solutions arising from the use of Nodejs

Blocking programming wastes a lot of process resources just waiting, resulting in a lot of memory and CPU waste. node. js is a lot better in this regard, but it's also because JavaScript built-in mechanisms such as closures can lead to wasted resources. Look at the following code:

JS Code:

1 function Main () {2     var id = "1"; 3     var str = "..."; Here the local variable str stores a 2M string of 4     db.query ("Selcect name from persons where id=" + id,function (name) {5         output ("Person ID: "+ ID +", Name: "+ name",//n seconds after data return to execute callback 6     }); 7} 8 main ();

At least 2 m of memory used by the variable STR will not be freed during the entire data query, and it may not be meaningful for STR to persist. The principle of closures has been explained earlier, and closures are not intelligent enough to wrap up objects that may be accessed in the future.

Initial knowledge of Nodejs, a JavaScript runtime environment based on the GOOGLEV8 engine

Related Article

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.