node. js the next day

Source: Internet
Author: User

node. JS entry and enterprise-level development combat

2nd Day Class notes (8 days in this course)

Directory

Directory....................................................................................................................... ......................................... 2

First, review ......................................................................................................................... ................................ 3

Second, the module ......................................................................................................................... ................................ 4

Third, POST request ......................................................................................................................... .......................... 7

Four, template engine ......................................................................................................................... ......................... 8

First of all, say Ejs ... ..... ..... ..... ............................... ..... ..... ..... ..... ..... ..... ..... ..... ..... ..... ..... ..... ....... ..... ............................... 8

First, review

Review:

node. JS Development Server, data, routing. The effect of local care, interaction;

node. js is actually a little toy developed by geeks, not a silver bullet. Have strange features that others don't have:

Single thread, NON-BLOCKINGI/O, Event driven. is actually a feature.

First, node does not open a thread for each user, so the extreme choice is single-threaded. Single-threaded, to take care of all the users, then there must be non-blocking I/O, or a person's I/O to others, they are blocked. Once a person has non-blocking I/O, if the I/O is gone, the CPU is discarded and replaced by another person using the CPU (or by executing the statement behind the person). So CPU utilization is 100%. When the first person I/O ends, it is necessary to notify the thread with an event and execute the callback function. There must be an event ring at this time, there is a queue scheduling mechanism. More than half of the C + + code in node is building event loops.

node. JS is not the same as other veteran 3P:

1) without their own grammar, using the V8 engine, so is JS. V8 engine parsing JS, the efficiency is very high, and V8 a lot of things are asynchronous. Node is the V8 of some of the functions of the self-rewriting (others have done, they stand on the shoulders of giants), transplanted to the server.

2) There is no web container, that is, after the installation configuration is complete, there is no root directory.

The path to the command prompt is too important because all the relative paths in the program "./" are relative to this command prompt path, not relative to the JS file itself.

In the system, port 80 is the default HTTP port. So when there is no port number, it is port 80.

1 Server.listen (80, "127.0.0.1");

Second, the module

In node. js, all functions are partitioned in modules, and a complete module loading mechanism is provided, in which case we can divide the application into various parts.

It is impossible to use a JS file to write all the business. There must be MVC.

In a narrow sense , every JavaScript file is a module, and multiple JavaScript files can be require to each other, they collectively implement a function, they are the whole external, also known as a generalized module.

In node. js , the variables and functions defined in a JavaScript file are valid only within the file . When you need to reference these variables, functions from outside of this JS file, you must use the exports object for exposure. The user will use the Require () command to refer to this JS file.

Code in the Foo.js file:

1 var msg = "Hello";

2

3 exports.msg = msg;

MSG, a variable that is scoped within a JS file.

if people want to use this variable, then they need to use exports be exposed .

User:

1 var foo = require ("./test/foo.js");

2

3 Console.log (FOO.MSG);

The user uses Foo to receive the exports object, which means that the Foo variable here is the exports variable in the file.

A JavaScript file that can exports an infinite number of variables, functions. But require, just need to require this JS file once. When using its variables, functions, you can use the dot syntax. So, invisibly, adds a top-level namespace.

JS file, you can use exports to expose a lot of things, such as functions, variables.

1           var msg = "Hello";

2           var info = "hehe";

3            

4           function Showinfo () {

5               console.log (info);

6          }

7            

8           exports.msg = msg;

9           exports.info = info;

10       exports.showinfo = showinfo;

In the user, you only need to require once.

1 var foo = require ("./test/foo.js");

The equivalent of adding a top-level variable. All functions and variables go from this top-level variable:

1 Console.log (FOO.MSG);

2 Console.log (Foo.info);

3 Foo.showinfo ();

node, JS files and JS files, is a exports and require built into a mesh.

Not by HTML files unified.

You can describe a class in a JavaScript file. Use

Module.export = Name of the construction function;

Exposes a class out of the way.

In other words, there are two modes of cooperation between JS file and JS file:

