Node. js Study Notes (1)-Node basics, node. jsnode
Welcome to reprint, but please indicate the source: http://blog.csdn.net/sysuzjz/article/details/43968787
Node. js literacy names Node. js include Node, Nodejs, and NodeJS. Node is used more frequently for convenience. Why is it named "Node? In the beginning, the Creator Ryan Dahl called web. js to build a web server. But later, projects grew faster and faster. Beyond the idea of a single web server, it became the basic framework for building network applications. More things can be built on the framework, such as servers, clients, and command line tools. It is like a Node that forms various network applications. Therefore, it is called a Node.
As the most popular background language recently, Node has frequently entered our sights. But just as some people have been confused about the relationship between Java and JavaScript, many people have many misunderstandings about Node. For example:
- Node must have been drummed up by several front-end engineers in the lab.
- What's interesting about backend for the sake of backend?
- How can I create a new language?
- JavaScript takes too much responsibility.
- Intuitively, JavaScript should not run on the backend
- The front-end engineer is about to attack back.
In fact, JavaScript running in the background is not the first case. At the beginning, Netscape began to try to use it on the backend. Microsoft also learned the same thing. This is the scripting language used in ASP. However, when JavaScript was used as a back-end language, its performance was not comparable to that of Java and PHP, so it gradually fell out of sight. Now, the advantages of V8 engine, real-time, and high concurrency make Node popular. The features of asynchronous I/OIO consume a lot of time and performance. As we all know, JavaScript is single-threaded. If I/O causes blocking, the performance will be greatly compromised. So asynchronous I/O came into being. IO is independent from the main thread and only performs callback after IO is completed. The effect is similar to ajax. For example:
Var fs = require ("js"); fs. readFile ("/path", function (err, file) {console. log ("read completed") ;}); console. log ("initiate read ");The execution sequence is as follows: start to read the file, output "initiate read", read complete, and output "read complete ". It is unknown when the callback is executed. We only know that the callback will be executed after the IO is executed. This is a typical non-relational process that only cares about the results. Event-driven DOM events are believed to be clear to everyone who has written the front-end. After the event is bound, the callback function can be executed as long as the event is triggered. This approach is very efficient, because we do not need to wait for the idling, or we have handed over the idling wait to the lower layer for implementation. We can use the following example to illustrate that this example is generally used to process data submitted by forms.
var http = require("http");http.createServer(function(request, response) { var postData = ""; request.on("data", function(trunk) { postData += trunk; }) request.on("end", function() { response.end(postData); })})We add data events and end events to the request object separately. The former is because the form is submitted multiple times each time. The latter means that the submission is complete and the received form items are output. Event-driven systems are lightweight, loosely coupled, and focus only on transaction points. Single thread
JavaScript is single-threaded, and Node is also single-threaded. In Node, JavaScript cannot share any State with other threads. The biggest benefit of a single thread is that you don't have to worry about State synchronization everywhere like multi-thread programming. In general, there will be no deadlocks, and there will be no performance overhead caused by thread context switching. Weak Current also exists, with the following three aspects:
- Multi-core CPU cannot be used
- The error will cause the entire application to exit, and the robustness of the application is worthy of further study.
- The asynchronous I/O cannot be called because a large number of computing resources occupy the CPU.
To solve these problems, Node adopts a compromise: Enable a dedicated and completely independent process for a large amount of computing, and then pass the running results through message transmission. This is child_process. The idea is the same as that of HTML5 Web Workers.
The cross-platform Node can only run in Linux at the beginning, and then reached an agreement with Microsoft to achieve compatibility with the Windows platform. Currently, most mainstream platforms support Node perfectly. To install and deploy Node in windows, download and install it on the official website: Download link. In windows, node comes with npm, which can be used to install various modules and check whether node is successfully installed:
node -v
Npm installation module: the installation of express is used as an example: (-g indicates global installation)
npm install express -g
In linux, run sudo apt-get install nodejs directly.
Other systems have not been tested. You are welcome to test them by yourself and give the results a comment.
The first Node program, the first program in each programming language, is "hello world". We should not make any exception this time. Node. js is followed by JS first, so we should first create a new. js file: server. js, and enter the following code in it:
var http = require("http");http.createServer(function(request, response) { response.writeHead(200, {"Content-Type": "text/plain"}); response.write("Hello World"); response.end();}).listen(8888);The require in the first line is similar to the import in python. It introduces new modules. The difference is that an object is returned after Node is introduced. By default, we use the module name to name the module object. Of course, we can also replace it with another name, for example:
<pre name="code" class="javascript">var foo = require("http");foo.createServer(function(request, response) { response.writeHead(200, {"Content-Type": "text/plain"}); response.write("Hello World"); response.end();}).listen(8888);
This is fine, but the first naming method is recommended here. The server creation method is to call the createServer method of the http module. The parameters are a function and the parameters of the function are request and response. The result returned by this method is still an object. The chained operation is supported, followed by the listening port number. When running the server, we first enter the directory where the js file is located and run node server. then open localhost: 8888 in the browser. We will find that "Hello World" is displayed in the browser and the server is enabled successfully.