node. js

Source: Internet
Author: User
Tags emit install node node server using git version control system

What's a node?

Write something or try to be as comprehensive as possible, so the basic concept of things I also picked from the Internet selectively, some places for their own understanding of the changes, the concept of these things have a better understanding of the choice to skip this paragraph.

1.Node is a server-side JavaScript interpreter, but really think that JavaScript good classmate learning Node can easily win, then you are wrong, summed up: water 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 can handle tens of thousands of simultaneous connections to a physical machine. Dealing with high concurrency and asynchronous I/O is one of the reasons that node is concerned by developers.

The 3.Node itself runs the Google V8 JavaScript engine , so speed and performance are very good, as Chrome knows, and Node's encapsulation of it also improves its ability to process binary data. As a result, node not only uses V8, but also optimizes it to make it more resilient in a variety of environments. (What is the 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 are written for node.

Install node

In this brief talk about installing node in the WINDOW7 and Linux two environments. When installing, be sure to pay attention to the Python version, many times because the Python version of the problem installation failed, the recommended version of 2.6+, the lower version will appear node installation error, query Python version can be entered in the terminal: Pyhton-v

1. First introduce Linux under the installation Bar, node in the Linux environment installation and use is very convenient, it is recommended to run node under Linux, ^_^ ... I'm using Ubuntu11.04.

A. Install the dependency package:50-100kb/s about one minute each package can be downloaded and installed to complete


sudo apt-get install Git-core

B. Run the command at the end step:

git clone git://github.com/joyent/node.git   
CD node
./configure
Make
sudo make install

If the installation is successful, the 2M network has a total of 12 minutes.

Note: You can download the source code directly without git download, but you should pay attention to the node version issue in 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, because it really takes a long time and a better personality. my system is win7 flagship edition

Cygwin is a UNIX simulation environment that runs on the Windows platform: Http://cygwin.com/setup.exe.

Download the good Cygwin and start the installation, steps:

A. Select the source of the download-Install from the Internet

B. Select the root directory of the download installation

C. Select the directory where the downloaded files are stored

D. How to select a connection

E. Select the downloaded website-http://mirrors.163.com/cygwin

F. Trouble is in this step, the time to test the character. The required download installation time is uncertain, 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" 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

Last, take download zlib-devel for example:

    

After a few steps to complete the environment, but now not to install node, but also in the Cywgin ash mode to execute Rebaseall, the steps are as follows:

A. cmd command line

B. Enter the bin subdirectory of 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 install node, start Cygwin.exe after input:

$ 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 the Node.exe file directly

nodejs.org download is slow so I uploaded one on the Web disk: http://www.everbox.com/f/VhyL6EiGF5Lm3ZSRx85caFDIA5

I heard there is a problem that is not very stable, but if you just want to get to know node in Windows first, personally feel that this method is much better than you can put a cygwin.

Note: Originally did not want to write installation node this paragraph, but for this article comprehensiveness or write, did not expect a write is so long a paragraph ... Coffee table.

"Hello World"-why every time 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, generally directly assigns 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 the system presets

B. Http.createserver is the method of the module, which is to create and return a new Web server object and bind a callback to the service to process the request.

C. The Http.listen () method allows the HTTP server to listen on a specific port.

D. Console.log will not have to say more, understand firebug should know, node implementation of this method.

Note: For specific details, please see document Cnodejs.org/cman/all.html#http.createserver

Then run the node server, execute the hello.js code, and successfully start to see the text in Console.log (). There is a picture of the truth:

  

  

Download and use of NPM

In addition to the API provided by node itself, there are now a number of third-party modules that can greatly improve the development efficiency, NPM is node's package Manager, you can use it to install the required packages and publish their own Nodejs write packages. Website address: npmjs.org

Installation requires only one line of code to be written to the terminal:

Curl Http://npmjs.org/install.sh | Sh

NPM Installing the node extension package is also a line of code:

NPM Install < package name >//Example: NPM Install Express

Note: If the domain name error is reported during the installation of the module, empty the cache clean or restart the computer >npm.

  

Understanding node's modular concept

In node, different functional components are divided into different modules. The application can choose to use the appropriate module according to its own needs. Each module exposes a number of common methods or properties. The user of the module directly uses these methods or properties, and the internal implementation details are not known. In addition to the APIs provided by node itself, developers can use this mechanism to split the application into multiple modules to improve the reusability of the code.

  1. How do I use the module?

The use of modules in node is very convenient, and in JavaScript code you can directly use the global function require () to load a module.

In just "Hello world" example, require ("http") can load the System preset HTTP module; The module name begins with "./", as require ("./mymodule.js") is used to load the current JavaScript The Mymodule.js module in the same directory as the file.

  2. How do I develop the module?

