Basic concepts
Node.js , or Node, is a platform that allows JavaScript to run on the server side. It can be said that Node.js pioneered the modular development of javascript . The early javascript requirements were very simple, and they were basically written as functions, followed by process-oriented writing. Later, object-oriented development ideas were gradually introduced, and then they were slowly written into classes. Finally, the emergence of node.js began to have the concept of js modular development, which eliminated the bloated js code such as naming conflicts and other development problems.
The biggest feature Node is its adoption of asynchronous I/O and event-driven architectural design. Node.js is a platform that allows js to run outside the browser. Its initial goal is to implement event-driven, non-blocking I/O web servers
Node.js is just a JavaScript running environment (or a set of libraries), which supplements the standard js with the functions of asynchronous IO, that is, reading and writing networks and files.
As a library, it is nothing more than a tune API. In addition to slightly anti-human event callbacks, it is not much different from other back-end languages (PHP, Python).
Node.js uses a single thread mode. Each thread completes a function. A process can have multiple threads. All I/Os are used in an asynchronous request method. After each asynchronous I/O request is completed, it will be pushed to the event queue and wait for the program process to process.
In short, the core idea of node is: non-blocking, single-threaded and event-driven. (Synchronous corresponds to blocking, asynchronous corresponds to non-blocking)
Node.JS architecture diagram
Single threaded
The execution environment of the javascript language is "single thread".
The so-called "single thread" means that one task can only be completed at a time. If there are multiple tasks, you must queue up, complete the previous task, execute the next task, and so on.
The advantage of this model is that it is relatively simple to implement and the execution environment is relatively simple; the disadvantage is that as long as there is a task that takes a long time, the subsequent tasks must be queued up, which will delay the execution of the entire program. Common browsers are unresponsive (fake death) often because a certain piece of Javascript code runs for a long time (such as a dead loop), causing the entire page to be stuck in this place and other tasks cannot be executed.
The bottlenecks of most web applications are in I/O , that is, read and write disks, read and write networks, and read and write databases. What strategy to use to wait for this period of time has become the key point to improve performance
Synchronous and asynchronous
To solve this problem, Javascript language divides the execution mode of tasks into two types: Synchronous (Synchronous) and Asynchronous (Asynchronous).
"Synchronous mode" is the mode of the previous section. The latter task waits for the previous task to end and then executes. The execution order of the program is consistent and synchronous with the arrangement order of the tasks; the "asynchronous mode" is completely different. Each task has one or more callback functions ( callback ). After the previous task is over, it is not the next task, but the callback function is executed. The latter task is executed without waiting for the previous task to end, so the execution order of the program is inconsistent and asynchronous with the arrangement order of the tasks.
"Async mode" is very important. On the browser side, long-term operations should be executed asynchronously to avoid the browser from losing response. The best example is Ajax operations. On the server side, "asynchronous mode" is even the only mode, because the execution environment is single-threaded, if all http requests are allowed to be executed synchronously, the server performance will drop sharply and will soon lose its response.
Processes and threads
Processes and threads in mac system
From the figure, we can see that a process can include multiple threads. Processes are like workshops in projects. Threads are workers in this workshop. In the operating system that introduces threads, they usually use processes as the basic unit for allocating resources, and threads as the basic unit for independent operation and independent scheduling. Since threads are smaller than processes and basically do not own system resources, the overhead of scheduling will be much smaller, which can more efficiently improve the degree of concurrent execution between multiple programs in the system.
the difference
The difference between a thread and a process is that the child process and the parent process have different code and data spaces, while multiple threads share data spaces, each thread has its own execution stack and program counter for its execution context. Multithreading is mainly used to save CPU time and use it according to the specific situation. The computer's memory resources and CPU are required to be used during the running of a thread.
Modules and Package Modules
Module: A file that implements certain specific functions to implement modular programming. Introduce modules through require (module name).
― Functions in modules (such as variables, functions) are provided to the caller by assigning a property to the exports object.
How to use modules?
It is very convenient to use modules in Node. In JavaScript code, you can directly use the global function require() to load a module. For example, we can use require("http") to load the http server module that comes with node .
Bag
Package: A package is a folder that encapsulates modules for release, update, dependency management, and version control. Describe package information through package.json: entry files, dependency external packages, etc. Install the package through the npm install command and use the package through require .
Asynchronous I/O and event-driven
Node.js ' asynchronous mechanism is event-based. Each I/O is a request. All disk I/O , network communication, and database queries are requested in a non-blocking manner. The returned results are processed by the event loop. As shown in the figure below:
The Node.js process will only process one event at the same time, and immediately enter the event loop to check and process the subsequent events after completion. The advantage of this is that the CPU and memory exist at the same time to centralize one thing while allowing time-consuming I/O operations to be executed in parallel as much as possible
Start node programming
Here, I recommend that you use webstorm for node.js development, which is convenient and fast, and is much easier to use than cmd or terminals under Mac.
As for the node installation, please Baidu on your own. I won’t go into details here. Let’s take a look at the node programming interface under webstorm :
We just need to right-click the written node code interface and click Run, which is convenient and fast
The following is the output interface of node:
In Mac system, I recommend the three tools I use: coda2, webstorm and Sublime text3. These are the best development tools I have so far. You might as well try which one is more in line with your taste.
For node development in webstorm , you need to configure certain files first. Everyone should use Baidu to do it. Because my webstorm has been configured, I can't take a screenshot to show you the steps. The general steps are: Under the mac system, first click webstorm in the top bar, then click perference , then click Node.js and NPM , then click configure on the right side, and finally it will look like the following:
The steps of the process under windows system are roughly similar to this process. The version I use 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
console is used to output characters to the standard output stream standout (stdout) and standard error stream (stderr).
console.log() prints characters to the standard output stream and ends with a newline, which accepts multiple parameters and will be output in C-like printf() format
console.log(__dirname)输出文件目录Calculate code running time
console.time(label) console.timeEnd(label)We just need to give the same label at the beginning and end, and put any code you want to calculate the execution time in the middle.
__filename and __dirname
console.log(__filename);// /Users/hwax/Desktop/My Project/avalon/hello.js console.log(__dirname);// /Users/hwax/Desktop/My Project/avalon