search
HomeWeb Front-endJS TutorialDetailed introduction to the basic knowledge about node js

Detailed introduction to the basic knowledge about node js

Jun 26, 2017 pm 01:32 PM
javascriptnodejsFirst acquaintance

Previous words

A few years ago, you might have been hesitant about learning NodeJS, fearing that it would distract from front-end learning. But now, if you don't learn nodeJS, you may not be able to make any progress in front-end learning. The progress of technology is so cruel. When we wait and see about new technologies, the technology has already become popular. This article will introduce the basic knowledge of nodeJS

Language selection

Ryan Dahl is a senior C/C++ programmer. Before creating Node, his main job It's all centered around high-performance web servers. After some attempts and failures, he found several key points for designing high-performance web servers: event-driven, non-blocking I/O, and these are the two major characteristics of nodejs

So Ryan Dahl The original goal was to write a web server based on event-driven, non-blocking I/O to achieve higher performance and provide an alternative to servers such as Apache. When writing Node, Ryan Dahl evaluated C, Lua, Haskell, Ruby and other languages ​​as alternative implementations. He concluded that C has a high development threshold and it is foreseeable that not many developers will be able to use it for daily use. Business development, so abandon it; Ryan Dahl felt that he was not good enough with Haskell, so he abandoned it; Lua itself already contains many blocking I/O libraries, and building a non-blocking I/O library for it cannot change people's continued use of blocking I/O. /O library habit, so it was abandoned; and Ruby’s virtual machine was rejected due to poor performance

In comparison, JavaScript has a lower development threshold than C and has less historical baggage than Lua. Although server-side JavaScript has existed for many years, there has been no market for the back-end part. It can be said that there is zero historical baggage, and there is no additional resistance to importing non-blocking I/O libraries for it. In addition, JavaScript has a wide range of event-driven applications in browsers, which coincides with Ryan Dahl's preference for event-driven needs. At that time, the second browser war was gradually coming to an end, and the Chrome browser's JavaScript engine V8 won the title of No. 1 in performance. Taking into account the three main reasons of high performance, being event-driven, and having no historical baggage, JavaScript became the implementation language of Node

Name

At first, Ryan Dahl said that he His project is web.js, which is a Web server. However, the development of the project has exceeded his original idea of ​​simply developing a Web server and has become a basic framework for building network applications, so that more can be built on it. Things such as servers, clients, command line tools, etc. Node has developed into a single-threaded, single-process system that enforces no sharing of resources. It contains libraries that are very suitable for the network and provides infrastructure for building large-scale distributed applications. Its goal is also to become a platform for building fast and scalable network applications. It itself is very simple. It organizes many Nodes through communication protocols and is very easy to expand to achieve the purpose of building large-scale network applications. Each Node process constitutes a node in this network application, which is the true meaning of its name

Features

As a back-end JavaScript running platform, Node retains the familiar interfaces in front-end browser JavaScript without rewriting any features of the language itself. It is still based on scope and prototype chain. The difference is that it migrates ideas widely used in front-end to the server side. The characteristics of Node compared to other languages ​​are as follows

 1. Asynchronous I/O

In Node, most operations are called asynchronously. Ryan Dahl overcame all difficulties and built many asynchronous I/O APIs at the bottom level, from file reading to network requests, etc. The significance of this is that in Node, we can naturally perform parallel I/O operations from the language level. There is no need to wait for the previous I/O call to complete between each call. The efficiency can be greatly improved in the programming model

Taking the simultaneous execution of two file reading tasks as an example, asynchronous I/O depends on the slowest file reading time, while synchronous I/O The time taken is the sum of the time taken by the two tasks. The advantages brought by asynchronous here are obvious

2. Events

With the advent of the Web 2.0 era, JavaScript has assumed more responsibilities on the front end, and events have also been widely used. Node is not as heavily influenced by Java as Rhino. Instead, it introduces widely used and mature events in front-end browsers into the back-end, cooperates with asynchronous I/O, and exposes event points to business logic

Events The programming method has the advantages of being lightweight, flexible, and focusing only on transaction points. However, in the scenario of multiple asynchronous tasks, events are independent of each other, and how to collaborate is a problem

 3. Callback Function

