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
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.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The Evolution of JavaScript: Current Trends and Future ProspectsThe Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.