1) A certain JS file, provides a function for others to use. Only need to expose the function to be OK; exports.msg=msg;

2) A JS file that describes a class. Module.exports = people;

If in the Require command, write this:

1 var foo = require ("Foo.js"); Not written./, so not a relative path. is a special path.

Then node. JS treats the file as a file in the Node_modules directory

The Node_modules folder is not necessarily in a sibling directory, it can be in any direct ancestor level directory. It can even be placed in the folder of the NODE_PATH environment variable. The benefits of doing so you'll know later: when you share a project, you don't need to bring modules with them.

We can use folders to manage modules, such as

1 var bar = require ("bar");

Then node. JS will look for the index.js in the Bar folder under the Node_modules directory to execute.

Each module folder, recommended to write a Package.json file, the name of this file can not be changed. Node will automatically read the configuration inside. There is a main entry, which is the entry file:

1 {

2 "name": "Kaoladebar",

3 "version": "1.0.1",

4 "main": "App.js"

5}

6

Package.json file, go to the root directory of the module folder.

We have just learned that the module is the encapsulation of some functions, so some mature, often used features, have been encapsulated into a module. And put them in the community for free download.

This great community is called NPM. Also a tool name node package management

https://www.npmjs.com/

Go to the community to search for the needs, then go in and see the API.

If you want to configure a module, use it directly in cmd

1 NPM Install module name

You can install it. Module name globally unique.

When installing, be aware of where the command prompt is located.

1. Our dependency packages, may be updated at any time, we always want to keep the update, or a certain version of the hold;

2. When the project is getting bigger and larger, it is not necessary to share the third-party modules we refer to again when it comes to others.

We can use Package.json to manage dependencies.

In cmd, you can initialize a Package.json file with NPM init and generate a new Package.json file in a way that answers the questions.

Use

1 NPM Install

will be able to install all dependencies.

NPM also has documentation, which is an introduction to Package.json:

Https://docs.npmjs.com/files/package.json

require () Other JS file, the JS will be executed. file.

Attention:

require () in the path, is from the current JS the papers set out to find someone else. and FS is to find someone from the command prompt.

So, there is a a.js on the desktop , the test folder has b.js, c.js, 1.txt

A To reference B:

1 var b = require ("./test/b.js");

B To reference C:

1 var b = require ("./c.js");

However, when other modules such as FS are used in the path, they are relative to the position of the cmd command cursor.

Therefore, in b.js to read 1.txt files, it is recommended to use absolute path:

1 fs.readfile (__dirname + "/1.txt", function (Err,data) {

2 if (err) {throw err;}

3 Console.log (data.tostring ());

4});


Third, POST request

1 var alldata = "";

2//The following is a formula received by the POST request

3//node in order to pursue the Acme, it is a small segment of a small segment received.

4//Accept a short paragraph, may give others to service. Prevents an oversized form from blocking the entire process

5 Req.addlistener ("Data", function (chunk) {

6 alldata + = chunk;

7});

8//Full transfer complete

9 Req.addlistener ("End", function () {

Ten Console.log (Alldata.tostring ());

Res.end ("Success");

12});

Native write post processing, more complex, to write two listening. File upload business is difficult to write.

So, use a third-party module. Formidable.

As long as the file upload is involved, the form tag is added with a property:

1 <form action= "Http://127.0.0.1/dopost" method= "post" enctype= "Multipart/form-data" >


Four, template engine

1 <a href= "<%= url%>" ></a>

Data binding, it becomes a complete HTML string.

Front of the template, we now want to learn is the background of the template.

Backstage template, the famous two, the first is called Ejs, the second one is called Jade.

Is the NPM third-party package.

First, Ejs.

Embedded JavaScript Templates

Background template engine

< P class= "a" >1               <ul>

2                     <% for (var i = 0; i < news.length; i++) {%>

3&n bsp;                       <li> <%= news[i]%> </li>

4                      <%}%>

5                </ul>

1 var dictionary = {

2 A:6,

3 News: ["1 class is too good", "high-paying employment", "ha ha ha haha")

4};

node. js the next day

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.