search
HomeWeb Front-endJS TutorialWhy Nodejs chooses JavaScript as the carrier language_node.js

Let’s first take a look at the introduction on the NodeJS official website:

Its characteristics are:

1. It is a Javascript running environment

2. Rely on Chrome V8 engine for code interpretation

 3. Event-driven

 4. Non-blocking I/O

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

6. Single process, single thread

(1), why Nodejs chooses JavaScript as the carrier language

In fact, when implementing Node.js, the author Ryan Dahl did not choose JavaScript. He tried C and Lua, but they lacked the features of some high-level languages, such as closures and functional programming, making the program complicated. , difficult to maintain.

  JavaScript is a language that supports the functional programming paradigm and fits well with the event-driven programming model of Node.js. Coupled with the V8 engine provided by Google, the execution speed of the JavaScript language is greatly improved.

What is finally presented to us is Node.js, not Node.c, Node.lua or other language implementations.

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

When seeing the name Node.js, beginners may mistakenly think that it is a Javascript application. In fact, Node.js is written in C language and is a Javascript running environment.

Node.js uses the V8 engine of the Google Chrome browser, which has very good performance and also provides many system-level APIs, such as file operations, network programming, etc.

The following are all modules involved in NodeJS:

 

The Javascript code on the browser side will be subject to various security restrictions when running, and has limited operations on the customer system.

In contrast, Node.js is a comprehensive background runtime that provides Javascript with many functions that other languages ​​can achieve.

(3), Features of Node.js

Node.js is also relatively innovative in design. It runs in single-process, single-thread mode (this is consistent with the way Javascript runs),

The event-driven mechanism is implemented by Node.js through an internal single thread to efficiently maintain the event loop queue. There is no multi-threaded resource occupation and context switching. This means that in the face of large-scale http requests, Node.js relies on Event-driven takes care of everything,

Web service developers who are used to traditional languages ​​may be very familiar with multi-threaded concurrency and collaboration, but when faced with Node.js, we need to accept and understand its characteristics.

2. Important concepts

1. What is Event Loop? (very important concept)

Event Loop is a very important concept, which refers to an operating mechanism of a computer system.

If you want to understand Event Loop, you must start with the running mode of the program. The program after running is called a process. Generally, a process can only perform one task at a time.

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

(1), line up. Because a process can only execute one task at a time, it has to wait until the previous task is completed before executing the subsequent task.

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

(3), create a new thread. Because processes consume too many resources, today's programs often allow a process to contain multiple threads, and the threads complete tasks.

Take the JavaScript language as an example. It is a single-threaded language, and all tasks are completed on one thread, that is, the first method above is used. Once a large number of tasks are encountered or a time-consuming task is encountered, the web page will appear "suspended" because JavaScript cannot stop and cannot respond to the user's behavior.

You may ask, why is JavaScript single-threaded? Can’t it be implemented as multi-threaded?

This has something to do with history:

A major feature of the JavaScript language is that it is single-threaded, which means that it can only do one thing at a time. So why can't JavaScript have multiple threads? This can improve efficiency.

JavaScript’s single thread is related to its purpose. As a browser scripting language, JavaScript's main purpose is to interact with users and manipulate the DOM. This determines that it can only be single-threaded, otherwise it will cause very complex synchronization problems.

For example, suppose JavaScript has two threads at the same time. One thread adds content to a certain DOM node, and the other thread deletes the node. In this case, which thread should the browser use?

Therefore, in order to avoid complexity, JavaScript has been single-threaded since its birth. This has become the core feature of this language and will not change in the future.

In order to take advantage of the computing power of multi-core CPUs, HTML5 proposes the Web Worker standard, which allows JavaScript scripts to create multiple threads, but the child threads are completely controlled by the main thread and must not operate the DOM.
Therefore, this new standard does not change the single-threaded nature of JavaScript.

Return to EventLoop:

Single thread means that all tasks need to be queued, and the next task will not be executed until the previous task is completed. If the previous task takes a long time, the next task will have to wait.

If the queue is due to a large amount of calculation and the CPU is too busy, forget it, but many times the CPU is idle because the IO device (input and output device) is very slow (such as Ajax operations to read data from the network) , I have to wait for the results to come out before proceeding.

The designers of the JavaScript language realized that at this time, the main thread can completely ignore the IO device, suspend the waiting tasks, and run the later tasks first. Wait until the IO device returns the result, then go back and continue executing the suspended task.

Therefore, all tasks can be divided into two types, one is synchronous task (synchronous) and the other is asynchronous task (asynchronous). Synchronous tasks refer to tasks queued for execution on the main thread. Only the previous task has been executed.

Only the latter task can be executed; asynchronous tasks refer to tasks that do not enter the main thread but enter the "task queue". Only the "task queue" notifies the main thread that an asynchronous task can be executed. The task will then enter the main thread for execution.

As shown below:

  

As long as the main thread is empty, it will read the "task queue". This is the running mechanism of JavaScript. This process keeps repeating.

3. Example explanation

Okay, no more "nonsense", let's start our first NodeJS application: "Hello Big Bear".

Open your favorite editor and create a HelloWorld.js file.

The code is as follows:

Copy code 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, execute your script with Node.js:

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

Next, open the browser and visit http://localhost:8888/, you will see a webpage that says "Hello, Big Bear!"

A little expanded knowledge:

As shown in the figure below, this is part of the source code of http.js in NodeJS. createServer is a very user-friendly interface. The internal implementation adopts the singleton mode. The advantage of this is that the creation and initialization tasks of the instance are Effective separation, dedicated responsibilities, and reduced coupling are ideas that everyone can learn from when programming.

 

Hahaha, isn’t it very interesting? This is just a short experience. Many knowledge points will be explained later. Everyone will slowly understand O(∩_∩)O haha~

4. General Overview

1. It is a Javascript running environment

2. Rely on Chrome V8 engine for code interpretation

 3. Event-driven

 4. Non-blocking I/O

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

6. Single process, single thread

The last thing I want to say is: There are not many examples in this article, but these concepts are very important. You must have a clear understanding. This will lay a solid foundation for future NodeJS learning. Friends, come on and work hard together.

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

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.