node. js "6" Web Development, Advanced (module loading, control flow, deployment, drawbacks)

Source: Internet
Author: User
Tags readfile

Notes from the node. JS Development Guide Byvoid

Implementation process: Https://github.com/ichenxiaodao/express-example


5th chapter Web Development using node. js
Zero-based implementation of a micro-blogging system with node. js, including routing control, page templates, database access, user registration, login, user sessions and other content.

Describes the Express framework, MVC design pattern, Ejs template engine, and MongoDB database operations.

5.1. Preparatory work
In addition to providing higher-level interfaces for HTTP modules, Express (http://expressjs.com/) also implements a number of features, including:
    • routing control;
    • Template parsing support;
    • Dynamic view;
    • User session;
    • CSRF protection;
    • static file service;
    • Error controller;
    • Access logs;
    • Cache
    • Plugin support.

It's just a lightweight web shelf, most of which is just the encapsulation of common operations in the HTTP protocol, and more features that require plug-ins or integration with other modules.

5.2. Quick Start
Install Express:
NPM install-g [email protected]
NPM install-g Express-generator (v4.0.0 later)

Ejs (Embeddedjavascript) is a label replacement engine, its syntax is similar to ASP, PHP, easy to learn, is now widely used. Express by default the engine is jade, it overturned the traditional template engine, developed a complete set of syntax to generate HTML for each tag structure, powerful but not easy to learn.

Establish the basic structure of the website:
Express-t Ejs Microblog
CD microblog && NPM install

The function of the parameterless NPM install is to check the Package.json in the current directory and install all specified dependencies automatically.

5.3. Routing control
Structure of the "figure" Express website


This is a typical MVC architecture in which the browser initiates the request, which is accepted by the routing controller and directed to different controllers depending on the path. The controller handles the user's specific request and may access the object in the database, the model part. The controller also accesses the template engine, generates HTML for the view, and finally returns the controller to the browser to complete a request.

Express supports the rest-style request method before we introduce what is rest. Rest means the representation of state transitions (representational-Transfer), which is an interface style based on the HTTP protocol of the network application, which takes full advantage of the HTTP method to realize the service of the unified style interface. The HTTP protocol defines the following 8 standard methods.
    • Get: Request to get the specified resource.
    • Head: Requests the response header for the specified resource.
    • POST: Submits data to the specified resource.
    • PUT: The request server stores a resource.
    • Delete: The request server deletes the specified resource.
    • TRACE: Echo the request received by the server, primarily for testing or diagnostics.
    • The connect:http/1.1 protocol is reserved for proxy servers that can change connections to pipelines.
    • OPTIONS: Returns the HTTP request method supported by the server.
    • We often use the GET, POST, put, and delete methods. According to the rest design pattern, this
    • 4 methods are typically used to implement the following functions, respectively.
    • Get: Get
    • POST: New
    • PUT: Update
    • Delete: Remove
This is because these 4 methods have different characteristics, so-called security refers to the absence of side effects, that is, the request does not change the resources, continuous access to the results obtained by multiple times is not affected by the visitor. Idempotent refers to repeated requests that have the same effect as a single request, such as the fetch and update operations being idempotent, which is different from the new one. Delete is also idempotent, that is, delete a resource repeatedly, and delete it once is the same.

Features of the "figure" Rest-style HTTP request


Express has designed different route binding functions for each HTTP request method, such as the previous example is all App.get, which indicates that a GET request is bound to the path, and that the request to initiate another way to the path will not be responded to.

Binding functions for HTTP requests supported by "figure" Express


Express supports multiple route response functions that are bound to the same path. But when you access any path that is matched to the two same rules, you will find that the request is always captured by the previous routing rule and the subsequent rules are ignored. The reason is that when express handles routing rules, it prioritizes the first defined routing rules, so the same rules are masked later.

Express provides a way to transfer control over a route, that is, the third parameter of the callback function next, which, by invoking next (), transfers the routing control to the following rule.

5.4. Template engine
Template engine is a tool that generates HTML from a page template according to certain rules. PHP is the first prototype of the template engine. The subsequent ASP, JSP all follow this pattern, that is, the creation of an HTML page template, insert executable code, the runtime dynamically generated HTML.

In the MVC architecture, the template engine is included on the server side. After the controller obtains the user request, obtains the data from the model, invokes the template engine. The template engine takes data and page templates as input, generates HTML pages, and returns them to the controller,
The controller is handed back to the client.

There are many implementations of the JavaScript-based templating engine, and we recommend using Ejs (Embedded JavaScript) because it is simple and well integrated with Express.

The Ejs label system is very simple and it has only the following 3 types of labels.
    • <% Code%>:javascript codes.
    • <%= code%>: Displays content that has been replaced with HTML special characters.
    • <%-code%>: Displays the original HTML content.

Express provides a tool called the View helper that allows access to a global function or object in the view without having to pass in each time the view is parsed.

There are two types of view assistants, the static view assistant and the Dynamic View helper. The difference between the two is that the static view helper can be any type of object, including a function that accepts arbitrary arguments, but the object to be accessed must be independent of the user's request, whereas the Dynamic View helper can only be a function that cannot accept parameters but can access the Req and Res objects.

The essence of the view helper is to register global variables for all views, so you don't need to call the template engine every time
Passes the data object.

5.5, the establishment of micro-blog website
function analysis, route planning, interface design, using bootstrap

5.6. User Registration and Login


NoSQL was introduced in 1998 as a lightweight, open source, relational database that does not provide SQL functionality. But now NoSQL is considered the abbreviation of Notonlysql, mainly refers to the non-relational, distributed, does not provide acid (database system transactions (transaction) must have four characteristics, namely atomicity (atomicity), consistency (consistency) , isolation (isolation), and persistence (durability)) of the database system. As its name implies, NoSQL is not designed to replace SQL database, but as a supplement, it has its own different areas of adaptation to SQL databases. NoSQL doesn't have a unified architecture and interface like a SQL database, and different NoSQL database systems can be completely different from the inside out.

MongoDB is an object database that has no concepts such as tables, rows, or fixed patterns and structures, and all of the data is stored in the form of documents. The so-called document is an associative array of objects, the interior of which is composed of attributes, the value of an attribute may be a number, a string, a date, an array, or even a nested document.

The data format for MongoDB is JSON. To be precise, MongoDB's data format is Bson (Binary JSON), which is an extension of JSON.

A session is a persistent network protocol that accomplishes some interaction between the server and the client. A session is a more granular concept than a connection, a session may contain multiple connections, and each connection is considered an operation of the session. In Web application development, it is necessary to implement a session to help users interact.

To implement a session on top of a stateless HTTP protocol, the cookie was born. Cookies are information stored on the client, which is submitted by the browser to the server each time the connection is made, and the server initiates a request to the browser to store the cookie, depending on the way the server can identify the client. This is how the HTTP session function in our usual sense is implemented. Specifically, when the browser initiates a request to the server for the first time, the server generates a unique identifier and sends it to the client browser, which stores the unique identifier in a cookie and the client browser sends the unique identifier to the server each time it is requested. The server uses this unique identifier to identify the user.


5.7, published micro-Boulhosa

6th Chapter node. JS Advanced Topic
6.1. Module loading mechanism
node. JS modules can be divided into two major categories, one is the core module, and the other is the file module. The core modules are the modules provided in the node. JS Standard API, such as FS, HTTP, net, VMS, etc., which are compiled into binary code by the modules that are officially provided by node. js. We can get the core modules directly through require, such as require (' FS '). The core module has the highest load priority, in other words node. js always loads the core module if there is a module that conflicts with its naming.

A file module is a module that is stored as a separate file (or folder), which may be JavaScript code, JSON, or compiled C + + code. The loading method of the file module is relatively complex, but very flexible, especially when combined with NPM. When you do not explicitly specify a file module extension, node. JS will attempt to add. js,. JSON, and. node extension. js is the JavaScript code,. JSON is a JSON-formatted text, and. Node is a compiled C + + code.

File module Load priority:. js->.json->.node

There are two ways to load a file module, one to load by path, and one to find the Node_modules folder.

The node. JS module is not loaded repeatedly because node. JS caches all the loaded file modules through the file name, so it will not reload when it is accessed later.

Summarize the loading order when using require (Some_module).
(1) If Some_module is a core module, load directly and end.
(2) If the some_module is "/", "./" or ". /"begins with the Some_module loaded by path, ending.
(3) Assuming the current directory is Current_dir, load current_dir/node_modules/some_module by path.
If the load succeeds, end.
If the load fails, make Current_dir the parent directory.
Repeat this process until the root directory is encountered, throwing an exception, and ending.

6.2. Control Flow

var fs = require (' FS '); var files = [' A.txt ', ' b.txt ', ' C.txt '];for (var i = 0; i < files.length; i++) {fs.readfile (file S[i], ' utf-8 ', function (err, contents) {Console.log (Files[i] + ":" + contents);}); /* Run Result: undefined:aaaundefined:bbbundefined:ccc*/

The reason is that the callback function that reads the file 3 times is actually the same instance where the I value referenced is the value after the end of the loop execution, and therefore cannot be distinguished.

Workaround:
var fs = require (' FS '); var files = [' A.txt ', ' b.txt ', ' c.txt '];files.foreach (function (filename) {fs.readfile (filename, ' Utf-8 ', function (err, contents) {console.log (filename + ":" + contents);}); * Operation Result: a.txt:aaab.txt:bbbc.txt:ccc*/
In addition to looping traps, there is a significant problem with the asynchronous programming of node. JS, which is that deep callback functions are nested.

Many projects are trying to solve this problem. Async is a control-flow decoupling module that provides functions such as Async.series, Async.Parallel, Async.waterfall, and so on, using these functions instead of nested callback functions to make the program more readable and easier to maintain when implementing complex logic.

There are Streamlinejs, Jscex, Eventproxy.

6.3. Node. JS Application Deployment
When deploying a node. JS application, it is important to consider the failure recovery and improve the reliability of the system.
It is necessary to implement the logging function.
Use multiple processes to improve the performance of your system.
Reverse proxy to implement domain-based port sharing.
The ability to start or stop a server is implemented through scripting.

6.4. Node. js is not a silver bullet
No matter what language or tool you use, the only thing that can change is the comfort and convenience of development, and the extent to which the final software can change is quite limited. Any attempt to improve the quality of software by restricting programmers to make mistakes has ended in failure. Really good software is developed by excellent programmers, excellent language, platform, tools only in the hands of excellent programmers can show its power.

What node. js is not suitable for:
    • computational-intensive programs;
    • Single user multi-tasking application;
    • A transaction of very complex logic;
    • Unicode and internationalization;


Document Information

    • Copyright Disclaimer: Free Reprint-Non-commercial-non-derivative-retain attribution | Creative Commons by-nc-nd 3.0
    • Original URL: http://blog.csdn.net/cdztop/article/details/37745779
    • Last modified: July 14, 2014 00:08
Related Article

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.