Node. js and Golang usage experience and summary [2]

Source: Internet
Author: User
Tags install node

V. Introduction to Node. js

Node. js is a platform based on Google's V8 engine. It uses the V8 engine and complies with the COMMONJS standard to implement an efficient and stable platform. Node. javascript web programming is based on data streams and can directly manipulate http streams. Thanks to this feature, we can easily customize the data sent to the client, at the same time, because Javascript is used and asynchronous, it is more suitable for the development of modern applications. At present, many companies around the world are using it. Well-known users such as linkin, TaoBao and Myspace.

6. is front-end selection or the gospel of backend?

After the release of Node. js, there was a great storm of discussion at home and abroad. Even a large number of front-end engineers in China think that this platform is prepared for front-end engineers, and some back-end engineers are not used to Node. js programming style.

Javascript is a controversial language, and it takes only a short time from design to use. It draws on the features of many languages, and of course there are also some disadvantages of many languages. For historical reasons, Javascript had no package basis in the early stage, and classes were simply simulated through prototype. However, Javascript is one of the most free languages in the world. You can use syntactic sugar to simulate your familiar language. Generally, it is not recommended to simulate other languages. When using a language, it is best to think about how to solve the same problem in this language, instead of using the thinking of another language to do Javascript, it seems to have become a necessary tool for front-end developers in the early days. With the development of the times, we found that Javascript can also write server programs.

In fact, it is only one of the solutions for efficient http servers. It is not especially intended for front-end or back-end engineers. If you want to, you can use it. But whether it can be used well depends on yourself. Throughout the software development, it is difficult for us to distinguish between front-end and back-end engineers. In terms of operating systems, we are currently developing on the application layer (some books are called user mode ), so compared with those kernel engineers, are we frontend or backend?

VII. Comparison between Node. js and traditional php-fpm Models

Traditional PHP running mode (non-libevent and other running Modes ):

Most PHP runtime environments generally have a server with a middleware role, which is responsible for communicating with the PHP port (default port 9000 ), apache and Nginx can all be used as middleware. After an http request is initiated from a client, the server generally performs the following operations:

1. Determine the HTTP method, POST or GET based on the request message sent by the user, and then proceed to the next step based on the implementation of the server software.

2. Determine whether the resources requested by the user are static or dynamic scripts. This step is especially handled by some middleware such as nginx. If a static file is requested, the file will be directly sent to the browser if all the permissions are met and the resource exists. Of course, some files that have already been requested may directly return a 304 status code, in this way, the browser will use the content in the cache to give the user. If it is a dynamic file, the middleware will determine how to handle it. This is why most servers, such as nginx, need to configure scripts such as php in the configuration file.

3. If it is php, the middleware will forward the request to the php interpreter first. After the php interpreter completes the operation, the result will be returned to the middleware, middleware is returning the result to the browser. Middleware acts as a proxy here. In fact, it does work by php through modules such as libevent, but the implementation cost is too high, therefore, most enterprises choose nginx or apache to implement these basic functions, and focus on business development.

Node. js running mode-Modern Programming Based on Data Stream

For modern program development, the most direct way is to directly control data streams. In this way, you can decide what is returned to the user and what needs to be hidden. A Node. js application will do the following after receiving an http request:

1. Router distribution rules: because an application itself is a server, no forwarding or proxy is required, and requests are directly processed using custom rules.

2. The specific service can be processed in queue or asynchronous mode. To put it simply, in traditional web development, when we need to do one thing, we generally wait until the last thing is done before we can handle new things. But in node. js, you can handle multiple tasks at the same time. When they are completed, their results are returned to the user.

 

 

 

 

(The figure is taken from the previous PPT)

Platform Style

Node. js

PHP

Installation Method

Source code or binary installation package can be directly installed

Install or use a third-party green package through source code compilation

Programming style

Asynchronous and data-based operations

Synchronization Style

Method of processing user requests

The application itself is an HTTP server

Use servers such as Nginx

Extended Installation Method

Npm

Phpize or configured during initial installation

Real-time running mode

