Overview of Node development
1. Why learn the basics of server-side development
With the development of the Internet in recent years, the concept of full stack engineer began to rise, the so-called full stack. This includes user interfaces, business logic, data modeling, servers, networks, and environments. This means that full stack engineers need to be skilled at handling the interactions between the layers. Now, with node.js, JavaScript language can be used for both client-side development, server-side development, and database interaction. In this way, the learning cost of developers is greatly reduced and a good environment is created for program development.
Node.js can be used for website development, backstage server of online games, software part of Internet of Things development, console application, data interaction and so on.
2. Server-side development things to do
- Implement the business logic of the website
- Add, delete, change and check data
3.为什么选择Node
- Develop back-end applications using JavaScript syntax
- The ecosystem is active and there are plenty of open source libraries available
- Front-end development tools are mostly developed based on Node
4. What is Node: the code environment
Second,Setting up the Node running environment
Node.js quick start
1. The Node. Js
- Js consists of three parts: ECMAScript,DOM and BOM
- Node.js consists of ECMAScript and some additional apis provided by the Node environment
2. Basic Syntax of Node.js
1.HelloWorld, the easiest way to build a server
Var HTTP = require(" HTTP "); Var server = http.createserver (function(req,res){//req indicates request, request; Res: response // Set the HTTP header, the status code is 200, the file type is HTML, and the character set is utf8 res.writeHead(200,{" content-type ":"text/ HTML; charset=UTF-8"}); Res.end (" Hahaha, I bought five iphones "+ (1+2+3) + "s"); }); Server.listen (3000,"127.0.0.1"); // Run the server and listen to port 3000 (port number can be changed to '127.0.0.1').Copy the code
Note: Res.end () must be a string
2. Run the Node. Js
1. Run
Node.js is the server program, write JS statements, will run on the server. What is returned to the client is pure HTML that has already been processed. Node[name].js means to run your own file, [name] is your actual file name, and then open the browser
2. Modify
If you want to modify the program, you must interrupt the current running server, node again, refresh, just line. CTRL + C to break the pending server program. Press the up arrow to quickly invoke the nearest Node command.
3. Summary
You’ll notice that if you write js locally, you can’t just drag it into the browser and run it, but with Node, you can run any JS file through Node. In other words, Node is a JS execution environment. So now we’re going to run a server, and the script for that server is going to be stored as.js. Is a JS file. Run the js file with the node command.
3.Node.js Global object
4. Node.js modular development
1. Disadvantages of JS development: file dependency naming conflict
2. Modularization development in software
3. Develop specifications
- Node.js specifies that a JS file is a module, and variables and functions defined inside the module are not available outside the module
- Exports members internally using exports objects and imports other modules using require methods
4. Export module members
const add = (n1, n2) => n1 + n2;
exports.add = add;
Copy the code
5. Import module members
const a = require('./03-module-a');
console.log(a.add(10, 20));
Copy the code
6. Another way to export module members
const greeting = name => `hello${name}`;
module.exports.greeting = greeting;
Copy the code
7. The module exports the connection and difference between the two methods
Exports is an alias (address reference relationship) of module.exports
5. System module
1. What is a system module
The Node runtime environment provides apis for system modules
2. Perform operations on fs files in the system module
Fs: file operating system
const fs=require('fs');
Copy the code
-
Reading file contents
Fs. readFile(' file path/file name ',[' file encoding '], callback); fs.readFile('... ',' utF-8 ',(err,doc) => {// If a file read error occurs, the value of err is the error object; otherwise, the value of err is null. // Doc is the file content console.log(doc); }});Copy the code
-
Write content operation
Fs. writeFile(' file path/file name ',' data ', callback); const fs = require('fs'); Const content = '<h3> </h3>'; fs.writeFile('./01.HelloWord.js', content, err => { if (err ! = null) { console.log(err); return; } console.log(' file was written successfully '); })Copy the code
3. System module Path Path operation: splicing paths
4. Syntax for path stitching
Path. join(' path ',' path ',....) // import path module const path = require('path'); / / path joining together let finalPath = path. Join (' itcast ', 'a', 'b', 'Arthur c. ss'); Itcast \a\b\c.css console.log(finalPath);Copy the code
5. Relative path vs. absolute path
- Most use absolute paths
- Get the absolute path of the current file using __dirname and concatenate it with the path module
Vi. Third-party modules
1. What are third-party modules
There are specific functions, directly used modules, multiple file composition, folder, and package two forms of existence
- It exists in the form of JS files and provides API interfaces for realizing specific functions of the project
- In the form of command line modules, auxiliary functions
2. Obtain the third-party module
Npmjs.com third party module website
- Download:
NPM install Specifies the module name
- Uninstall:
NPM Uninstall Package Module name
Global installation vs. local installation
- Command line tools: Global installation
- Library files: locally installed
3. The third-party module Nodemon: command line tool
Using the step
- use
npm install nodemon -g
download - In command line tools
nodemon
Command instead ofnode
Command line tool: CTRL + C terminates the operation
4. Third-party module NRM: NPM downloads the address switching tool
Domestic download speed is slow, special server to synchronize
Use steps:
- use
npm install nrm -g
download - Query the list of available download addresses
nrm ls
- Switch the NPM download address
NRM use Download address name
5. The third-party module Gulp
Front-end construction tool based on node platform development
6. What can Gulp do
- Project on-line, HTML,CSS,JS file compression merge
- Syntax conversion (ES6,less..)
- Public files are removed
- Modify the file browser automatically refreshes
7. Use Gulp
- use
npm install gulp
download - Create the gulpfile.js file in the project root directory
- The folder structure of the refactoring project is the SRC directory for the source files and the dist directory for the post-build files
- Write it in gulpfile.js
- Command line execution file
8. Methods provided in Gulp
-
Gulp.src (): Gets the file to be processed by the task
-
Gulp.dest (): Output file
-
Gulp.task (): Creates a gulp task
-
Gulp.watch (): Monitors file changes
// const gulp = require('gulp'); Gulp.task ('first', () => {console.log(' first gulp task executed in my life '); SRC ('./ SRC/CSS /base.css').pipe(gulp.dest('dist/ CSS ')); });Copy the code
Then download gulp-cli -g global installation from the command line and gulp first to execute the JS file
9.Gulp plugin —— download reference call
gulp-htmlmin
: HTML file compressiongulp-csso
Compression CSS:gulp-babel
: js syntax conversiongulp-less
: less Syntax conversiongulp-uglify
: compressing obfuscate JSgulp-file-include
Public files containbrowsersync
Real-time Browser synchronization
Package. json file
1. Node_modules folder meaning
The transmission speed is slow, and the version must be consistent. Otherwise, an error will be reported
2. Functions of package.json files
Project description file, record the current project information… Run the NPM init -y command
3. Project Dependence:npm install --production
"Dependencies" : {" formidable ":" ^ 1.2.2 ", "gulp" : "^ 4.0.2", "mime" : "^ 2.5.0"}Copy the code
Note: NPM install will download all third-party modules
4. Development dependency: third-party packages need to be relied on in the project development stage, but not in the online operation stage
npm install gulp --save-dev
"DevDependencies ": {"gulp": "^4.0.2"}Copy the code
5. Package – lock. The role of json
- Lock the version of the package to ensure that the next download will not cause problems due to the version
- Speed up package downloads
Usage of aliases
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "nodemon app.js"
},
Copy the code
Command line: NPM run build
Module loading mechanism in Node.js
1. Module lookup rule – —-require(‘./find.js’) when module has path but no suffix; Find. Js –> index. Js –> package.json –> find entry file in main option –> error
2. Require (‘find’) when a module has no path but no suffix Node.js assumes that it is a system module –> look for the js file with the same name in node_modules –>find the index.js file –> package.json file to find the entry file in main –> error
Basic concepts of server side
- Site composition: client side and server side
- Node web server: receives and responds to requests
- IP address: Internet protocol address that uniquely identifies a device on the Internet
- Domain name: web address used to access the Internet
- Port: An outlet for communication between a computer and the outside world, used to distinguish between the different services provided in a server computer
- URL: and web address
- URL composition: Transport protocol: // Server IP address or domain name: port/resource location identifier
- Description of client and server during development
Developer PC: Browser +Node Local domain name: locallhost Local IP: 127.0.0.1
Create a Web server
// module used to create web server const HTTP = require(' HTTP '); //app object is the web server object const app = http.createserver (); / / when the client request to the app. On (' request '(the req, res) = > {res. The end (' < h2 > hello user < / h2 > "); }); // Listen to app.listen(3000); Console. log(' website server started successfully ');Copy the code
Nodemon app.js // Updates the JS file automatically
HTTP protocol
1. Concept of HTTP protocol: Hypertext transfer protocol
2. The message
3. Request packets
1. Request Method
- GET request data
- POST Sends data
- Obtaining request method:
req.method
2. Request URL
- Get the requested address:
req.url
- Obtain request message information:
req.headers
4. Respond to the packet
1. The HTTP status code
- 200 Request succeeded
- 404 requested resource not found
- 500 Server error
- 400 The client request has a syntax error
res.writeHead(400);
2. Content type
5.HTTP request and response processing
1. Request parameters such as login operations
2.GET Request parameters
-
Parameters are placed in the browser address bar
// require('url') const url = require('url'); Let {query, pathName} = url.parse(req.url, true); // console.log(url.parse(req.url, true).query); console.log(query.name); console.log(query.age);Copy the code
3.POST request parameters
- Parameters are placed in the request body for transmission
- The DATA event and end event are used to get the POST parameter
- Use queryString system module parameters to convert to object format
4. Routing: the mapping between the client’s request address and the server’s program code
5. Static resources: directly respond to users, such as HTML, CSS and JS, without server processing
6. Dynamic resources: response resources with different addresses for the same request
Node.js asynchronous programming
1. Synchronous API, asynchronous API
- Synchronous API: The next API can be executed only after the current API is executed
- Asynchronous API: Execution of the current API does not block execution of subsequent code
2. Difference between synchronous API and asynchronous API (get return value)
The synchronous API can get the result of the API execution from the return value, but the asynchronous API cannot
3. Callback functions
function getMsg(callback) {
setTimeout(() => {
callback({
msg: 'hello node.js'
})
}, 2000);
}
getMsg(function(data) {
console.log(data);
})
Copy the code
4. Difference between synchronous API and asynchronous API (code execution order)
Asynchronous APOS do not wait for API execution to complete before executing code down
5. Asynchronous apis in Node.js
File read/event listening API
6.Promise
Fix callback hell in Node.js asynchronous programming
7. Asynchronous functions: Asynchronous code is written in synchronous form
const fn =async () => {};
async function fn() {};
Copy the code
- To precede the normal function definition
async
The keyword becomes an asynchronous function - The default return value for asynchronous functions is
promise
object - Used inside asynchronous functions
return
Keyword to return results will be wrapped inpromise
Object replaces the resolve method with the return keyword - Used in asynchronous functions
throw
Keyword throws a program exception - Call asynchronous function and chain call
then
Method to get the result of asynchronous function execution - Call asynchronous function and chain call
catch
Method to get an asynchronous function execution error message
The await keyword
- Can only occur in asynchronous functions
await promise
It can pause the execution of the asynchronous function and wait for the promise object to return the result