When we introduced the module using require (), the module name starts with "./", which is the module file that you developed. Note that the JS file is the system path.

The code encapsulates the internal processing logic of the module, and a module generally exposes methods or properties that are exposed to other people. The internal code of the module needs to expose these methods or properties.

  3. Come up with a simple set of examples. first create a module file, such as Mymodule.js, 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 now a number of third-party modules in the node community, hoping that more people can join this family by learning node to contribute to the node community. Thank you first, let's go on.

  4. Come up with an example of a deep point. This example will be described 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, namely, private properties, common attributes, and common methods, and then create a test.js to execute node

The highlight of the result clearly tells us that the private method we are not in the module is not access, so is undefined. Declarations of common properties and common methods need to precede the This keyword.

What node can do and its advantages

Node Core ideas: 1. Non-blocking, 2. Single thread, 3. Event driven .

In the current Web application, the interaction between client and server can be considered event-based, so 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 through the network. The server must respond to this request, usually to open up a new process. Then the more users access this page, the number of requests will be more and more, there will be memory overflow, logical interleaving caused by conflicts, network paralysis, system crashes these problems.

Node's goal is to provide a solution for building scalable Web applications, in the Hello World example, where the server can handle many client connections at the same time.

Node has a convention with the operating system, and if a new link is created, the operating system notifies node and then goes into hibernation. If someone creates a new link, it (Node) executes a callback and each link takes up a very small (memory) stack overhead.

To give an example of a simple asynchronous invocation, get test.js and mymydule.js ready, ^_^. Copy the following code into 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 async, you should be able to expect the runtime will first display "Async", and then display "successfully".

Node is non-blocking, and when new requests arrive at the server, there is no need to do anything for this request alone. Node simply waits for the request to occur, and requests it to process the 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, such as it can do socket service, can do such as file-based, and then based on like some say can have child process, and then internal, it is a very complete event mechanism, including some asynchronous non-injection solution, And not just on the network level. At the same time it is possible that, even as a Web service, it provides more features that can go deep into the core of the service, such as the HTTP Agent that node uses, which is what it takes to get deeper into the service kernel to do some functions.

Node Event Flow Concept

Because node takes an event-driven pattern, many of the modules produce various events that can be added by the module to add event-handling methods, and all objects that can produce events are instances of the Eventemitter class in the event module. The code is a universal language in the world, so we still talk in code:






Emitter.emit ("MyEvent", "Hello World");

Simple analysis of this paragraph:

1. Add the events module using the Require () method and assign the return value to a variable

2. New events. Eventemitter () This sentence creates an event trigger, an instance of the Eventemitter class in the so-called event module

3. On (event, listener) is used to add an event-handling method listener

4. Emit (event, [Arg1], [arg2], [...]) method is used to generate the event. Executes each listener function in the listener list sequentially, using the supplied parameters as arguments to 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 to 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 for the event. 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 different kinds of data streams, and stream is an abstract interface implemented by different objects. For example, request for an HTTP server is a stream, similar to stdout (standard output), including file systems, HTTP requests and responses, and TCP/UDP connections. The stream can be readable, writable, or both readable and writable. All flows are instances of eventemitter, so you can produce a variety of different events.

Readable streams mainly produce the following events:

    • The event is triggered when data is read to the stream
    • End this event is triggered when no data is readable in the stream
    • Error This event is triggered when the read data is wrong
    • Close when the stream is closed, this event is triggered, but not all streams will trigger the event. (for example, a connection enters an HTTP request stream that does not trigger a ' close ' event.) )

There is also a special FD event that fires 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 documents: Http://cnodejs.org/cman/all.html#events_

The powerful file system filesystem module

The FS module in Node is used to operate on the local file system. The I/O to a file is encapsulated by a standard POSIX function. This module needs to be accessed using require (' FS '). All of these 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 will use a callback method as the last parameter. The callback method is called when the operation is completed. The first parameter of the callback method is always left as an exception that may occur when the operation occurs. If the operation succeeds correctly, the value of the first parameter is null or undefined.

The method name of the version of the synchronous operation is followed by a sync as a suffix after the corresponding async 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 files ready for the wood? Copy the following code into Test.js to execute once

var fs = require (' FS ');
Fs.unlink ('./mymodule.js ', function (err) {
if (err) throw err;
Console.log (' successfully deleted Mymodule.js ');
});

If the error is not reported, then the Mymodule.js is deleted, it is so simple

  

From: http://www.cnblogs.com/Darren_code/archive/2011/10/31/nodejs.html

node. js

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.