Each change requires restarting the application. However, you can also refer to the Play framework in Java to perform hot loading, but this will affect the performance. The common cause of hot loading is to monitor file changes in real time.

The modified file is saved directly and takes effect immediately, but the program will read the new PHP file each time, causing a certain I/O loss.

Language rules

Class C style

Class C style

Performance Comparison

---- Use http_load and other tools for comparison

---- Use http_load and other tools for comparison

 

 

8. Install Node. js

First log on to the http://nodejs.org/download/ and then download the appropriate version of your platform, it is recommended that beginners download the binary installation package, but familiar with the source code is still compiled and installed. The advantage of compilation and installation is that the compiler will be optimized based on the platform environment that the user is working on.

Assume that we have downloaded the Binary Package

All the way down to Next.

To check whether the installation is successful, enter node-v in your console (for windows users, Enter cmd in the running menu, because the article is written on the windows platform, take windows as an example)

9. Let the browser understand your mind-Content-Type

To write a Node. js program, you only need an editor and a runtime environment ~

Var http = require ('http ');

Http. createServer (function (req, res ){

Res. writeHead (200, {'content-type': "text/plain; charset = UTF-8 "});

Res. write ('Hello world ~! \ N ');

Res. end ();

}). Listen (3000, '192. 0.0.1 ');

Console. log ('server running at http: // 127.0.0.1: 3000 /');

 

Save the code content as hello. js, and then run node <your saved directory>/hello. js on the console. After all this is done, open your browser and enter http: // 127.0.0.1: 3000 and press enter to see the effect.

Through this DEMO, you should be able to see the success of a simple http server. Of course, there are still many things to do for a fully functional server. Here is a simple DEMO. in this DEMO, you should find the Content-Type stuff. The Content-Type stuff tells the browser what to do. For example, if you send a text file to a user as a video or image, you need to tell the browser to call some programs of the system to run or display it.

 

 

10. Send a file to the browser

Let's move on to the code first. Everything is code first.

Var server,

Ip = "127.0.0.1", port = 3000, http = require ('http'), fs = require ("fs"), folderPath = "static", // store folders

Url = require ('url '),

Path = require ('path '),

Urlpath, // Request Path

FilePath; // file path

Var types = {

"Css": "text/css ",

"Gif": "image/gif ",

"Html": "text/html ",

"Ico": "image/x-icon ",

"Jpeg": "image/jpeg ",

"Jpg": "image/jpeg ",

"Js": "text/javascript ",

"Png": "image/png ",

"Tiff": "image/tiff ",

"Txt": "text/plain"

};

Server = http. createServer (function (req, res ){

Urlpath = url. parse (req. url );

FilePath = folderPath + urlpath. pathname;

Var content_type = types [path. extname (urlpath. pathname). substr (1)] | 'text/plain ';

Fs. readFile (filePath, function (err, file ){

If (err ){

Res. writeHead (404, {'content-type': 'text/plain '});

Res. end ();

Return;

}

Res. writeHead (200, {'content-type': content_type });

Res. write (file );

Res. end ();

});

});

Server. listen (port, ip );

Console. log ("Server running at http: //" + ip + ":" + port );

Of course, the process of sending the file to be read exists, so the fs package is required. This DEMO should be relatively simple. As long as you have the foundation, I believe you will soon understand the intention of this DEMO. This part is not intended to be explained in detail, because there have been many preliminary instructions and there are also many articles on the Internet. We need to focus on Node. javascript asynchronous process control, which contains a small amount of Chinese materials, is mostly implemented using node libraries such as AsyncJS or step, which does not mean that their implementation is poor, but the intermediate principle must be understood to master some of the key technologies that are considered to be.

 

Coming soon

========================================================== ============================

About Author:

Network Name: Nian: Shenzhen

Email: jinfei121@qq.com

QQ: 490821193

I started playing on the forum in, but it was a few years before I officially wrote code. Two major php programs written before work, mainly full-time

Javascript. I like to study various new technologies ~~

Node and Golang fans ~~

========================================================== ============================

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.