This is my 14th day on the Challenge @TOC

Introduction and Installation of Node.js:

1.1 introduction:

1.Node.js was released in May 2009 and developed by Ryan Dahl. It is a JavaScript runtime environment based on Chrome V8 engine. It uses an event-driven, non-blocking I/O model and enables JavaScript to run on the server. It puts JavaScript on an equal footing with server-side languages like PHP, Python, Perl, and Ruby. 2.Node.js optimizes some special use cases and provides alternative apis to make V8 run better in non-browser environments. The V8 engine executes Javascript very fast and performs very well, based on the platform built by Chrome Javascript runtime. It is used to build fast response and easy to expand network applications.

1.2 installation:

1.2.1 Go to the official website to download the installation package according to your own system and then install it.Node. Js Chinese website1.2.2 After the installation is complete, open the command console and enter node -v to display the version number.

Ii. Computer environment variables:

2.1 What is the CMD Command?

The CMD window is used to input commands to the computer. For example, node -v is the command to view the version of a node.

2.2 Functions of environment Variables:

There are environment variables in any operating system. Exe program inside the folder configured in the environment variable, can be called by the system CMD window. For example, if you type QQ directly in CMD window, it will not be able to execute because you have not configured environment variables. So you first look at the qq.exe folder path location, paste it in the environment variable configuration can be called by CMD window.

Use of Node.js:

3.1 Host Environment:

The js file must be executed in the host environment, otherwise it cannot be executed. The only hosting environment we’ve ever learned about is HTML. Now learn about another hosting environment, the Node.js platform.

3.2 CMD File directory:

We can open CMD command window to run js file. If I have a file named 01.js under path D:\node_Study, the content is:

for(let i=0; i<10; i++){console.log(i);
     }
Copy the code

We’ll execute it in the node file in that directory:If you execute 02.js, type node 02.js, and execute whatever js file you want.

4.Node.js build server:

4.1 A simple Demo:

Write the following code in the 01.js file:

// Get the built-in module, importing the built-in HTTP module of Node.js
var http = require('http');
// Create a server using the createServer method
// The req parameter in the callback represents the request and the res parameter represents the response
var server = http.createServer(function(req,res){
    // Set the character set
    res.setHeader("Content-Type"."text/html; charset=UTF8")
    // Output a sentence
    res.end('Night of the Northern Lights. ')})// The default port is 80, we use port 3000
server.listen(3000)
Copy the code

Run node 01.js in a CMD or PowerShell window, then go to your browser and run 127.0.0.1:3000/ to get the result:

Matters needing attention:1. If you want to change the contents of this file, re-execute Node.

CTRL + C breaks the connection

2. Like PHP, Node builds a server that flattens all the results and returns them to the computer. 3. Even a computer that does not have Node.js installed can request the functionality of our local Node.js computer. Because Node.js itself is to build the server, all we need to give the ID to the corresponding communication network under the computer can access, because essentially access is not Node, but to build the server.

4.2 Res.end ()

4.2.1 Res. end is not allowed to output multiple lines.
// Get the built-in module, importing the built-in HTTP module of Node.js
var http = require('http');
// Create a server using the createServer method
// The req parameter in the callback represents the request and the res parameter represents the response
var server = http.createServer(function(req,res){
    // Set the character set
    res.setHeader("Content-Type"."text/html; charset=UTF8")
    // Output a sentence
    res.end('Night of the Northern Lights. 1 ')
    res.end('Night of the Northern Lights. 2 ')
    res.end('Night of the Northern Lights. 4 ')
    res.end('Night of the Northern Lights. 4 ')
    res.end('Night of the Northern Lights. 5 ')
    res.end('Night of the Northern Lights. 6 ')})// The default port is 80, we use port 3000
server.listen(3000)
Copy the code

Output:

4.2.2 Res. end cannot be entered as a non-string:

It is wrong to say something like this:

res.end(123455)
Copy the code
4.2.3 Res.end is htML-aware:

Such as:

 res.end("

Night of the Northern Lights.

"
) Copy the code

Output:

4.3 res.write ()

Res.write () must end with res.end, otherwise the browser will remain in the request state. Res.write benefits from multiple output and recognition of HTML tags, but also cannot enter non-strings.

