I haven’t written for a long time, so I’m kind of back in the community. Dear friends, I am back! Haha, without further ado, today let’s talk about node.js, the back-end language that is easiest to get started with on our front end. In fact, relative to Node. js is early heard, but forced by no systematic learning, before always a little understanding, even do not know how to use? For what? In recent period of time, under the guidance of the great god, now it is a little door, so write down this note, if there is a mistake in the text, but also hope that you pass by the great God to help give directions. The little lady is being polite here!

A list,

Node.js is a JavaScript runtime environment based on Chrome V8 engine. Node.js uses an event-driven, non-blocking I/O model, making it lightweight and efficient. - NodeJS website introductionCopy the code

“Node.js is simply JavaScript running on the server side.”


1. Purpose Analysis:

  1. Middle tier (security, high performance, reduced primary server complexity) :

Node.js can be used as the middle layer between the client and the server, which is used to bridge the two ends, avoiding direct exposure of the master server and ensuring the security of the master server. And the middle tier can do a number of customizations to improve access speed, reduce the complexity of the primary server, and so on.

  1. Small service

Node.js can be built as a small service, making it easier to use

  1. Tool class development

Node.js is fast and can be used to develop a variety of packaging, conversion and other tools, such as webpack,gulp, Babel…


2. Advantages of front-end learning:

  1. Easy to start with the front end, the same syntax and front js
  2. High performance (using Chrome’s V8 engine)
  3. Better integration with front-end code

3. Get started quickly:

  1. Download address:

    Official: nodejs.org/en/

    English: nodejs. Cn /

  2. Command execution:

    Download version:

node -v
Copy the code

The inputnodeAfter press Enter, the calculation can be performed directly on the command line, as follows:

Development:

Node comes with an NPM for downloading libraries, tools, and more.


Two, the system has its own module method

To introduce a few more commonly used system system module, direct reference can be used.

Before introducing the module, let’s do a little test to see if our js file works:

The console. The log (" node ")Copy the code

Console output:

After the test is complete, the console can display normally and proceed to the next step.


Let’s formally introduce our module.

1. HTTP module:

This module is the most basic module used in Node. It is used to start our service and listen for the corresponding port.

// const HTTP = require(" HTTP "); Http.createserver ((req,res)=>{console.log(" Request coming "); }).listen(8000) // 8000 listener port numberCopy the code

Next, go to the console and execute this file:

Then manually enter the port number we are listening to in the browser:

localhost:8000
Copy the code

Return to the console to view the listening result:

At this point we can successfully start the server and listen for the corresponding port

In http.createServer, there are two parameters: request and response. We’ll use them several times later.

  • Request: short: req:
const http =  require("http"); 


http.createServer((req,res)=>{
   
    console.log(req);
 
}).listen(8000)  
Copy the code

There are so many parameters that I can’t show them in screenshots.

Req. url and ruq.method

