Why does Nodejs use javascript as the carrier language _ node. js?

Source: Internet
Author: User
I am going to write a series of articles on node. js. It is easy to understand and step by step. Adhering to the philosophy of focusing on thinking, practice, and diligence, you must stick to it. First, let's start with the basic knowledge. Let's take a look at the introduction on the official node. js Website:

Features:

1. It is a Javascript Runtime Environment

2. Code explanation based on Chrome V8 engine

3. event-driven

4. Non-blocking I/O

5. lightweight and scalable, suitable for real-time data interaction applications

6. Single Process and single thread

(1) Why does Nodejs use javascript as the carrier language?

In fact. at the beginning of js, Ryan Dahl did not select JavaScript. He tried C and Lua because of its lack of some advanced language features, such as closure and functional programming, which made the program complex, difficult to maintain.

JavaScript is a language that supports functional programming paradigm and fits well with Node. js's event-driven programming model. In addition, Google's V8 engine greatly improves the execution speed of the JavaScript language.

In the end, it becomes the implementation of Node. js instead of Node. c, Node. lua, or other languages.

(2) Node. js is not a JS application, but a JS running platform

When you see the name of Node. js, beginners may mistakenly think that this is a Javascript application. In fact, Node. js is written in C ++ and is a Javascript runtime environment.

Node. js uses Google Chrome's V8 engine to provide excellent performance. It also provides many system-level APIs, such as file operations and network programming.

The following are all the modules involved in NodeJS:

    

Browser-side Javascript code is subject to various security restrictions during operation, and the operation on the customer's system is limited.

In contrast, Node. js is a comprehensive background runtime that provides many functions that can be implemented by other languages for Javascript.

(3) features of Node. js

Node. js is also relatively innovative in design. It runs in single process and single thread mode (which is consistent with the Javascript running mode ),

The event-driven mechanism is Node. js is implemented through highly efficient maintenance of the event loop queue by a single internal thread. It does not have multi-threaded resource occupation and context switching, which means that in the face of large-scale http requests, Node. js handles everything with event-driven,

Network service developers who are used to traditional languages may be very familiar with multi-thread concurrency and collaboration, but in the face of Node. js, we need to accept and understand its features.

Ii. Important Concepts

1. What is Event Loop? (Important concepts)

Event Loop is a very important concept, which refers to a running mechanism of computer systems.

To understand Event Loop, start with the program running mode. A running program is called a Process. Generally, a Process can only execute one task at a time.

If many tasks need to be executed, there are no more than three solutions.

(1), queuing. Because a process can only execute one task at a time, it has to wait until the previous task is finished and then execute the subsequent task.

(2) create a process. Use the fork command to create a process for each task.

(3) create a thread. Because the process is too resource-consuming, today's programs often allow a process to contain multiple threads, and tasks are completed by threads.

Taking JavaScript as an example, it is a single-threaded language. All tasks are completed on one thread, that is, the first method above. Once you encounter a large number of tasks or a time-consuming task, the web page will be "suspended", because JavaScript cannot stop, it will not be able to respond to user behavior.

You may ask why JavaScript is a single thread. Isn't it possible to implement multiple threads?

This is related to history:

One of the major features of JavaScript is the single thread, which means that only one thing can be done at the same time. So why cannot JavaScript have multiple threads? This improves efficiency.

The single thread of JavaScript is related to its purpose. As a Browser Scripting Language, JavaScript is mainly used to interact with users and operate DOM. This determines that it can only be a single thread, otherwise it will bring a very complicated synchronization problem.

For example, if JavaScript has two threads at the same time, one thread adds content to a DOM node, and the other thread deletes the node, which thread should the browser take as the standard?

Therefore, in order to avoid complexity, JavaScript is a single thread from its birth, which has become the core feature of the language and will not change in the future.

To utilize the computing capability of multi-core CPUs, HTML5 proposes the Web Worker standard, which allows JavaScript scripts to create multiple threads, but the sub-threads are completely controlled by the main thread and cannot operate the DOM.
Therefore, this new standard does not change the nature of JavaScript single-thread.

Return to EventLoop:

A single thread means that all tasks need to be queued and the previous task ends before the latter task can be executed. If the previous task takes a long time, it will have to wait.

If the queue is too large for computing and the CPU is too busy, it may be okay, but the CPU is mostly idle because of the I/O device (input/output device) it is slow (for example, Ajax operations read data from the network) and has to wait for the results to come out before executing.

The designers of the JavaScript language realized that the main thread can suspend a waiting task regardless of the I/O device, and first run the following task. Wait until the IO Device returns the result and then go back and continue the pending task.

Therefore, all tasks can be divided into two types: synchronous and asynchronous ). A synchronization task refers to a task that is queued on the main thread and executed only after the previous task is completed,

The next task can be executed. An asynchronous task refers to a task that enters the "task queue" instead of the main thread. Only the "task queue" notifies the main thread, an asynchronous task can be executed before it is executed in the main thread.

For example:

        

As long as the main thread is empty, it will read the "task queue", which is the JavaScript operating mechanism. This process will be repeated.

Iii. Examples

Okay, I will not talk much about "nonsense". Now we will start our first NodeJS application: "Hello Big Bear ".

Open your favorite editor and createHelloWorld. jsFile.

The Code is as follows:

The Code is as follows:

1 var http = require ("http"); 2 http. createServer (function (request, response) {3 response. writeHead (200, {4 "Content-Type": "text/plain" 5}); 6 response. write ("Hello, Big Bear! "); 7 response. end (); 8}). listen (8888 );

Let's run and test this code. First, use Node. js to execute your script:

Open the command line tool CMD, switch to your working directory, and run the command "node HelloWorld. js"

Next, open the browser to access http: // localhost: 8888/, and you will see a message saying "Hello, big bear !" .

A small amount of extended knowledge:

As shown in, this is the http in NodeJS. part of the js source code, createServer is a user-friendly interface, internal implementation adopts the singleton mode, the advantage of doing so is to effectively separate the instance creation and initialization tasks, dedicated responsibilities to reduce coupling. This is an idea that can be used for programming at ordinary times.

  

Haha, isn't it interesting? This is just a short experience. I will explain a lot of knowledge points later, and you will learn about O (∩ _ ∩) O Haha ~

Iv. Overview

1. It is a Javascript Runtime Environment

2. Code explanation based on Chrome V8 engine

3. event-driven

4. Non-blocking I/O

5. lightweight and scalable, suitable for real-time data interaction applications

6. Single Process and single thread

Finally, I would like to say that there are not many examples in this article, but these concepts are very important and must be clearly understood. This will lay a solid foundation for future NodeJS learning, let's work together.

Hahaha, this article is over and is not to be continued. I hope to communicate with you more and make progress together ...... Call ...... (* ^__ ^ *)

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.