Initial Nodejs, nodejs

Source: Internet
Author: User

Initial Nodejs, nodejs

Basic Concepts

Node.jsOr Node isJavaScriptRun on the server platform. It can be said that,Node.jsCreatedjavascriptModular development first, earlyjavascriptThe requirements are very simple. They are basically written as functions, followed by process-oriented writing. Later, we gradually introduced the idea of object-oriented development, and then began to write classes. Finally, the emergence of node. js began to have the idea of js modular development, which makes the bloatedjsThe Code eliminates a series of development challenges such as naming conflicts.

NodeThe most important feature is the asynchronousI/OAnd event-driven architecture design.Node.jsIs a platform that allows js to run outside the browser. Its initial goal was to implement event-driven, non-blockingI/OWeb Server

Node.jsOnly oneJavaScriptThe running environment (or a group of databases) of is the standardjsAdded the asynchronous IO, that is, the ability to read and write networks and files.
A library is nothing more than calling APIs. In addition to slightly anti-human event callbacks, it is not much different from other backend languages (PHP and Python.

Node.jsThe single-thread mode is used. Each thread completes a function. A process can have multiple threads, and all I/O requests are asynchronous. After each asynchronous I/O request is complete, it is pushed to the event queue, waiting for the program process to process.

In short,nodeThe core idea is: non-blocking, single-thread, and event-driven. (Synchronization corresponds to blocking, while asynchronous corresponds to non-blocking)

Node.JSArchitecture

Single thread

javascriptThe execution environment of the language is "single thread ).
A single thread means that only one task can be completed at a time. If there are multiple tasks, you must queue up, complete the previous task, and then execute the next task, and so on.

The advantage of this mode is that the implementation is relatively simple, and the execution environment is relatively simple. The disadvantage is that as long as one task takes a long time, the subsequent tasks must be waiting in queue, which will delay the execution of the entire program. Common browsers do not respond (false), often becauseJavascriptIf the code runs for a long time (such as an endless loop), the entire page is stuck in this place and other tasks cannot be executed.

Most Web applications have bottlenecksI/OThat is, read/write disks, read/write networks, and read/write databases. What policies are used to wait for this period of time has become a key point to improve performance

Synchronous and asynchronous

To solve this problem,JavascriptThe language divides the execution mode of a task into two types: Synchronous and Asynchronous ).

"Synchronization mode" is the mode of the previous section. The latter task is waiting for the previous task to end and then executed. The execution sequence of the program is consistent with the task arrangement order; asynchronous mode is completely different. Each task has one or more callback functions (callback). After the previous task is completed, the callback function is executed instead of the last task. The latter task is executed without the end of the previous task, therefore, the execution sequence of the program is asynchronous and inconsistent with the task arrangement order.

"Asynchronous mode" is very important. On the browser side, all the operations that take a long time should be executed asynchronously to avoid the browser's loss of response. The best example is Ajax operations. On the server side, the "asynchronous mode" is even the only mode, because the execution environment is single-threaded, if you allow synchronous execution of allhttpRequests, server performance will drop sharply, and response will soon be lost.

Processes and threads

Processes and threads in mac system

We can see that a process can contain multiple threads. A process is like a workshop in a project. A thread is a worker in the workshop. In the operating system that introduces threads, generally, processes are used as the basic unit for resource allocation, while threads are used as the basic unit for independent operation and scheduling. Because a thread is smaller than a process and basically does not have system resources, the overhead for scheduling is much smaller, it can improve the degree of concurrent execution among multiple programs in the system more efficiently.

Differences

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 the data space, each thread has its own execution stack and program counter for its execution context. Multithreading is mainly used to save CPU time and make full use of it, depending on the specific situation. The computer's memory resources and CPU need to be used during thread running.

Module and Package Module

Module: a file that implements certain functions to implement Modular programming. Use require (Module name) to introduce the module.
-Functions in the module (such as variables and functions) are assignedexportsAn attribute of an object is provided to the caller.

How to Use modules?

It is very convenient to use modules in Node.JavaScriptYou can directly use global functions in the code.require()To load a module. For example, we can userequire("http")To loadnodeSelf-contained http server module,

Package

Package: a package is a folder that encapsulates modules for release, update, dependency management, and version control. Package. json is used to describe the package information: the entry file, the dependent external package, and so on. Passnpm installCommand to install the package, andrequireUse package.

Asynchronous I/O and event-driven

Node.jsThe asynchronous mechanism of is event-based.I/OIs a request, all disksI/ONetwork Communication and database query are all requests in non-blocking mode, and the returned results are processed by the event loop. As shown in:

Node.jsA process processes only one event at a time. After completing the process, it immediately enters the event loop check and processes subsequent events. The advantage of doing so is that the CPU and the memory have the same time to process one thing in a centralized manner, and try to make time-consuming I/O operations run in parallel as much as possible.

Start node Programming

I recommend that you usewebstormProceednode.jsIt is convenient and quick to develop. It is much easier to use than cmd or Mac terminals.

As for node installation, you should go to Baidu. I will not go into details here. Let's take a look.webstormThe node programming interface below:
We just need to right-click the node Code interface and click Run. It's convenient and quick.

Below is the node output interface:

InMacFor web development in the system, we recommend that you use three tools: coda2, webstorm, and Sublime text3, which are currently my best development tools, you may try which one suits your taste better.

InwebstormFor node development, you need to configure certain files first. Baidu is your choice, because mywebstormThe configuration is complete, so you cannot see the steps. The general step is to click the top column in the mac system.webstormAnd then clickperferenceAnd then clickNode.js and NPMClick configure configuration on the right side, and the configuration will look like the following:

windowsThe process steps in the system are similar. The version I used is 8.0.4.

Global Variables

In js programming, we 'd better add the var keyword to each variable to avoid contamination of the global namespace and increase the risk of code coupling.

Console

consoleUsed to output streams to the standardstandout(Stdout) and stderr output characters.

console.log()Print characters to the standard output stream and end with a line break. It accepts multiple parameters and usesprintf()Format output

Console. log (_ dirname) output file directory

Calculate the code running time

 console.time(label) console.timeEnd(label)

We only need to give the same tag at the beginning and end, and place any code in the middle that you want to calculate the execution time.

__filenameAnd__dirname

 console.log(__filename);// /Users/hwax/Desktop/My Project/avalon/hello.js console.log(__dirname);// /Users/hwax/Desktop/My Project/avalon

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.