// Get the built-in module, importing the built-in HTTP module of Node.js
var http = require('http');
// Create a server using the createServer method
// The req parameter in the callback represents the request and the res parameter represents the response
var server = http.createServer(function(req,res){
    // Set the character set
    res.setHeader("Content-Type"."text/html; charset=UTF8")
    // Output a sentence
    res.write("<h1>one</h1>");
    res.write("<h1>two</h1>");
    res.write("<h1>three</h1>");
    res.end("End request")})// The default port is 80, we use port 3000
server.listen(3000)
Copy the code

Results:

V. Built-in functions of Node.js:

This is all the built-in modules of node.js Chinese documentation.

5.1 FS module:

The most important part of the FS module is the asynchronous readFile, the first parameter file, the second parameter is the callback function.

fs.readFile("File path and name".function(err,data){
       if(err) throw err;
        res.end(data);
   })
Copy the code

Example:

There is an index.html file:

<! DOCTYPEhtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
    <title>Document</title>
</head>
<body>
    <h1> Hello World. </h1>
</body>
</html>
Copy the code

Js reads it:

// Get the built-in module, importing the built-in HTTP module of Node.js
var http = require('http');
// Introduce node.js's built-in fs module
var fs = require('fs');
var server = http.createServer(function(req,res){
     fs.readFile("./index.html".function(err,data){ res.end(data); })})// The default port is 80, we use port 3000
server.listen(3000)
Copy the code

Results:

5.2 Routing (Key)

A problem with the example in 5.1 is that no matter what address url we enter, it will display the same content, such as: . Etc.

So we can introduce the concept of designing a route, when the user enters a different URL address, we get different content back.

Example:

var http = require('http');
var fs = require('fs');
var server = http.createServer(function(req,res){
   res.setHeader("Content-Type"."text/html; charset=UTF8");
   // If the address is /index, the file index. HTML will be read
   if(req.url === "/index"){
     fs.readFile("./index.html".function(err,data){
        res.end(data);
    })
    // otherwise display Nothing
   }else{
       res.end('Nothing');
   }
})
server.listen(3000)
Copy the code

Effect: Note: the design of the routing address does not mean that the actual physical existence of the path file, this is custom.

Top-level routing design concepts:

The physical file level has nothing to do with the URL. NodeJS can do top-level routing design! A page URL can be customized. Such that the URL entered by the user can map to any HTML page.

5.3 Examples of Top-level Routing Design:

Set has an address http://127.0.0.1:3000/user/… /… Indicates a valid route.

