Preface: The origin of writing this article:
1. A period of time before the unit has a new project to start, the server to do the work is not too much trouble, is to deal with a number of middle-tier services, and all of our team will be JavaScript, the leadership decided to try the server-side JavaScript, the result I was fortunate to be sent to study With chicken frozen mood began node.js chapter, this article is the summary of the study for these days.
2. A JavaScript engineer If you have not heard node.js then I think you are missing something, every good front-end engineers need to understand the background processing process, then if you can start from JavaScript, it is not a wonderful thing.
3. The heat of the internet makes the JavaScript scenery Infinite, and the service-side JavaScript is not a new technology, the relevant framework has many, Just Node.js's success allowed him to burst out of sight, allowing many front-end engineers to see another hope for implementation from the front end to the back end. Note: Node.js is a framework that allows developers to write server-side code using the JavaScript language.
4. In August this year the last round of a major company (fifth round) interview was asked Node.js question, the corresponding answer that is quite bad, the results how you understand, feel that this problem is a key to not pass the point ... That company is when I was in college in the very yearning for the company, now recall that experience and process, no regrets, after all, I really try to-in fact this article is more in order to complete their own a small heart knot ... Well, it's a long way off.
5. Welcome all kinds of reprint, but please indicate the source, thank you.
What's node?
Write a thing or try to be as comprehensive as possible, so the basic concept of things I also from the Internet selectively took some, some places for their own understanding of the changes, the concept of these things have to know the choice to skip this paragraph.
1.Node is a server-side JavaScript interpreter, but really think JavaScript good students learn Node can easily take off, then you are wrong, summed up: the depth is not deep I do not know, but really not shallow.
The goal of 2.Node is to help programmers build highly scalable applications and write connection codes that handle tens of thousands of simultaneous connections to one physical machine. Handling high concurrency and asynchronous I/O is one of the reasons that node is concerned by developers.
3.Node itself runs Google V8 JavaScript engine, so the speed and performance is very good, see Chrome, and Node to its encapsulation also improved its ability to process binary data. Therefore, node not only uses V8, but also optimizes it to make it more power in various environments. (What is a V8 JavaScript engine?) Please "Baidu know")
4. Third-party extensions and modules play an important role in the use of node. The download NPM,NPM is the management tool for the module, which installs various node packages (such as Express,redis, etc.) and publishes the packages that you write for node.
Installing node
In this simple way, you install node in the WINDOW7 and Linux two environments. The installation must pay attention to the Python version, many times because of the Python version of the problem installation failed, recommended 2.6+ version, a low version of node installation error, query Python version can be entered in the terminal: Pyhton-v
1. First introduce the installation under Linux, node in the Linux environment is very convenient to install and use, it is recommended to run the node in Linux, ^_^ ... I'm using a Ubuntu11.04.
A. Installing the dependency pack: 50-100kb/s about a minute of each package can be downloaded and installed complete
sudo apt-get install g++ curl libssl-dev apache2-utils
sudo apt-get install Git-core
B. Run the command one step at a terminal:
git clone git://github.com/joyent/node.git
cd node
./configure
make
sudo make install
If the installation is successful, the 2M network uses a total of 12 minutes.
Note: You can download the source code without git download, but you need to be aware of the node version problem with this download installation. Using Git to download the installation is the most convenient, so recommend it.
2. Using Cygwin to install node under Windows is not recommended in this way because it really takes a long time and a good character. My system is the Win7 flagship version.
Cygwin is a UNIX simulation environment running on a Windows platform, download address: Http://cygwin.com/setup.exe.
Download the Cygwin and start the installation process:
A. Select the source of the download-Install from Internet
B. Select the root directory of the download installation
C. Select the directory where the download file is stored
D. How to select a connection
E. Select the downloaded Web site-http://mirrors.163.com/cygwin
F. Trouble at this step, the time to test the character. The required download installation time is uncertain, but it takes a long time (more than 20 minutes), and occasionally an installation failure occurs. Click the rotate arrow icon in front of each package to select the version you want, and the "X" number appears when selected to indicate that the package is already selected. Select the package you want to download:
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
The last screenshot to download Zlib-devel for example:
It takes a few steps to complete the environment, but it is not yet up to the installation node to perform the Rebaseall in Cywgin ash mode, as follows:
A. cmd command line
B. Access to the bin subdirectory under the Cygwin installation directory
C. Run ash into shell mode
D./rebaseall-v
E. Close the Command line window without errors
OK, now to download the install node, start Cygwin.exe and enter:
$ 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
nodejs.org download slower so I uploaded one on the net, download the address: http://www.everbox.com/f/VhyL6EiGF5Lm3ZSRx85caFDIA5
I hear there's a problem with instability, but if you just want to get to know node in Windows first, it's a lot better for you to feel this way than you cygwin.
Note: Originally do not want to write installation node this paragraph, but for this article is comprehensive or wrote, did not think that a write is so long ... Tea table.
"Hello World"-Why every time I see this mood will be small excited, puzzled ...
First, create a hello.js file, and copy the following code in the file:
var http = require (' http ');
Http.createserver (function (req, res) {
res.writehead ({' 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. Global method require () is used to import modules, and generally directly assign the return value of the Require () method to a variable, which can be used directly in JavaScript code. Require ("http") is the HTTP module that loads system presets
B. Http.createserver is a modular approach to creating and returning a new Web server object and binding a callback to the service to process the request.
C. The HTTP server can be monitored on a specific port through the Http.listen () method.
D. Console.log Needless to say, understand the firebug should know, node to achieve this method.
Note: Please check the documentation for details Cnodejs.org/cman/all.html#http.createserver
Then run the node server, execute the hello.js code, and the successful launch will see the text in Console.log (). There is a picture of the truth:
The download and use of NPM
With the exception of the API provided by node itself, there are now a number of third-party modules that can greatly improve development efficiency, and NPM is the node's Package manager that can use it to install the required packages and publish its own software packages written for Nodejs. Website address: npmjs.org
Installation requires only one line of code to be written to the terminal:
Copy Code code as follows:
Curl Http://npmjs.org/install.sh | Sh
The NPM Installation node expansion pack is also a line of code:
Copy Code code as follows:
NPM Install < package name >
Example: NPM Install Express
Note: If the process of installing the module reported a domain name error, please empty the cache >npm cached clean or restart the computer.
Understand node's module concepts
In node, different functional components are divided into different modules. Applications can choose to use the appropriate modules according to their own needs. Each module exposes some common methods or properties. The user of the module can use these methods or attributes directly, and the internal implementation details are not understood. In addition to the APIs provided by node itself, developers can use this mechanism to split applications into multiple modules to improve the reusability of the code.
1. How to use the module?
Using modules in node is convenient, and you can use the global function require () to load a module directly in JavaScript code.
In the "Hello World" example, require ("http") can load the HTTP module of the system preset, and the module name starts with "./", such as require ("./mymodule.js") to load the current JavaScript The Mymodule.js module in the same directory as the file.
2. How to develop your own module?
When you first introduced the module with require (), the module name starts with "./", which is the module file that you developed. Need to pay attention to is the JS file system path.
The code encapsulates the internal processing logic of the module, and a module typically exposes some publicly available methods or properties to others. The internal code of the module needs to expose these methods or attributes.
3. Come to a set of simple 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, execute node to see the results
There are already a number of third-party modules in the node community, hoping that more people will be able to join the family by learning node to contribute to the node community. Thank you first, let's go on.
4. Come to a deep point example. This example will be introduced for both private and shared. First create a mymodule.js with the following code:
var name = "Darren";
This.location = "Beijing";
This.showlog = function () {
console.log (' Hi Darren. ')
};
There are three types in the code: Private properties, shared properties, and common methods, and then create a test.js that performs node
The highlight of the result is that we're not getting the private method out of the module, so it's undefined. Declarations of common properties and common methods need to precede the This keyword.
What node can do and its advantages
Node core idea: 1. Non-blocking; 2. Single thread; 3. Event-driven.
In the current Web application, there is some interaction between the client and server that can be considered event-based, then Ajax is the key to the timely response of the page. Each time a request is sent (no matter how small the requested data), it will go back and forth in the network. The server must respond to this request, usually by opening a new process. So the more users visit this page, the number of requests will be more and more, there will be memory overflow, logic staggered conflict, network paralysis, system crashes these problems.
Node's goal is to provide a solution for building scalable network applications, in the Hello World example, where servers 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 notifies node and enters hibernation. If someone creates a new link, it executes a callback, and each link takes up a very small (memory) stack overhead.
To give an example of a simple asynchronous invocation, Test.js and Mymydule.js are ready, ^_^. Copy the following code into the Test.js and execute:
var fs = require (' FS ');
Fs.readfile ('./mymodule.js ', function (err, data) {
if (err) throw err;
Console.log (' successfully ');
});
Console.log (' async ');
The so-called asynchronous, everyone should be able to want to run will first show "Async", and then show "successfully".
Node is non-blocking, and when a new request arrives at the server, there is no need to do anything alone for the request. node is only there to wait for the request to occur, processing the request on request.
node is better at handling small-volume requests and event-based I/O.
Node is not just a framework for Web services, it can do more, for example, it can do socket service, can do for example file-based, and then based on something like a child process, and then the internal, it is a very complete event mechanism, including some asynchronous non-injection solutions, And not just on the network level. At the same time it may, even as a Web service, it provides more depth to the core of the service, such as the HTTP Agent node, which is it can go deeper into the service kernel to do some functions.
Node Event Flow Concept
Because node uses event-driven patterns, many of these modules produce a variety of events that can be added to the event-handling method by the module, and all objects capable of generating events are instances of the Eventemitter class in the event module. Code is a common language in the world, so we still talk in code:
var events = require ("events");
var emitter = new events. Eventemitter ();
Emitter.on ("MyEvent", Function (msg) {
console.log (msg);
});
Emitter.emit ("MyEvent", "Hello world.");
Simple analysis of this paragraph:
1. Use the Require () method to add the events module and assign the return value to a variable
2. New events. Eventemitter () Creates an event trigger, which is an instance of the Eventemitter class in the so-called event module
3. On (event, listener) is used to add an incident handler method listener for an event incident
4. Emit (event, [Arg1], [arg2], [...]) method is used to generate events. Executes each listener function in the listener list sequentially, using the supplied parameters as parameters for 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) both methods add a listener to the end of the listener array for the specified event
2. Once (event, listener) This method adds a one-time listener to the events. The listener executes the first time the event is triggered and is then removed
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], [...]) has just been mentioned.
In node, there are a variety of different streams of data, and stream (stream) is an abstract interface implemented by different objects. For example, requesting HTTP server request is a stream, similar to stdout (standard output), including file system, HTTP request and response, and TCP/UDP connection. The stream can be readable, writable, or readable and writable. All streams are instances of eventemitter, so you can produce a variety of different events.
A readable stream mainly produces the following events:
This event is triggered when data is read to the stream
End this event is triggered when there is no data to read in the stream
Error This event is triggered when there is an error reading the data
Close when the stream is closed, this event is triggered, but not all streams will trigger the event. (for example, a connection into an HTTP request stream does not trigger a ' close ' event.) )
There is also a special FD event that triggers this event when a file descriptor is received in the stream. Only UNIX streams support this feature, and other types of streams do not trigger this event.
Related Detailed documentation: HTTP://CNODEJS.ORG/CMAN/ALL.HTML_
Powerful File system filesystem module
The FS module in Node is used to manipulate the local file system. File I/O is encapsulated by the standard POSIX function. The module needs to be accessed using require (' FS '). All methods provide both asynchronous and synchronous approaches.
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 action file has a synchronous and asynchronous two-version method.
The version of the asynchronous operation uses a callback method as the last argument. When the operation completes, the callback method is invoked. The first parameter of the callback method is always left as an exception that may occur when the action is taken. If the operation succeeds correctly, the value of the first parameter is null or undefined.
The method name for the version of the synchronization operation 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 is a list of some common methods in the FS module that describe only the version of the asynchronous operation.
Test.js and Mymodule.js papers ready for the wood? Take the following copy of the code to Test.js and execute it once
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 the mymodule.js is deleted, it is so simple
This is just a simple example, interested in a lot of yourself to try to practice the truth. There are not many examples because of space. ^_^
Learning Node's summary:
1. For a Linux command and shell knowledge is almost zero for me, this period of time and learned a lot about Linux knowledge; Vim is really a powerful editor, without the use of the mouse feeling is very good; and one thing is important to me, Linux programming is cool, Especially in the team are using Windows, loaded more healthy ^_^.
2. Understanding a successful framework for server JavaScript-node, along with some of its advantages and ways of using it, is the best summary, and of course, it will only be a start.
3. For those who do not enter the dream of the company is actually a little regret, but life should be so, there are ups and downs, this is what I need and look forward to ... So the new life is still to continue, to be their own helmsman, to grasp their own direction, the past let it pass.
Something to say to everyone:
1. In this I have to blow up some people's enthusiasm. If you are not familiar with the background technology or have not contacted the server language, I do not know the knowledge of I/O, there is no background processing process This concept, then ... node is not a service-side technology for getting started. Why do you say this:
A. The main point is that there are few examples of Chinese, less articles, want to study the system will be more trouble, so in the use of the process there is always an immature feeling, of course, mainly because I am unfamiliar with it caused. The domestic use of node is really not many companies, of course, there are a lot of foreign, from the cnodejs.org cut a figure:
B. For inexperienced friends, node is not very easy to use, from the simplest "Hello world" can be seen (a variety of operating environment and installation details of the understanding of a bit of effort), not to the jquery library for comparison, the processing of different things, the cost of learning is also different- Therefore, it is not very recommended as a novice entry-level server technology, if you want to learn a service-side language PHP and Python are good choices, because: more than a few examples of books more than the framework of simple easy to understand the construction convenience ...
C. The above are my personal well-meaning suggestions, because the level is limited, please advise, hope that the mouth of mercy.
2. Regarding node's writing specification and the concrete technique oneself does not have the shortcoming, oneself writes the node the code to be not many, but the object-oriented programming idea is all to be convenient.
The above content is small series to introduce the Nodejs preliminary experience, I hope you like.