Compared with other web back-end programming languages, in addition to asynchronous and events, callback functions are a major feature of Node. Looking at it all, callback functions are also the best way to accept data returned by asynchronous calls. However, this programming method may be very unfamiliar to many people who are accustomed to synchronous programming. The order in which the code is written has nothing to do with the order in which it is executed, which may cause reading difficulties for them. In terms of process control, because asynchronous methods and callback functions are interspersed, it becomes less clear-cut compared to the conventional synchronization method

 4. Single thread

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. JavaScript is single-threaded, depending on 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, which has become the core feature of this language

Node maintains the single-threaded characteristics of JavaScript in the browser. And in Node, JavaScript cannot share any state with other threads. The biggest advantage of single-threading is that you don’t have to worry about state synchronization issues like multi-threaded programming. There is no deadlock here, and there is no performance overhead caused by thread context exchange

Similarly, single-threading also has Its own weaknesses include the following three aspects: it cannot take advantage of multi-core CPUs; errors will cause the entire application to exit, and the robustness of the application is worth testing; a large amount of calculations occupy the CPU, making it impossible to continue calling asynchronous I/O

Like browsing JavaScript in the server shares the same thread as the UI. Long-term execution of JavaScript will cause the rendering and response of the UI to be interrupted. In Node, long-term CPU usage will also cause subsequent asynchronous I/O calls to be unable to be made, and the callback function of the completed asynchronous I/O will not be executed in time

HTML5 customizes the Web The standard for Workers, Web Workers can create worker threads to perform calculations to solve the problem of large JavaScript calculations blocking UI rendering. In order not to block the main thread, the working thread delivers the running results through message passing, which also prevents the working thread from accessing the UI

in the main thread. Node adopts the same idea as Web Workers to solve the single-thread problem. Medium and large calculation problem: child_process. The emergence of sub-processes means that Node can calmly deal with the problems of single-threaded robustness and inability to utilize multi-core CPUs. By distributing calculations to individual sub-processes, a large number of calculations can be broken up, and then the results can be communicated through event messages between processes, which can keep the application model simple and low-dependency. Through the Master-Worker management method, each work process can also be well managed to achieve higher robustness

Application scenarios

When making technology selection Before, you need to understand what kind of scenarios a new technology is suitable for. After all, the right technology can have unexpected effects when used in the right scenarios. Regarding Node, the most discussed ones are I/O-intensive and CPU-intensive

 1. I/O-intensive

If all scripting languages ​​are judged in one place , then from a single-threaded perspective, Node's ability to handle I/O is worthy of thumbs up. Generally speaking, there is basically no objection to saying that Node is good at I/O-intensive application scenarios. Node is network-oriented and good at parallel I/O, and can effectively organize more hardware resources to provide more good services

The I/O-intensive advantage mainly lies in the processing capabilities of Node using the event loop. Instead of starting each thread to serve each request, it takes up very little resources

 2. CPU-intensive

From another perspective, can Node be competent in CPU-intensive application scenarios? ? In fact, V8's execution efficiency is very high. Judging by execution efficiency alone, there is no doubt that the execution efficiency of V8 is

The main challenges that CPU-intensive applications bring to Node are: due to the single thread of JavaScript, if there are long-running calculations ( For example, a large loop) will cause the CPU time slice to be unable to be released, making subsequent I/O unable to be initiated. However, proper adjustment and decomposition of large-scale computing tasks into multiple small tasks allows the computing to be released in a timely manner without blocking the initiation of I/O calls. In this way, you can enjoy the advantages of parallel asynchronous I/O and make full use of the CPU

The above is the detailed content of Detailed introduction to the basic knowledge about node js. For more information, please follow other related articles on the PHP Chinese website!

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 Data Types : Is there any difference between Browser and NodeJs?Javascript Data Types : Is there any difference between Browser and NodeJs?May 14, 2025 am 12:15 AM

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScript Comments: A Guide to Using // and /* */JavaScript Comments: A Guide to Using // and /* */May 13, 2025 pm 03:49 PM

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

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 Article

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

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.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor