What is Node?
It is better to try to cover everything when writing something, so I have also taken some basic concepts from the Internet. Some places have changed their understanding of my own. If you have any understanding of these conceptual things, you can choose to skip this paragraph.
1.Node is a server-side JavaScript interpreter, but I really think that students who are good at JavaScript can easily get Node by learning Node, so you are wrong. Summary: I don’t know whether the water is deep or not, but it is indeed not shallow.
2.Node's goal is to help programmers build highly scalable applications and write connection codes that can handle tens of thousands of connections to a physical machine at the same time. Handling high concurrency and asynchronous I/O is one of the reasons why Node has attracted the attention of developers.
3.Node itself runs the Google V8 JavaScript engine, so the speed and performance are very good. You can see it by looking at Chrome. Moreover, while Node encapsulating it, it also improves its ability to process binary data. Therefore, Node not only simply uses V8, but also optimizes it to make it more powerful in various environments. (What is V8 JavaScript engine? Please "Baidu Knows")
4. Third-party extensions and modules play an important role in the use of Node. The following will also introduce downloading npm. npm is the module management tool. Use it to install various Node software packages (such as express, redis, etc.) and publish the software packages you wrote for Node.
Install Node
Here is a brief introduction to installing Node in two environments: Windows 7 and Linux. When installing, you must pay attention to the Python version. The installation failed many times due to problems with the Python version. It is recommended that the 2.6+ version will have Node installation errors. If you query the Python version, you can enter: pyhton -v
1. Let’s first introduce the installation under Linux. Node is very convenient to install and use in Linux environment. It is recommended to run Node under Linux. ^_^...I am using Ubuntu11.04
a. Installation dependency package: 50-100kb/s Each package can be downloaded and installed in one minute.
The code copy is as follows:
sudo apt-get install g++ curl libssl-dev apache2-utils
sudo apt-get install git-core
b. Run the command step by step in the terminal:
The code copy is as follows:
git clone git://github.com/joyent/node.git
cd node
./configure
Make
sudo make install
If the installation is smooth, Node will be successfully installed, and it will take a total of 12 minutes for the 2M network.
Note: If you don’t use git to download the source code, you can download the source code directly, but you need to pay attention to the Node version issue when downloading and installing this way. It is the most convenient to download and install using git, so it is recommended.
2. Use Cygwin to install Node on Windows. This method is not recommended because it really takes a long time and good character. My system is win7 flagship version
Cygwin is a Unix simulation environment running on the Windows platform. The download address is: http://cygwin.com/setup.exe.
After downloading Cygwin, start the installation. Steps:
a. Select the source of download - Install from Internet
b. Select the root directory for download and install
c. Select the directory where the download file is stored
d. Choose the connection method
e. Select the website to download - http://mirrors.163.com/cygwin
f. Trouble is at this step, the time has come to test your character. The required download and installation time is uncertain. Anyway, it takes a long time (more than 20 minutes), and the installation failure occasionally occurs. Click the rotary arrow icon in front of each package to select the version you want. When selected, the "x" sign will appear to indicate that the package has been selected. Select the package you want to download:
The code copy is as follows:Devel package:
gcc-g++: C++ compiler
gcc-mingw-g++: Mingw32 support headers and libraries for GCC C++
gcc4-g++: G++ subpackage
git: Fast Version Control System core files
make: The GNU version of the 'make' utility
openssl-devel: The OpenSSL development environment
pkg-config: A utility used to retrieve information about installed libraries
zlib-devel: The zlib compression/decompression library (development)
Editor package: vim: Vi IMproved enhanced vi editor
Python package: Switch Default to install state
Web Package:
wget: Utility to retrieve files from the WWW via HTTP and FTP
curl: Multi-protocol file transfer command-line tool
Previous screenshot, take downloading zlib-devel as an example:
After a few steps, the environment is completed. However, it is not time to install Node yet. You still need to execute rebaseall in Cywgin's ASH mode. The steps are as follows:
a. cmd command line
b. Enter the bin subdirectory under the cygwin installation directory
c. Run ash to enter shell mode
d. ./rebaseall -v
e. Close the command line window without errors
OK, now it’s time to download and install Node, start Cygwin.exe and enter:
The code copy is as follows:
$ wget http://nodejs.org/dist/node-v0.4.12.tar.gz
$tar xf node-v0.4.12.tar.gz
$ cd node-v0.4.12
$./configure
$ make
$ make install
3.Download node.exe file directly
Go directly to nodejs.org to download. I heard that there are unstable problems, but if you just want to learn about Node in Windows first, I personally feel that this method is much better than installing Cygwin.
Note: I didn't really want to write the paragraph of installing Node, but I still wrote it for the comprehensiveness of this article. I didn't expect it to be so long as I wrote it... It's a coffee table
"Hello World" - Why do I feel a little excited every time I see this sentence, and I am puzzled...
First, create a hello.js file and copy the following code in the file:
The code copy is as follows:
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World/n');
}).listen(1337, "127.0.0.1");
console.log('Server running at http://127.0.0.1:1337/');
Code logic:
a. The global method requires() is used to import modules. Generally, the return value of the require() method is assigned to a variable directly, and this variable is used directly in JavaScript code. require("http") is to load the preset http module of the system
b. http.createServer is a module's method, the purpose is to create and return a new web server object and bind a callback to the service to handle the request.
c. The HTTP server can be listened on a specific port through the http.listen() method.
d. console.log needless to say, those who know firebug should know that Node implements this method.
Note: For specific details, please check the document cnodejs.org/cman/all.html#http.createServer
Then run the Node server, execute the hello.js code, and after successfully starting, you will see the text in console.log(). There are pictures and truth:
Download and use of npm
In addition to the API provided by Node itself, there are now many third-party modules that can greatly improve development efficiency. npm is Node's package manager, which can use it to install the required software packages and publish the software packages written for nodejs. Official website address: npmjs.org
Installation only requires writing one line of code in the terminal:
The code copy is as follows:
curl http://npmjs.org/install.sh | sh
npm installs node extension package with the same line of code:
The code copy is as follows:
npm install <package name> //Example: npm install express
Note: If the domain name error is reported during the installation of the module, please clear the cache > npm cache clean or restart the computer.
Understand the module concept of Node
In Node, different functional components are divided into different modules. The application can choose and use the appropriate module according to its needs. Each module will expose some common methods or attributes. The user of the module can use these methods or attributes directly, and there is no need to understand the internal implementation details. In addition to the API provided by Node itself, developers can also use this mechanism to split applications into multiple modules to improve code reusability.
1. 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.
In the "Hello World" example just now, require("http") can load the system preset http module; the module name starts with "./", such as require("./myModule.js") to load the myModule.js module in the same directory as the current JavaScript file.
2. How to develop modules by yourself?
When I just introduced that when using require() to import a module, the module name starts with "./" is the module file I developed by myself. What you need to pay attention to is the system path of the JS file.
The internal processing logic of the module is encapsulated in the code. A module will generally expose some public methods or attributes for other people to use. The internal code of the module needs to expose these methods or attributes.
3. Let’s take a simple set of examples. First create a module file such as myModule.js, just one line of code
console.log('Hi Darren.')
Then create a test.js file, import this JS file, and execute node to see the results
There are many third-party modules in the Node community now. I hope that more people can join this big family by learning Node and contribute to the Node community. Thank you in advance, let's continue.
4. Take a deeper example. In this example, private and shared will be introduced. First create a myModule.js, the code is as follows:
The code copy is as follows:
var name = "Darren";
this.location = "Beijing";
this.showLog = function(){
console.log('Hi Darren.')
};
There are three types in the code, namely: private attributes, shared attributes and shared methods, and then create a test.js and execute Node
The highlighted area clearly tells us that we cannot get private methods outside the module, so they are undefined. The declaration of shared attributes and shared methods needs to be preceded by the keyword this.
What Node can do and its advantages
Node core ideas: 1. Non-blocking; 2. Single-threaded; 3. Event-driven.
In current web applications, some interactions between the client and the server can be considered event-based, so AJAX is the key to the page's timely response. Every time a request is sent (no matter how small the requested data is), it will go back and forth on the network. The server must respond to this request, usually opening up a new process. Then the more users visit this page, the more requests they will be initiated, and there will be problems such as memory overflow, conflicts caused by logical interleaving, network paralysis, and system crashes.
Node's goal is to provide a solution to build scalable network applications. In the hello world example, the server can handle many client connections at the same time.
Node and the operating system have a convention that if a new link is created, the operating system will notify Node and then go to hibernation. If someone creates a new link, then it (Node) executes a callback, each link taking up only a very small (memory) stack overhead.
Take a simple example of asynchronous calls, prepare test.js and myMydule.js, ^_^. Copy the following code into test.js and execute:
The code copy is as follows:
var fs = require('fs');
fs.readFile('./myModule.js', function (err, data) {
if (err) throw err;
console.log('successfully');
});
console.log('async');
Asynchronous, everyone should be able to think that the runtime will first display "async" and then "successfully".
Node is non-blocking, and when a new request arrives at the server, there is no need to do anything separately for this request. Node is just waiting for the request to occur there and handles the request if there is a request.
Node is better at handling small-sized requests and event-based I/O.
Node is not just a framework for making a web service, it can do more, such as it can do Socket services, for example, file-based, and then based on some examples, there can be child processes, and internally, it is a very complete event mechanism, including some asynchronous non-injection solutions, rather than being limited to the first layer of the network. At the same time, it may, even as a web service, provide more functions that can penetrate into the service kernel and core. For example, the Http Agent used by Node, is that it can penetrate into the service kernel and do some functions.
Node event flow concept
Because Node adopts an event-driven mode, many modules will generate various events, and the module can add event processing methods. All objects that can generate events are instances of the EventEmitter class in the event module. Code is a common language all over the world, so we still use code to speak:
The code copy is as follows:
var events = require("events");
var emitter = new events.EventEmitter();
emitter.on("myEvent", function(msg) {
console.log(msg);
});
emitter.emit("myEvent", "Hello World.");
A brief analysis of this paragraph:
1. Use the require() method to add events module and assign the return value to a variable
2. The new events.EventEmitter() sentence creates an event trigger, which is the so-called instance of the EventEmitter class in the event module.
3. on(event, listener) is used to add event handler to an event event event
4. The emit(event, [arg1], [arg2], [...]) method is used to generate events. Each listener function in the listener list is executed sequentially with the provided parameters as parameters of the listener function.
The methods in the EventEmitter class are related to the generation and processing of events:
1. AddListener(event, listener) and on(event, listener) are both methods that add a listener to the end of the listener array of the specified event.
2. once(event, listener) This method adds a one-time listener for events. The listener is executed when the event is fired for the first time and will be removed afterwards
3. removeListener(event, listener) This method is used to remove the listener from the listener array of the specified event.
4. emit(event, [arg1], [arg2], [...]) Just mentioned.
In Node, there are various different data streams, and Stream is an abstract interface implemented by different objects. For example, the request to request an HTTP server is a stream, similar to stdout (standard output); including file system, HTTP requests and responses, and TCP/UDP connections. The stream can be readable, writable, or both readable and writable. All streams are instances of EventEmitter, so various events can be generated.
A readable stream mainly produces the following events:
1.data This event is triggered when data in the stream is read.
2.end When there is no data in the stream to be read, this event is triggered
3.error This event is triggered when an error occurs when reading data.
4.close When the stream is closed, this event is triggered, but not all streams will trigger this event. (For example, an HTTP request stream incoming in a connection will not trigger the 'close' event.)
There is also a more special fd event, which is triggered when a file descriptor is received in the stream. Only UNIX streams support this feature, and no other types of streams will trigger this event.
Related detailed documentation: http://cnodejs.org/cman/all.html#events_
Powerful File System File System Module
The fs module in Node is used to operate on the local file system. The I/O of the file is encapsulated by the standard POSIX function. This module needs to be accessed using require('fs'). All methods provide asynchronous and synchronous methods.
The methods provided in the fs module can be used to perform basic file operations, including reading, writing, renaming, creating and deleting directories, and obtaining file metadata. Each method of operating files has two versions: synchronous and asynchronous versions.
Versions of asynchronous operations will use a callback method as the last parameter. When the operation is completed, the callback method will be called. The first parameter of the callback method is always reserved as an exception that may occur during operation. If the operation is correct and successful, the value of the first parameter is null or undefined.
The method name of the synchronous operation version is to add a Sync as the suffix after the corresponding asynchronous method. For example, the synchronous version of the asynchronous rename() method is renameSync(). The following lists some common methods in the fs module, and only introduces the version of asynchronous operation.
Are the test.js and myModule.js files ready? Copy the following code into test.js once
The code copy is as follows: var fs = require('fs');fs.unlink('./myModule.js', function (err) {
if (err) throw err;
console.log('successfully deleted myModule.js');
});
If there is no error, then myModule.js will be deleted. It's that simple
This is just a simple example. If you are interested, try it yourself and practice the truth. Due to space reasons, I won't give many examples. ^_^
A summary of learning Node:
1. For me, who has almost zero knowledge on Linux commands and shells, I have learned a lot of knowledge about Linux during this period. Vim is really a powerful editor, and it feels really good to not use a mouse; and one thing is very important to me. Programming under Linux is very cool, especially in the team, which is used to install healthier^_^.
2. Understand a successful framework for server-side JavaScript - Node, as well as some of its advantages and usage, this article is the best summary, of course, this will only be the beginning.
Some things to say to everyone:
1. I have to hit some people’s enthusiasm here. If you don’t know enough about backend technology or have never been exposed to server language, don’t know about I/O, and do not have the concept of backend processing flow, then...Node is not a server-side technology suitable for entry-level. Why do you say so:
a. The key point is that there are few examples and articles in Chinese, so it will be more troublesome to learn systematically, so there is always an immature feeling during use, of course, it is mainly caused by my unfamiliarity with it. There are indeed not many companies using Node in China, and of course there are still many abroad. I took a picture from cnodejs.org:
3. I actually have some regrets about not entering a company that dreams about, but life should be like this, with ups and downs, which is exactly what I need and expect... Then, I still have to continue my new life, be your own helmsman, grasp your own direction, and let it pass what is past.
b. For inexperienced friends, node is not easy to get started. It can be seen from the simplest "Hello world" (the understanding of various operating environments and installation details takes some effort). Do not compare the jQuery library. The things handled are different and the learning costs are also different. Therefore, it is not recommended to be a server-side technology for beginners. If you want to learn a server-side language PHP and Python, it is good choice, because: there are many books, examples, multiple frameworks, and many hands-on, simple and easy to understand and build...
c.The above are my personal kind suggestions. Due to my limited level, please give me some advice and hope to be merciless.
2. I am not ugly about Node writing standards and specific skills. I don’t have much code to write Node myself, but the object-oriented programming idea is good everywhere.
3. I hope this article will be useful for everyone to learn Node