const http = require("http"); Http.createserver ((req,res)=>{// req.url gets the path of the current port // req.method Gets the current request console.log(req.url,req.method) }).listen(8000)Copy the code

Browser input:

http://localhost:8000/root/abc
Copy the code

View console output:

  • response:res

Let’s see what’s in it first

const http =  require("http");

http.createServer((req,res)=>{

    console.log(res)
    
}).listen(8000)
Copy the code

Like res, the content is endless

We’ll start today with one of these methods,res.write(), which writes to the browser:

const http = require("http"); Http.createserver ((req,res)=>{res.write(" ABC ") // Write to browser, only string console.log(" Request coming "); Res.log (res)}).listen(8000)Copy the code

Next, go to the console and execute the file, manually entering the following address in your browser:

http://localhost:8000
Copy the code

To view the browser display effect, it has been written to the browser:


2. Path module:

Used to parse the path, get the corresponding file name, extension and path, etc.

  • path.dirname() Get directory name
const http = require("http");

const path = require("path");

http.createServer((req,res)=>{

    console.log(path.dirname(req.url));

}).listen(8000)
Copy the code

Start the server from the console, run the js code above, and enter the following address in the browser:

http://localhost:8000/root/build/a.text
Copy the code

Return to view console execution:

  • path.basename() Get file name
const http = require("http");

const path = require('path');

http.createServer((req,res)=>{

    console.log(path.basename(req.url))
    
}).listen(8000)

Copy the code

Start the server from the console, run the js code above, and enter the following address in the browser:

http://localhost:8000/root/build/a.text
Copy the code

Return to view console execution:

  • path.extname() Gets the file extension
const http = require("http");

const path = require("path");

http.createServer((req,res)=>{

    console.log(path.extname(req.url)) 

}).listen(8000)
Copy the code

Start the server from the console, run the js code above, and enter the following address in the browser:

http://localhost:8000/root/build/a.text
Copy the code

Return to view console execution:

  • path.resolve() Used to parse a series of chaotic paths to get the final path
const http = require("http"); const path = require("path"); Http.createserver ((req,res)=>{console.log(path.resolve("__dirname","build") console.log(path.resolve('root/a/b','.. /c','build',".." ,"strict")) // parse path}).listen(8000)Copy the code

The console starts the server, runs the js code above, and the browser enters the following address

http://localhost:8000
Copy the code

View console execution


3. urlThe module

Used to return the url path to which parsing is completed

const url = require("url"); let str="http://localhost:8080/root/a/b? a=1&b=8"; console.log(url.parse(str,true))Copy the code

The console starts the server, runs the js code above, and looks at the parsing results

The second argument, true, converts the query argument in the URL to JSON format


4. querystringModule, parameter format conversion

  • querystring.parse() Parse the url parameters intojson
const querystring = require("querystring");

console.log(querystring.parse("a=12&b=5&c=2")) 

Copy the code

The console starts the server, runs the js code above, and looks at the parsing results

  • querystring.stringify()Reverse parse json into ampersand format
const querystring= require("querystring");

let json={"a":5,"b":8};

console.log(querystring.stringify(json)) 

Copy the code

The console starts the server, runs the js code above, and looks at the parsing results


5. assertThe module

When an assert assert is encountered in a block of code, no processing is done. If the condition is correct, an exception is thrown and no further execution is performed

const assert = require ('assert'); // assert(condition, error MSG) Assert (5<3,' error ') console.log("123")Copy the code

The console starts the server, runs the js code above, and looks at the parsing results

  • assert.deepEqual() Depth equality judgment, only compare value, not type, “==” in equality and operation
const assert = require("assert"); const boo = 55; Assert.deepequal (Boo,"55"," Error ")Copy the code

The console starts the server, runs the js code above, and looks at the parsing results

  • assert.deepStrictEqual() Depth strict equality judgment, “===” in equality and operation
const assert = require("assert"); Const boo = {2, a: 1, b: c: / "555"} assert. DeepStrictEqual (boo, {2, a: 1, b: c: [555]}, "wrong")Copy the code

Method can be used for function call, parameter passing judgment, or large calculation result judgment, avoid because of parameter error, resulting in program error.


6. fsModule that can be used to read files, write files, copy resource files to target files, etc.

Fs.readfile () reads the file

  • The first parameter is the file location and file name
  • The second argument is the callback function

Read the localdataThe folder2.text

Local 2.text file

const fs = require("fs"); // The readFile() method takes two arguments, ReadFile ("./data/2. TXT ",(err,data)=>{if(err){console.log(" failed ")}else{fs.readfile ("./data/2. TXT ",(err,data)=>{if(err){console.log(" failed ")}else{ Console. log(" successful ", data.tostring ())}})Copy the code

The console starts the server, runs the js code above, and looks at the parsing results

Let’s try reading the image and writing it to the browser

HTML part:

<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, <meta HTTP-equiv =" x-UA-compatible "content=" IE =edge"> <title>Document</title> </head> <body> < p > I have a picture < / p > < img SRC = ". / data/timg. Jpeg "> < / body > < / HTML >Copy the code

Js:

const http = require("http"); const fs = require('fs'); Let server= http.createserver ((req,res)=>{console.log(req.url) fs.readfile ('./${req.url} ',(err,buffer)=>{// Process the request, If (err){res.writehead (404); res.write('Not Found6',err); console.log(err) res.end(); }else{ res.write(buffer); res.end(); }})}); server.listen(8000);Copy the code

The console starts the server, runs the js code above, and the browser enters the following address:

http://localhost:8000/img.html
Copy the code

Viewing parsing Results

Fs.writefile () writes to a file

  • The first parameters are the location to add and the file name
  • The second parameter is what was written
  • The third argument is the callback function

Write 1.text to the local data folder

const fs = require("fs"); Fs. WriteFile ('. / data / 1. TXT ', ` `, ABC (err) = > {the if (err) {the console. The log (" fail ")} else {the console. The log (" success ")}})Copy the code

The console starts the server, runs the js code above, and looks at the parsing results

View my local file:

Implement a copy from 2.text to 1.text

const fs = require("fs");

( (source,target)=>{
    let result = fs.readFileSync(source,'utf8');
    fs.writeFileSync(target,result)
    
})('./data/2.txt','./data/1.txt');

Copy the code

The console starts the server, runs the js code above, and views the two files

Three, to achieve onegetAnd apostrequest

1. To implement onegetRequested login

HTML part:

<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, <meta HTTP-equiv =" x-UA-compatible "content=" IE =edge"> <title>Document</title> </head> <body> <form Action = "http://localhost:8000/abc" method = "get" > user name < input type = "tet" name = "usernam" > < br / > < input type = "password" password Name = "pass" > < br / > < input type = "submit" value = "submit" > < / form > < / body > < / HTML >Copy the code

Js:

const http = require("http"); const querystring = require("querystring"); http.createServer((req,res)=>{ console.log(req.url); let [url,query] = req.url.split("?" ); console.log(url,query); let get =querystring.parse(query); console.log(get) }).listen(8000)Copy the code

The console starts the server, runs the js code above, views the foreground page, and submits the username and password:

View console data:


2. To implement onepostRequested login

HTML part

<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, <meta HTTP-equiv =" x-UA-compatible "content=" IE =edge"> <title>Document</title> </head> <body> <form Action = "http://localhost:8000/abc" method = "post" > username: < input type = "text" name = "username" > < br / > password: < form> </body> </ HTML >Copy the code

Js:

const http = require("http"); const querystring = require("querystring"); // let arr=[]; let arr=[]; Let server= http.createserver ((req,res)=>{// Receive data req.on('data',buffer=>{arr.push(buffer)}); Req. on('end',()=>{let buffer = buffer.concat (arr); let post = querystring.parse(buffer.toString()) console.log(post) }) }); server.listen(8000);Copy the code

The console starts the server, runs the js code above, views the foreground page, and submits the username and password:

View the data returned from the console:


(3) integrationgetandpostrequest

HTML part:

<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, <meta HTTP-equiv =" x-UA-compatible "content=" IE =edge"> <title>Document</title> </head> <body> <form Action = "http://localhost:8000/abc" method = "post" > user name < input type = "tet" name = "usernam" > < br / > < input type = "password" password Name = "pass" > < br / > < input type = "submit" value = "submit" > < / form > < / body > < / HTML >Copy the code

Js:

const http = require("http"); const querystring = require("querystring"); http.createServer((req,res)=>{ // console.log(req.method) if(req.method==='GET'){ // console.log(req.url) let [url,query] = req.url.split("?" ); let get = querystring.parse(query); console.log(url,get) }else{ let arr=[]; req.on("data",(buffer)=>{ // console.log(buffer) arr.push(buffer) }); req.on("end",()=>{ let buffer= Buffer.concat(arr); let post = querystring.parse(buffer.toString()); url= req.url console.log(url,post) }) } }).listen(8000)Copy the code

The console starts the server, runs the js code above, views the foreground page, and submits the username and password:

View the data returned from the console:

Four, to achieve a simple login & registration of the front and back end data interaction

Now we integrate the methods mentioned above to implement a front and back page interaction, including interface calls and normal page interaction actions.

HTML part:

<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, "> <meta http-equiv=" x-UA-compatible "content=" IE =edge"> <title>Document</title> <script SRC ="./jquery-1.7.2.js"></script> </head> <body> User name <input type="tet" id="user"><br/> Password <input type="password" Id ="pass"><br/> <input type="button" id="btn1" value=" register ">< script> $(function(){ $("#btn1").click(()=>{ $.ajax({ url:"/reg", dataType:"json", data:{ username:$("#user").val(), Password: $(" # pass "). The val ()}}), then ((json) = > {the if (json. The error) {alert (json. MSG)} else {alert (" registration ")}}, the error = > { Alert (" registration failed, please refresh and try again ")})}); $("#btn2").click(()=>{ $.ajax({ url:"/login", dataType:"json", data:{ username:$("#user").val(), Password: $(" # pass "). The val ()}}), then ((json) = > {the if (json. The error) {alert (json. MSG)} else {alert (" login succeeds ")}}, the error = > { Alert (" login failed, please refresh and try again ")})}); }) </script> </body> </html>Copy the code

Display effect:


Js:

const http = require('http'); const querystring = require('querystring'); const url = require('url'); const fs = require('fs'); let users ={} http.createServer((req,res)=>{ let path ='',get={},post={}; console.log(req.method) if(req.method === 'GET'){ let {pathname,query}= url.parse(req.url,true) path = pathname; get = query; console.log() complete() }else{ let arr =[]; path = req.url req.on("data",buffer=>[ arr.push(buffer) ]); req.on('end',()=>{ let buffer = Buffer.concat(arr) post = querystring.parse(buffer.toString()) // complete() }) } Function complete(){// console.log(path,get,post) // register if(path =='/reg'){let {username,password} = get; If (users[username]){res.write(json.stringify ({error:1, MSG :' This username already exists '})); res.end() }else{ users[username] = password; Res.write (json.stringify ({error:0, MSG :' registered successfully '})); Res.end ()}}else if(path == '/login'){// login let {username,password} = get; if(users[username]){ if(users[username] ! == password){res.write(JSON. Stringify ({error:1, MSG :' password error '})); Res.end ()}else{res.write(json.stringify ({error:0, MSG :' login succeeded '})); Res.end ()}}else{res.write(json.stringify ({error:1, MSG :' This user does not exist '})); res.end() } }else{ fs.readFile(`./${path}`,(err,buffer)=>{ if(err){ res.writeHead(404); res.write('Not Found'); res.end() }else{ res.write(buffer); res.end() } }) } } }).listen('8000')Copy the code

The console starts the server, runs the js code above, views the foreground page, and submits the username and password:


To be continued…..

Author: sunny day DE rain Source: https://juejin.cn/post/6844903614377361422 all rights reserved, welcome to retain the original link reproduced: want to see my latest articles can be added under the attention oh!)Copy the code