Basic concepts
<font face="新宋体">Node.js</font>
, or Node, is a platform that allows <font face="新宋体">JavaScript</font>
to run on the server side. It can be said that <font face="新宋体">Node.js</font>
pioneered <font face="新宋体">javascript</font>
modular development. The early requirements of <font face="新宋体">javascript</font>
were very simple and were basically written as functions. Then they became process-oriented. Later, object-oriented development ideas were slowly introduced. , and then slowly written into classes. Finally, with the emergence of node.js, the concept of js modular development began to emerge, which eliminated the bloated <font face="新宋体">js</font>
code from a series of development problems such as naming conflicts.
<font face="新宋体">Node</font>
The biggest feature is the use of asynchronous <font face="新宋体">I/O</font>
and event-driven architecture design. <font face="新宋体">Node.js</font>
is a platform that allows js to run outside the browser. Its initial goal is to implement an event-driven, non-blocking <font face="新宋体">I/O</font>
web server
<font face="新宋体">Node.js</font>
is just a <font face="新宋体">JavaScript</font>
runtime environment (or a set of libraries) that adds asynchronous IO to the standard <font face="新宋体">js</font>
, that is, the function of reading and writing networks and files.
A library is nothing more than a tuning API or something. Except for the slightly anti-human event callback, it is not much different from other back-end languages (PHP, Python).
<font face="新宋体">Node.js</font>
uses a single-threaded mode, each thread completes a function, a process can have multiple threads, and uses asynchronous request methods for all I/O. After each asynchronous I/O request is completed, it will be pushed to the event queue and wait for processing by the program process.
In short, the core idea of <font face="新宋体">node</font>
is: non-blocking, single-threaded and event-driven. (Synchronization corresponds to blocking, and asynchronous corresponds to non-blocking)
<font face="新宋体">Node.JS</font>
Architecture diagram
Single thread
<font face="新宋体">javascript</font>
The execution environment of the language is "single thread".
The so-called "single thread" means that only one task can be completed at a time. If there are multiple tasks, they must be queued. After the previous task is completed, the next task will be executed, and so on.
The advantage of this mode is that it is relatively simple to implement and the execution environment is relatively simple; the disadvantage is that as long as one task takes a long time, subsequent tasks must be queued up, which will delay the execution of the entire program. Common browser unresponsiveness (suspended death) is often caused by a certain section of <font face="新宋体">Javascript</font>
code running for a long time (such as an infinite loop), causing the entire page to get stuck in this place and other tasks cannot be performed.
The bottleneck of most web applications is <font face="新宋体">I/O</font>
, that is, reading and writing disk, reading and writing network, and reading and writing database. What strategy to use to wait for this period of time becomes the key point to improve performance
Synchronization and asynchronous
In order to solve this problem, <font face="新宋体">Javascript</font>
the language divides the task execution mode into two types: synchronous (Synchronous) and asynchronous (Asynchronous).
"Synchronous mode" is the mode in the previous paragraph. The latter task waits for the previous task to end before executing it. The execution order of the program is consistent and synchronous with the order of tasks; "asynchronous mode" is completely different. Each task has one or more callback functions (<font face="新宋体">callback</font>
). After the previous task ends, the callback function is executed instead of the next task. The latter task is executed before the previous task ends, so the program The execution order is inconsistent and asynchronous with the order of tasks.
"Asynchronous mode" is very important. On the browser side, long-running operations should be performed asynchronously to avoid the browser becoming unresponsive. The best example is Ajax operations. On the server side, "asynchronous mode" is even the only mode, because the execution environment is single-threaded, and if all <font face="新宋体">http</font>
requests are allowed to be executed synchronously, the server performance will drop drastically and it will become unresponsive very quickly.
Processes and Threads
Processes and threads in mac system
We can see from the picture that a process can include multiple threads. A process is like a workshop in an engineering project, and threads are the workers in this workshop. In operating systems that introduce threads, processes are usually used as allocated resources. The basic unit of threads is the basic unit of independent running and independent scheduling. Since threads are smaller than processes and basically do not own system resources, the overhead for scheduling them will be much smaller, which can more efficiently increase the degree of concurrent execution among multiple programs in the system.
Difference
The difference between threads and processes is that the child process and the parent process have different code and data spaces, while multiple threads share the data space, and each thread has its own execution stack and program counter for its execution context. Multi-threading is mainly to save CPU time and make full use of it, depending on the specific situation. The running of threads requires the use of computer memory resources and CPU.
Modules and Package Modules
Module: A file that implements certain specific functions to achieve modular programming. Introduce the module through require (module name).
—The functions in the module (such as variables, functions) are provided to the caller through a certain attribute assigned to the <font face="新宋体">exports</font>
object.
How to use modules?
It is very convenient to use modules in Node. In the <font face="新宋体">JavaScript</font>
code, you can directly use the global function <font face="新宋体">require()</font>
to load a module. For example, we can use <font face="新宋体">require("http")</font>
to load the http server module that comes with <font face="新宋体">node</font>
,
Pack
Package: A package is a folder that encapsulates modules for release, update, dependency management and version control. Use package.json to describe package information: entry files, dependent external packages, etc. Install the package through the <font face="新宋体">npm install</font>
command and use the package through <font face="新宋体">require</font>
.
Asynchronous I/O and event-driven
The asynchronous mechanism of<font face="新宋体">Node.js</font>
is event-based. Each <font face="新宋体">I/O</font>
is a request. All disk <font face="新宋体">I/O</font>
, network communication, and database queries are requested in a non-blocking manner, and the returned results are generated by the event loop. deal with. As shown below:
<font face="新宋体">Node.js</font>
The process will only process one event at the same time. After completion, it will immediately enter the event loop to check and process subsequent events. The advantage of this is that the CPU and memory are concentrated on one thing at the same time, while time-consuming I/O operations are executed in parallel as much as possible
Start node programming
Here, I recommend everyone to use <font face="新宋体">webstorm</font>
to develop <font face="新宋体">node.js</font>
, which is convenient and fast. It is much easier to use than cmd or the terminal under Mac.
As for the installation of node, you can just Baidu it yourself. I won’t go into details here. Take a look at the node programming interface under <font face="新宋体">webstorm</font>
:
We only need to right-click the node code interface and click Run. It is convenient and fast
The following is the output interface of node:
For web development under the <font face="新宋体">Mac</font>
system, the three tools I recommend everyone to use are: coda2, webstorm and Sublime text3. These are the best development tools I have so far. You might as well try which one suits you better. taste.
To develop node in <font face="新宋体">webstorm</font>
, you need to configure certain files first. You can just Baidu it yourself. Because my <font face="新宋体">webstorm</font>
has already been configured, I can’t take screenshots to show you the steps. The approximate steps are, on mac Under the system, first click <font face="新宋体">webstorm</font>
on the top bar, then click <font face="新宋体">perference</font>
, then click <font face="新宋体">Node.js and NPM</font>
, and then click configure on the right. In the end, it will probably look like this:
<font face="新宋体">windows</font>
The system is similar to this process. The version I am using is 8.0.4.
Global variables
In js programming, it is best to add the var keyword to each variable to avoid polluting the global namespace and increasing the risk of code coupling.
console
<font face="新宋体">console</font>
is used to output characters to the standard output stream <font face="新宋体">standout</font>
(stdout) and the standard error stream (stderr).
<font face="新宋体">console.log()</font>
prints characters to the standard output stream and ends with a newline character. It accepts multiple parameters and will output <font face="新宋体">printf()</font>
in a C-like
<code>console.log(__dirname)输出文件目录</code>
Calculate code running time
<code> console.time(label) console.timeEnd(label)</code>
We just need to give the same label at the beginning and end, and put any code in the middle that you want to calculate the execution time.
<font face="新宋体">__filename</font>
and <font face="新宋体">__dirname</font>
<code> console.log(__filename);// /Users/hwax/Desktop/My Project/avalon/hello.js console.log(__dirname);// /Users/hwax/Desktop/My Project/avalon</code>