// Get the built-in module, importing the built-in HTTP module of Node.js
var http = require('http');
var fs = require('fs');
// Create a server using the createServer method
// The req parameter in the callback represents the request and the res parameter represents the response
var server = http.createServer(function(req,res){
   res.setHeader("Content-Type"."text/html; charset=UTF8");
   
   // Get the address entered by the user
   var url = req.url;
   // Use regular expression to get address /user first /.. And the second /..
   var arr = url.match(/\/user\/(.+)\/(.+)$/);
   // If there is no corresponding address, an error is reported
   if(! arr){ res.end("

No corresponding page

"
) return; } // The first to get the re var $1 = arr[1]; // The second fetch of the re var $2 = arr[2]; // Simulate some data var user = { "liuyifei":"Liu Yifei"."dilireba":"Dilieba"."yangyin":"Angelababy" } // Simulate some data var list = { "page":"Article"."ask":"Question" } // Returns content based on user input res.write("< h1 > I am"+user[$1] +"~</h1>") res.end("< H2 > Welcome to"+list[$2] +"Module < / h2 >")})// The default port is 80, we use port 3000 server.listen(3000) Copy the code

Effect:

5.4 Problems encountered in top-level Routing Design:

For example, we have a 02.js file as follows: dilireba.html is read when the address is /satr/dilireba.

var http = require('http');
var fs = require('fs');
var server = http.createServer(function(req,res){
   res.setHeader("Content-Type"."text/html; charset=UTF8");
   // When the address is //satr/dilireba, read the dilireba.html file, of course this is custom
   if(req.url === "/satr/dilireba"){
     fs.readFile("./dilireba.html".function(err,data){
        res.end(data);
    })
    // otherwise display Nothing
   }else{
       res.end('Nothing');
   }
})
server.listen(3000)
Copy the code

Dilireba.html contains the following:

 <! DOCTYPEhtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
    <title>Document</title>
</head>
<body>
    <h1>I'm Dilieba</h1>
    <img src="dilireba.jpg">
</body>
</html>
Copy the code

The running results are as follows:

Question: The page has only text display, no image display, but the HTML structure has the IMG tag, why cannot load?

A: The ur1 path for this image does not have a physical folder. Now this picture of the actual physical address is our custom http://127.0.0.1:3000/satr/dilireba.jpg, but the picture of physical storage address is in our local D: \ node_Study, is different, so must not be loaded as needed.

Resolution: both text and pictures are requested:

var http = require('http');
var fs = require('fs');
var server = http.createServer(function(req,res){
   res.setHeader("Content-Type"."text/html; charset=UTF8");
   // If the address is /index, the file index. HTML will be read
   if(req.url === "/satr/dilireba"){
     fs.readFile("./dilireba.html".function(err,data){
        res.end(data);
    })
    // otherwise display Nothing
   }else if(req.url === "/satr/dilireba.jpg"){
      res.setHeader("Content-Type"."image/jpg");
      // get the image
      fs.readFile("./dilireba.jpg".function(err,data){ res.end(data); })}else{
       res.end('Nothing');
   }
})
server.listen(3000)
Copy the code

Results:

The question is, what if there are a lot of images?

Then every image must be requested and rendered, that is, every image must be routed, not just images, but other files as well.

The solution is the Middleware of Express, which we’ll look at later, to statically instantiate a folder. The goal is that the files within the current folder will automatically have URL routing, without having to set each one individually.

Note that you need to set the corresponding ContentType when requesting a file using NodeJS.

Such as:

HTML file:

res.setHeader("Content-Type"."text/html; charset=UTF8");
Copy the code

The CSS file:

res.setHeader("Content-Type"."text/css");
Copy the code

JPG image:

res.setHeader("Content-Type"."image/jpg");
Copy the code

And so on…

Vi. Modules (key points)

What is a module? When a JS file can perform a function independently, the JS file is a module. When multiple.js files perform a function together, the js files are a module. A module is a module.

6.1 HTML Multiple File References:

In an HTML hosting environment, multiple JS files share an HTML host, and their scope is common.

Example: index.html content:

<! DOCTYPEhtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
    <title>Document</title>
</head>
<body>
    <script src="01.js"></script>
    <script src="02.js"></script>
</body>
</html>
Copy the code

01. Js content:

var a = 666;
Copy the code

02. Js content:

alert(a);
Copy the code

Running index.html results:

At this time, 666 can pop up in the page, because a in 01.js file is the global variable, which is the property of window, so 02.js can use window.a, which is 666.

6.2 Node.js multiple file references:

The require() reference file executes at the same time it is referenced.

01.js Content:

console.log("I am 01.js");
Copy the code

02. Js content:

./ indicates the current directory

require("./01.js");
console.log("I am 02.js");
Copy the code

Result of running 02.js:

6.3 Scope isolation of JS files in Node.js:

For example: 01.js File contents:

var a = Awesome!;
Copy the code

02. Contents of js file:

require("./01.js");
console.log(a);
Copy the code

Running results:

The error message is that A is not defined. Because js files are scoped out in NodeJS, because NodeJS doesn’t have window objects.

At this point we want files to be able to communicate with each other, so we need to expose the files themselves. Such as 6.4

6.4 exports command:

01.js Content:

var num = Awesome!;
// Expose the num argument outwards
exports.num = num;
Copy the code

02. Js content:

var a = require("./01.js");
// get the num parameter of file A
console.log(a.num);
Copy the code

Running results:

Of course, it is recommended to standardize naming. Such as 6.5

6.5 Exports namespace:

These three files are all horizontal.

Round. Js content:

function area(r){
    return 3.14 * r * r 
}

exports.area = area;
Copy the code

A rectangle. Js content:

function area(a,b){
    return a * b 
}

exports.area = area;
Copy the code

App. Js content:

var round = require("./round.js");
var rectangle = require("./rectangle.js");

console.log(round.area(6));
console.log(rectangle.area(2.3));
Copy the code

Running results:

Both round. Js and rectangle. Js define the area function, but since we each have our own namespace, we don’t interfere with each other.

Exports can be used to expose multiple arguments, such as round. Js and rectangle.

function area(r){
    return 3.14 * r * r 
}
function perimeter(r){
    return 3.14 * 2 * r
}
exports.area = area;
exports.perimeter = perimeter;
Copy the code

App. Js content:

var round = require("./round.js");
var rectangle = require("./rectangle.js");

console.log(round.area(6));
console.log(rectangle.area(2.3));
console.log(round.perimeter(6));
Copy the code

Results:

6.6 module.exports command:

When a JS file wants to expose only one argument, usually a constructor, we can use the module.exports command to do so.

For example, there is a people.js file with the following content:

function people(name,age,sex){
    this.name = name;
    this.age = age;
    this.sex = sex;
}
// Prototype attributes give you the ability to add attributes and methods to objects.
people.prototype.sayHello = function(){
    console.log("I"+this.name+", I"+this.age+"Oh, what's my sex?"+this.sex+".");
}

module.exports = people;
Copy the code

The contents of app.js are as follows:

var people = require("./people.js");
var xiaohong = new people("Little red".18."Female");
xiaohong.sayHello();
Copy the code

The two files are level.

Results:

Module. exports does not use the same namespace object as exports when new, because module. exports returns results instead of objects by default.

6.7 Using folders:

Suppose there is a file directory hierarchy as follows:

We now put round. Js and rectangle. Js inside a result folder, which is integrated with index.js.

Round. Js content:

function area(r){
    return 3.14 * r * r 
}
function perimeter(r){
    return 3.14 * 2 * r
}
exports.area = area;
exports.perimeter = perimeter;

Copy the code

A rectangle. Js content:

function area(a,b){
    return a * b 
}

exports.area = area;
Copy the code

Index. Js content:

var round = require("./round.js");
var rectangle = require("./rectangle.js");

exports.round = round;
exports.rectangle = rectangle;
Copy the code

App. Js content:

var result = require("./result");
console.log(result.round.area(3));
console.log(result.rectangle.area(1.2));
Copy the code

If we require() without the.js suffix, NodeJS will think we are importing a folder and execute the index.js inside that folder.

var result = require(“./result”); Var result = require(“./result/index.js”);

Running results:

6.8 node_modules folder:

We found that in all of our code examples above, we can’t omit the./ in front of the file, which will cause an error, but in NodeJS, if the folder contains the node_modules folder, then the internal file is imported without a./. It’s amazing.

If we build on 6.7 and create node_modules under work and put result under node_modules, app.js will not be introduced with a./.

The current directory is as follows:App. Js content:

var result = require("result");
console.log(result.round.area(3));
console.log(result.rectangle.area(1.2));
Copy the code

Run without error:

In summary, if we use require to import files, without the./, we import files inside the node_ modules folder, otherwise we import other local folders.

Vii. Basic Use of NPM:

7.1 NPM Installation:

NPM is a worldwide module sharing community where we can use modules developed by others for free.Community links.

NPM is relied on by more than 11 million developers worldwide to make JavaScript development elegant, efficient, and secure.

Install go to the official website to find the module you want, and then install and use it according to the steps provided in the documentation.

7.2 NPM ID card and Dependencies:

The contents of the node_modules folder we downloaded from NPM are called “dependencies”. We can manage these dependencies using package.json, at which point we need to create our own ID card. One of the first things we do when we’re developing a project is create an ID card.

Enter the following command on the terminal:

npm init
Copy the code

Then fill in some form information, such as name, description, you can answer as needed, or press enter to skip.

Then you get something like package.json:

With this ID card, after the installation of dependencies to add – -save

Let’s say we install a module called NZH:

npm install --save nzh 
Copy the code

Then look at the ID card and get the NZH dependency:

Why do you do that?

Node_modules are known to depend on each other, so if you introduce too many modules, the physical file transfer will result in very large and fragmented file contents. So when we physically transfer, we can not pass the node_modules folder, just pass the ID card. So be sure to use the ID card to save, physical transmission is completed, the person can be based on the ID card before the next use, reinstall the need to rely on.

From now on, just type in the corresponding package.json directory:

npm isntall
Copy the code

NPM retrieves dependencies from the package. json file in the corresponding directory and installs them.

Conclusion:

Updated continuously ~