directory

 

 

 

What is NPM

Second, the command line program

Third, commander. Js

Iv. NPM package management

Node provides a link to download the image

Use the node native HTTP module write interface

7. Use node native HTTP module to realize all interfaces of shopping cart (no package or middleware required)

8. Node native write interface, build static Web server, process front-end history routing

9. Install FileZilla server

10. Install FileZilla client

11. Aliyun configuration supports FTP

Twelve, colors,

Express Scaffolding

NPM View command

14, String

Node is single-threaded

Error handling

The 17th and the process. NextTick (the callback)

Print the animal according to the subscript

Node reads file directories from web pages

Rename files or folders

Js distinguishes between object functions and arrays

Event triggers

Manual encapsulation events

Parent-child process communication

Docker

26. Koa

How to interrupt node debugging

Mysql > select * from ‘char’ where varchar = ‘varchar

Mysql > select * from ‘mysql’

Mysql primary key

31. Install the VM


 

 

 

 

 

 

 

 

 

 

 

 

 

 

Node.js is single-threaded, event-based, non-blocking IO. An event loop uses an event queue. At each point in time, the system only processes one event. Even if a computer has multiple CPU cores, it cannot process multiple events simultaneously and in parallel. Therefore, Node.js is suitable for I/O applications, not CPU intensive ones. In I/O applications, a callback function is defined for each input/output. Node.js automatically adds this callback function to the event polling processing queue. When the I/O operation is complete, this callback function will be triggered and the system will continue to process other requests.

What is NPM

NPM is a package management tool for javascript, which is a signature product of front-end modularization. Simply put, it is through NPM download modules, reuse the existing code, improve work efficiency.

  • 1. From the perspective of the community: publish modules for a specific problem to the NPM server for others in the community to download and use, and at the same time, you can find resources for specific modules in the community to solve the problem
  • 2. From the team’s point of view: With the package management tool NPM, it is much easier to reuse the team’s existing code

Create a new project, CD it in, and execute NPM init to initialize the configuration of the project.

Before implementing NPM init, there are two things to note:

  • The package name must be unique
  • NPM restrictions on package names: cannot contain uppercase letters/Spaces/underscores

NPM init Press enter

Or: NPM init -y

Generated package.json file:

Name and Version are unique identifiers. Change the version number every time you send a package.

Description: describe

This file is automatically found when someone installs your NPM package

Scripts: scripts NPM run test or YARN test

Keywords: keywords. Put introduction, string. Easy for others to find.

Author: the author

License: license

ISC License: baike.baidu.com/item/ISC%E8…

MIT License: baike.baidu.com/item/MIT%E8…

Files: Files is an array that contains the files in the project. If you name a folder, it will also include the files in the folder.

{
  "name": "xu-20191024"."version": "1.0.0"."description": ""."main": "index.js"."scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": []."author": ""."license": "ISC"
}
Copy the code
{
  "name": "xu-20191024"."version": "1.0.2"."description": "1705E, project Practice."."main": "index.js"."scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": ["1705E"."1706E"]."author": "Xu Tongbao"."license": "ISC"
}
Copy the code

Check whether the package name exists:

www.npmjs.com/package/xu-…



By keywords:

Repository: NPM associated with Git

  "repository": {
    "type": "git"."url": "https://github.com/xutongbao"
  },
Copy the code

Homepage: the official website of the project

  "homepage": "https://blog.csdn.net/xutongbao".Copy the code

 

Dependencies and devDependencies:

When the NPM package is published, the module under its dependencies is downloaded as a dependency. The module below devDependencies does not download automatically; For projects, however, NPM install automatically downloads devDependencies and the module below them.

When others use our plugin, peerDependencies tells you explicitly which host version of the plugin you want to install:

  "dependencies": {
    "axios": "^ 0.19.0"
  },
  "devDependencies": {
    "element-ui": "^ 2.12.0"
  },
  "peerDependencies": {
    "react": "^ 16.11.0"
  },
  "optionalDependencies": {
    "redux": "^ 4.0.4." "
  }
Copy the code

Reference links:

Blog.csdn.net/yq_oxygen/a…

Cloud.tencent.com/developer/a…

Nodejs.org/zh-cn/blog/…

OptionalDependencies:

OptionalDependencies. You can use optionalDependencies if you have dependencies that will run even if the installation fails or if you want NPM to continue running. Also, optionalDependencies overwrites dependencies of the same name, so don’t write them in both places.

Bin field:

Reference links:

Blog.csdn.net/feng98ren/a…

src/index.js:

Make sure your index.js file starts with #! /usr/bin/env node, otherwise the script in the file will not be executed under node

#! /usr/bin/env node
console.log(1)
Copy the code
  "bin": {
    "myapp": "./src/index.js"
  },
Copy the code

Global installation:

 

Common commands:

npm config list

npm config ls -l
Copy the code

Install the NPM package to Dependencies:

npm install commander --save-prod

npm install commander --save

npm install commander -S

npm install commander

npm add commander

npm i commander
Copy the code

Install the NPM package to devDependencies:

npm install commander --save-dev

npm install commander -D
Copy the code

Uninstalling NPM packages:

npm uninstall commander

npm unlink commander

npm remove commander

npm rm commander

npm un commander

npm r commander
Copy the code

Install to global:

npm install create-react-app -g
Copy the code

Delete from global:

npm un create-react-app -g 
Copy the code

 

 

 

 

Second, the command line program

console.log('hello world! ')
Copy the code

Command line arguments:

1)

console.log('hello world! ', process.argv[2])
Copy the code

2)

console.log('hello world! ', process.argv[1])
Copy the code

Third, commander. Js

Use the.option() method to define options for Commander

The short flag can be passed as a single ARG, for example -abc corresponds to -a – b-c.

Multi-word options like “–template-engine” become program.templateengine, etc

<> indicates mandatory, and [] indicates optional. Optional can set the default value

.version(‘0.0.1’) Use node app -v to check the version

.version(‘0.0.1’, ‘-v, –version’) Use node app -v or node app –version to check the version

Use node app -h or Node app –help to view help

The program.parse method is used to parse process.argv and can be used by program. XXX after parsing

const program = require('commander');
 
program
  .version('0.0.1')  //node app -V
  / / version (' 0.0.1 ', '-v - version) / / node app - v
  .option('-d, --debug'.'output extra debugging')
  .option('-s, --small'.'small pizza size')
  .option('-p, --pizza-type <type>'.'flavour of pizza');
  
program.parse(process.argv);
 
if (program.debug) console.log(program.opts());
console.log('pizza details:');
if (program.small) console.log('- small pizza size');
if (program.pizzaType) console.log(` -${program.pizzaType}`);
Copy the code

Sum:

const program = require('commander');
 
program
  .version('0.0.1')
  .option('-a, --my-a, <a>'.'First value')
  .option('-b, --my-b, <b>'.'Second value')
  .parse(process.argv);

console.log(program.myA)
console.log(program.myB)
console.log(program.myA*1 + program.myB*1)
Copy the code

Sum 2:

const program = require('commander');
 
program
  .version('0.0.1')
  .option('-a, --add'.'sum')
  .parse(process.argv);
  
if (program.add) {
  let sum = 0
  program.args.forEach(item= > {
    sum += item * 1
  })
  console.log(sum)
}
Copy the code

Factorial:

const program = require('commander');
 
program
  .version('0.0.1')
  .option('-a, --add'.'sum')
  .option('-f, --factorial <num>'.'factorial')
  .parse(process.argv);

const factorial = (num) = > {
  if (num < 0) {
    return -1
  } else if (num === 0 || num === 1) {
    return 1
  } else {
    return num * factorial(num - 1)}}if (program.add) {
  let sum = 0
  program.args.forEach(item= > {
    sum += item * 1
  })
  console.log(sum)
} else if (program.factorial) {
  let result = factorial(program.factorial)
  console.log(result)
}
Copy the code

Multi-word forms:

const program = require('commander');
 
program
  .version('0.0.1')
  .option('-a, --my-add'.'Sum, multiword form')
  .parse(process.argv);

/ / hump
if (program.myAdd) {
  let sum = 0
  program.args.forEach(item= > {
    sum += item * 1
  })
  console.log(sum)
}
Copy the code

Options that begin with –no represent the opposite of the word immediately following:

const program = require('commander');
 
program
  .version('0.0.1')
  .option('-a, --no-add'.'Summation, options beginning with --no, representing the opposite of the word immediately following it')
  .parse(process.argv);

console.log(program)  

if (program.add) {
  let sum = 0
  program.args.forEach(item= > {
    sum += item * 1
  })
  console.log(sum)
} else {
  console.log('invert')}Copy the code

Command method to customize a command

Description method, a descriptive statement of the command

Action method, which defines the callback function for the command

const program = require('commander');
program
  .version('1.0.0')
  .command('my-add <num>')
  .option('-a, --add, <num>'.'add')
	.action((num, cmd) = > {
    console.log(num, cmd.add)
  })

program
  .option('-u, --upadte'.'update')  
  .description('Description info!! ')
  
program.parse(process.argv)
Copy the code

Reference links:

Juejin. Cn/post / 684490…

www.npmjs.com/package/com…

Iv. NPM package management

Release NPM package:

1. Register an NPM account

2. Login to the terminal using the NPM account: NPM login press enter and enter the user name, password, and email address

3. Create a new folder, CD it to the newly created folder, and use NPM init to generate package.json

4. Publish NPM: publish NPM: publish NPM: publish NPM: publish NPM: publish NPM

 

Yarn update package:

yarn upgrade
Copy the code

Node provides a link to download the image

 

const fs = require('fs')
const request = require('request')
const program = require('commander')

program
  .option('-d, --down <url>'.'download')
  .parse(process.argv)
  
let url = program.down

const name = url.slice(url.lastIndexOf('/') + 1)
request(url).pipe(fs.createWriteStream('/' + name));

//node app -d https://n3-q.mafengwo.net/s15/M00/16/18/CoUBGV2xnO6ALntcAB_DZLkVUnY568.png
//node app -d https://p4-q.mafengwo.net/s15/M00/B3/B1/CoUBGV2wYYmAAByNACD9lHJSPKY794.png
//node app --down https://n2-q.mafengwo.net/s15/M00/D0/E4/CoUBGV2vBYGAbzADAB1W_rqrlCM012.png
Copy the code

Use the node native HTTP module write interface

Cross domain:

Access-control-allow-origin = access-Control-allow-headers = access-Control-allow-headers = access-Control-allow-headers = access-Control-allow-headers; Multiple custom request headers are separated by commas in the English state.

  / / across domains
  res.setHeader('Access-Control-Allow-Origin'.The '*')  // You can change * to http://localhost:3000 to avoid XSS attacks
  / / res. SetHeader (' Access - Control - Allow - the Methods', 'the GET, PUT, POST, PATCH, DELETE, HEAD, OPTIONS') / / release method
  res.setHeader('Access-Control-Allow-Headers'.'content-type')  // The request header for release
  res.setHeader('Access-Control-Max-Age'.1800)  // Precheck requests are initiated every 30 minutes, 1800 seconds
Copy the code

Url, parse:

url.parse(‘http://localhost:3000/api/list? id=0’) :

url.parse(‘http://localhost:3000/api/list? id=0’, true) :

204 Status Code:

The request was received, but the return message is empty. The request executes successfully, but there is no data, and the browser does not need to refresh the page. You don’t have to navigate to a new page. Often used for cross-domain requests.

Cross-domain request:

OPTIONS is a pre-check request. When processing a cross-domain access request, the browser sends a pre-check request to the server if the request is complex. The browser determines whether the server allows the request based on the returned content. If the Web server supports cross-domain access in the manner of CORS, this precheck request is unavoidable when handling complex requests.

The best we can do is to reduce the number of prechecks by setting access-Control-max-age so that only one precheck will occur.

The browser’s same-origin policy limits cross-domain HTTP requests (such as asynchronous GET, POST, PUT, DELETE, OPTIONS, etc.) from scripts for security reasons, so the browser makes two requests to the requested server. The first precheck request is sent by the browser using the OPTIONS method. The second truly asynchronous request is sent. The first precheck request tells the server whether the cross-domain request is allowed. If not, the second request is intercepted.

Access-control-max-age specifies the validity period of the precheck request, in seconds, during which no other precheck request is sent.

Such as:

Res.setheader (‘ access-Control-max-age ‘, 1800) indicates that precheck requests are initiated every 30 minutes. That is, send the request twice

 

7. Use node native HTTP module to realize all interfaces of shopping cart (no package or middleware required)

const http = require('http')
const fs = require('fs')
const url = require('url')
const { bookNavData, bookMallData, userList } = require('./data')

let bookList = []

const server = http.createServer((req, res) = > {
  / / across domains
  res.setHeader('Access-Control-Allow-Origin'.The '*')  // You can change * to http://localhost:3000 to avoid XSS attacks
  / / res. SetHeader (' Access - Control - Allow - the Methods', 'the GET, PUT, POST, PATCH, DELETE, HEAD, OPTIONS') / / release method
  res.setHeader('Access-Control-Allow-Headers'.'content-type')  // The request header for release
  res.setHeader('Access-Control-Max-Age'.1800)  // Precheck requests are initiated every 30 minutes, 1800 seconds
  
  let { pathname } = url.parse(req.url, true)
  console.log(req.method, url.parse(req.url, true))
  console.log(pathname)

  if (req.url === '/') {   //hello world!
    res.writeHead(200, { 'Content-Type': 'text/html' })
    res.write('hello world! ')
    res.end()
  } else if (req.url === '/home') {  / / routing
    res.writeHead(200, { 'Content-Type': 'text/html' })
    const home = fs.readFileSync('./index.html')   / / read the file
    res.end(home)
  } else if (req.url === '/banner01') {   / / picture
    //res.writeHead(200, { 'Content-Type': 'image/jpg' })
    const banner01 = fs.readFileSync('./images/banner01.jpg')  / / read pictures
    res.end(banner01)
  } else if (req.method == 'OPTIONS') { // Cross-domain, processing options requests
    res.writeHead(204) No content / / 204
    res.end()
  } else if (req.method === 'POST' && pathname === '/api/login') { / / login
    let body = ' '

    // Every time the request body is received, it is added to the body variable via req's data event listener
    req.on('data'.(chunk) = > {
      body += chunk
    })

    Parse parse the body into the actual POST request format after the end event is triggered
    req.on('end'.() = >{
      body = JSON.parse(body)
      let { username, password } = body
      let user = userList.find(item= > item.username === username)
      res.writeHead(200, { 'Content-Type': 'application/json' })
      if (user) {
        if (user.password === password) {
          res.write(JSON.stringify({
            code: 200.data: {
              username
            },
            message: 'Login successful'}}))else {
          res.write(JSON.stringify({
            code: 400.message: 'Password error'}}}))else {
        res.write(JSON.stringify({
          code: 400.data: body,
          message: 'User does not exist'
        }))
      }
      res.end()
    })
  } else if (pathname === '/api/nav') {  / / navigation
    res.writeHead(200, { 'Content-Type': 'application/json' })
    res.end(JSON.stringify({
      code: 200.data: bookNavData,
      message: 'navigation'}}))else if (pathname === '/api/list') {  / / list
    let { id } = url.parse(req.url, true).query
    let list = bookMallData.find(item= > item.id == id).list
    list.forEach(item= > {
      if (bookList.findIndex(book= > book.id === item.id) >= 0) {
        item.is_in_my_book = true
      } else {
        item.is_in_my_book = false
      }
    })
    res.writeHead(200, { 'Content-Type': 'application/json' })
    res.end(JSON.stringify({
      code: 200.data: list,
      message: 'list'}}))else if (pathname === '/api/get_book_list') { / / bag
    res.writeHead(200, { 'Content-Type': 'application/json' })
    res.end(JSON.stringify({
      code: 200.data: bookList,
      message: 'bag'}}))else if (pathname === '/api/add') {  // Add to the bag
    let body = ' '
    req.on('data'.(chunk) = > {
      body += chunk
    })

    req.on('end'.() = > {
      body = JSON.parse(body)
      let { item } = body
      bookList.push(item)
      res.writeHead(200, { 'Content-Type': 'application/json' })
      res.end(JSON.stringify({
        code: 200.data: bookList,
        message: 'Added successfully'}}})))else if (pathname === '/api/detail') {   / / details
    let { id } = url.parse(req.url, true).query
    let detail
    bookMallData.forEach(listItem= > {
      listItem.list.forEach(book= > {
        if (book.id == id) {
          detail = book
        }
      })
    })

    if (bookList.find(book= > book.id === detail.id)) {
      detail.is_in_my_book = true
    } else {
      detail.is_in_my_book = false
    }
    res.writeHead(200, { 'Content-Type': 'application/json' })
    res.end(JSON.stringify({
      code: 200.data: detail,
      message: 'details'}}))else if (pathname === '/api/delete') {  / / delete
    let body = ' '
    req.on('data'.(chunk) = > {
      body +=chunk
      console.log('chunk:', chunk)
    })
    req.on('end'.() = > {
      body = JSON.parse(body)
      let { ids } = body
      bookList = bookList.filter(item= >! ids.find(id= > id === item.id))
      res.writeHead(200, { 'Content-Type': 'application/json' })
      res.end(JSON.stringify({
        code: 200.data: bookList,
        message: 'Deleted successfully'}}})))else if (pathname === '/api/update') {
    let body = ' '
    req.on('data'.(chunk) = > {
      body += chunk
    })
    req.on('end'.() = > {
      body = JSON.parse(body)
      let { bookListNew } = body
      bookList = bookListNew
      res.writeHead(200, { 'Content-Type': 'application/json' })
      res.end(JSON.stringify({
        code: 200.data: bookList,
        message: 'Update successful'}}})))else {   / / 404
    res.writeHead(404, { 'Content-Type': 'text/html' })
    res.end('404')
  }
})

server.listen(9999.() = > {
  console.log(9999)})Copy the code

8. Node native write interface, build static Web server, process front-end history routing

Reference links:

www.npmjs.com/package/con…

www.npmjs.com/package/con…

Project online:

http://39.97.238.175/index/home

const http = require('http')
const url = require('url')
const path = require('path')
const fs = require('fs')
const connect = require('connect')
const history = require('connect-history-api-fallback')
const { bookNavData, bookMallData, userList } = require('./data')

let bookList = []

// Enable native HTTP modules to use middleware functionality
const app = connect()

// React route (BrowserRoute), vUE route (mode:history)
app.use(history())

// Cross-domain, static Web server
app.use((req, res, next) = > {
  / / across domains
  res.setHeader('Access-Control-Allow-Origin'.The '*')  // You can change * to http://localhost:3000 to avoid XSS attacks
  / / res. SetHeader (' Access - Control - Allow - the Methods', 'the GET, PUT, POST, PATCH, DELETE, HEAD, OPTIONS') / / release method
  res.setHeader('Access-Control-Allow-Headers'.'content-type')  // The request header for release
  res.setHeader('Access-Control-Max-Age'.1800)  // Precheck requests are initiated every 30 minutes, 1800 seconds

  let { pathname } = url.parse(req.url, true)
  let extName = path.extname(pathname)
  console.log(pathname, extName)
  if (pathname === '/') {
    pathname = '/index.html'
  }
  if  (pathname.indexOf('/api') > =0) {
    next()
  } else {
    fs.readFile(`./public/${pathname}`.(err, data) = > {
      if (err) {
        res.writeHead(404, {'Content-Type': 'text/html' })
        res.end('404')}else {
        if (extName === '.css') {
          res.writeHead(200, {'Content-Type': 'text/css'})
        }
        res.end(data)
      }
    })
  }
})

/ / interface
app.use((req, res) = > {
  let { pathname } = url.parse(req.url, true)

  if (req.method == 'OPTIONS') { // Cross-domain, processing options requests
    res.writeHead(204) No content / / 204
    res.end()
  } else if (req.method === 'POST' && pathname === '/api/login') { / / login
    let body = ' '

    // Every time the request body is received, it is added to the body variable via req's data event listener
    req.on('data'.(chunk) = > {
      body += chunk
    })

    Parse parse the body into the actual POST request format after the end event is triggered
    req.on('end'.() = >{
      body = JSON.parse(body)
      let { username, password } = body
      let user = userList.find(item= > item.username === username)
      res.writeHead(200, { 'Content-Type': 'application/json' })
      if (user) {
        if (user.password === password) {
          res.write(JSON.stringify({
            code: 200.data: {
              username
            },
            message: 'Login successful'}}))else {
          res.write(JSON.stringify({
            code: 400.message: 'Password error'}}}))else {
        res.write(JSON.stringify({
          code: 400.data: body,
          message: 'User does not exist'
        }))
      }
      res.end()
    })
  } else if (pathname === '/api/nav') {  / / navigation
    res.writeHead(200, { 'Content-Type': 'application/json' })
    res.end(JSON.stringify({
      code: 200.data: bookNavData,
      message: 'navigation'}}))else if (pathname === '/api/list') {  / / list
    let { id } = url.parse(req.url, true).query
    let list = bookMallData.find(item= > item.id == id).list
    list.forEach(item= > {
      if (bookList.findIndex(book= > book.id === item.id) >= 0) {
        item.is_in_my_book = true
      } else {
        item.is_in_my_book = false
      }
    })
    res.writeHead(200, { 'Content-Type': 'application/json' })
    res.end(JSON.stringify({
      code: 200.data: list,
      message: 'list'}}))else if (pathname === '/api/get_book_list') { / / bag
    res.writeHead(200, { 'Content-Type': 'application/json' })
    res.end(JSON.stringify({
      code: 200.data: bookList,
      message: 'bag'}}))else if (pathname === '/api/add') {  // Add to the bag
    let body = ' '
    req.on('data'.(chunk) = > {
      body += chunk
    })

    req.on('end'.() = > {
      body = JSON.parse(body)
      let { item } = body
      bookList.push(item)
      res.writeHead(200, { 'Content-Type': 'application/json' })
      res.end(JSON.stringify({
        code: 200.data: bookList,
        message: 'Added successfully'}}})))else if (pathname === '/api/detail') {  / / details
    let { id } = url.parse(req.url, true).query
    let detail
    bookMallData.forEach(listItem= > {
      listItem.list.forEach(book= > {
        if (book.id == id) {
          detail = book
        }
      })
    })

    if (bookList.find(book= > book.id === detail.id)) {
      detail.is_in_my_book = true
    } else {
      detail.is_in_my_book = false
    }
    res.writeHead(200, { 'Content-Type': 'application/json' })
    res.end(JSON.stringify({
      code: 200.data: detail,
      message: 'details'}}))else if (pathname === '/api/delete') {  / / delete
    let body = ' '
    req.on('data'.(chunk) = > {
      body +=chunk
      console.log('chunk:', chunk)
    })
    req.on('end'.() = > {
      body = JSON.parse(body)
      let { ids } = body
      bookList = bookList.filter(item= >! ids.find(id= > id === item.id))
      res.writeHead(200, { 'Content-Type': 'application/json' })
      res.end(JSON.stringify({
        code: 200.data: bookList,
        message: 'Deleted successfully'}}})))else if (pathname === '/api/update') {  / / update
    let body = ' '
    req.on('data'.(chunk) = > {
      body += chunk
    })
    req.on('end'.() = > {
      body = JSON.parse(body)
      let { bookListNew } = body
      bookList = bookListNew
      res.writeHead(200, { 'Content-Type': 'application/json' })
      res.end(JSON.stringify({
        code: 200.data: bookList,
        message: 'Update successful'}}})))else {   / / 404
    res.writeHead(404, { 'Content-Type': 'text/html' })
    res.end('404')}})const server = http.createServer(app)

server.listen(9998)
console.log(9998)
Copy the code

9. Install FileZilla server

Download the Filezilla client and server:

filezilla-project.org/

Installing the Server:

 

10. Install FileZilla client

11. Aliyun configuration supports FTP

Twelve, colors,

Packing:

yarn add colors
Copy the code

The node code:

const color = require('colors')

console.log('hello world! '.green)
console.log('hello world! '.underline.red)
console.log('hello world! '.inverse)
console.log('hello world! '.rainbow)
Copy the code

Effect:

Express Scaffolding

Packing:

yarn global add express-generator
Copy the code

Run:

express --view=pug m-express-demo

cd m-express-demo

yarn

yarn start
Copy the code

NPM View command

Display information about NPM package:

npm view axios

npm show axios

npm info axios

npm v axios
Copy the code

Query all version numbers of NPM packages:

npm view axios versions
Copy the code

Query all version numbers and dependencies of NPM package:

npm view axios versions dependencies
Copy the code

14, String

    let a = 'hello'
    let b = 'hello'
    let c = new String('hello')

    console.log(a === b)  //true
    console.log(a === c)  //false
    console.log(typeof a) //string
    console.log(typeof c) //object
    console.log(a instanceof String) //false
    console.log(c instanceof String) //true
Copy the code

Node is single-threaded

    let start = Date.now()
    console.log(start)
    setTimeout(() = > {
      console.log(Date.now() - start)  / / around 1000
      for (let i = 0; i < 5000000000; i++) {
        
      }
    }, 1000)
    setTimeout(() = > {
      console.log(Date.now() - start)  // > 2000, depending on the number of for sequences above
    }, 2000)
Copy the code

 

Error handling

Error stack:

test.js:

const a = () = > {
  console.log(obj.name)
}

const b = () = > {
  a()
}

b()
Copy the code

In asynchronous functions, stack information is lost:

const a = () = > {
  setTimeout(() = > {
    console.log(obj.name)
  }, 10)}const b = () = > {
  a()
}

b()
Copy the code

UncaughtException catches an exception (loses context where the error occurred) :

process.on('uncaughtException'.(error) = > {
  console.error("xu:", error)
})

const a = () = > {
  console.log(obj.name)
}

const b = () = > {
  a()
}

b()
Copy the code

Domain module:

When res is the context, error messages can be returned to the front end!

Refer to the link: www.runoob.com/nodejs/node…

const domain = require('domain')

const d = domain.create()

let name = 'tom'


d.on('error'.(error) = > {
  console.log('Context:', name)
  console.log('Exception message caught by domain:', error.stack)
})

d.run(() = > {
  console.log(obj.name)
})
Copy the code

17,process.nextTick(callback)

The next loop of the event loop calls the callback function.

console.log(1)

process.nextTick(() = > {
  console.log(2)})console.log(3)
Copy the code

Print the animal according to the subscript

const program = require('commander')
const fs = require('fs')
const packageInfo = require('./package.json')

program.version(packageInfo.version)
  .option('-i, --index <type>'."The subscript")

program.parse(process.argv)

console.log(program.index)

fs.readFile('./animals.txt'.'utf-8'.(err, data) = > {
  if (err) {
    return
  }
  let animalsArr = data.split('===============++++SEPERATOR++++====================')
  console.log(animalsArr[program.index])
})
Copy the code

Animal data:

Link: pan.baidu.com/s/1C3LKzQtd… Extraction code: G1SV

Node reads file directories from web pages

const program = require('commander')
const fs = require('fs')
const http = require('http')
const { exec } = require('child_process')
const path = require('path')
const packageInfo = require('./package.json')

program.version(packageInfo.version)
  .option('-p, --port <port>'."set port")

program.parse(process.argv)

let PORT = program.port || 8000

const app = http.createServer((req, res) = > {
  let rootPath = process.cwd()
  if (req.url === '/favicon.ico') {
    res.end()
    return
  }
  let myPath = path.join(rootPath, req.url)
  console.log('a', myPath)
  if (fs.statSync(myPath).isFile()) {
    fs.readFile(myPath, 'utf8'.(err, data) = > {
      res.end(data)
    })
  } else {
    let list = fs.readdirSync(myPath).map(filePath= > {
      return `<div>
      <a href="${path.join(req.url, filePath)}">${filePath}</a>
      </div>`
    }).join(' ')
    let html = fs.readFileSync(__dirname + '/public/index.html'.'utf8')
    html = html.replace("{{list}}", list)
    res.end(html)
  }
})

app.listen(PORT, () = > {
  //exec(`start http://localhost:${PORT}`)
})
Copy the code

Rename files or folders

const fs = require('fs')
const path = require('path')

let target = process.argv[2]
let rename = process.argv[3]
let rootPath = process.cwd()

target = path.join(rootPath, target)
if (fs.existsSync(target)) {
  fs.renameSync(target, path.join(rootPath, rename))
} else {
  console.log('File or folder does not exist')}Copy the code

Js distinguishes between object functions and arrays

const fs = require('fs')
const path = require('path')

let obj = {}

console.log(obj instanceof Object)  //true
console.log(typeof obj)  //object
console.log(Object.prototype.toString.call(obj))  //[object Object]

let fun = () = > {}

console.log(fun instanceof Function)  //true
console.log(fun instanceof Object)  //true
console.log(typeof fun)   //function
console.log(Object.prototype.toString.call(fun))  //[object Function]

let arr = []

console.log(arr instanceof Array)  //true
console.log(arr instanceof Object)  //true
console.log(typeof arr)   //object

console.log(Object.prototype.toString.call(arr))  //[object Array]
Copy the code

Event triggers

const EventEmitter = require('events')
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter()

myEmitter.on('myEventName'.(a, b) = > {
  console.log(a, b)
})

myEmitter.emit('myEventName'.1.2)
myEmitter.emit('myEventName'.1.2)

myEmitter.once('myOnce'.() = > {
  console.log('Trigger only once')
})

myEmitter.emit('myOnce')
myEmitter.emit('myOnce')

myEmitter.on('error'.(err) = > {
  console.error(err)
})

myEmitter.emit('error'.new Error('wrong'))
Copy the code

Manual encapsulation events

class MyEmitter {
  constructor() {
    this.events = {}
  }
  on(eventName, callback) {
    if (this.events[eventName]) {
      this.events[eventName].push(callback)
    } else {
      this.events[eventName] = [callback]
    }
  }

  emit(eventName, ... arg) {
    let callbackArr = this.events[eventName]
    callbackArr && callbackArr.forEach(item= > {
      if (Object.prototype.toString.call(item) === '[object Function]') { item(... arg) }else if (Object.prototype.toString.call(item) === '[object Object]') {
        if(item.once) { item.callback(... arg) item.callback =() = >{}}}})}once(eventName, callback) {
    if (this.events[eventName]) {
      this.events[eventName].push({
        once: true,
        callback
      })
    } else {
      this.events[eventName] = [{
        once: true,
        callback
      }]
    }
  }
}
const myEmitter = new MyEmitter()

module.exports = myEmitter
Copy the code

Parent-child process communication

app.js:

const child_process = require('child_process')

const child = child_process.fork('./compute.js')

child.send({ type: 'start' })
child.on('message'.(action) = > {
  if (action.type === 'sum') {
    console.log('Result calculated by the child process :', action.sum)
    process.exit()
    
  }
})

process.on('exit'.() = > {
  console.log('Main process terminated')})console.log('Run here')
Copy the code

compute.js:


const computeSum = () = > {
  let sum = 0
  for (let i = 0; i < 1000000; i++) {
    sum += i
  }
  return sum
}

process.on('message'.(action) = > {
  if (action.type === 'start') {
    let sum = computeSum()
    process.send({
      type: 'sum',
      sum
    })
  }
})
Copy the code

Docker

Docker: You’re a docker

Doctor: doctor

Docker Toolbox download link: github.com/docker/tool…

Docker toolbox download address: domestic mirrors.aliyun.com/docker-tool…

Docker website: www.docker.com/

Docker Hub website: hub.docker.com/

Docker novice tutorial: www.runoob.com/docker/dock…

Installation:

 

 

 

 

Download the latest version of boot2docker.iso and put it in the local cache folder, otherwise the latest version will be downloaded online during startup, and it will be difficult to download down, and an error will be reported

You can go to Baidu cloud disk to download:

Links:Pan.baidu.com/s/1Y9bLSSvy…

Extraction code: ESP0

hello world:

docker run ubuntu:15.10 /bin/echo "hello world"
Copy the code

 

Run interactive containers:

docker run -i -t ubuntu:15.10 /bin/bash
Copy the code

CTRL + D or Exit

 

docker run -d ubuntu:15.10 /bin/sh -c "while true; do echo hello; sleep 5; done"

docker ps

docker logs determined_meitner
Copy the code

Enter the container:

docker attach determined_meitner
Copy the code

26. Koa

Framework of koa:

Koa – the router: routing

Koa – bodyparser: parse the post

Koa2 – cors: cross domain

Koa-static: indicates static resources

Koa – logger: log

@koa/multer Multer: Upload files

 

koa:

const Koa = require('koa')
const app = new Koa()
const { bookNavData } = require('./data')

app.use(ctx= > {
  ctx.body = {
    code: 200.data: bookNavData,
    message: 'navigation'
  }
})

app.listen(84)
console.log(84)
Copy the code

koa-router:

const Koa = require('koa')
const Router = require('koa-router')
const app = new Koa()
const router = new Router()
const { bookNavData } = require('./data')

router.get('/api/nav'.ctx= > {
  ctx.body = {
    code: 200.data: bookNavData,
    message: 'navigation'
  }
})

app.use(router.routes())

app.listen(84)
console.log(84)
Copy the code

koa-bodyparser:

const Koa = require('koa')
const Router = require('koa-router')
const bodyParser = require('koa-bodyparser')
const app = new Koa()
const router = new Router()
const { bookNavData } = require('./data')

// List of users
const userList = [{
  id: '001'.username: 'admin'.password: '123456'
}, {
  id: '002'.username: 'xu'.password: '123'
}, {
  id: '003'.username: 'a'.password: '123456'
}]

/ / login
router.post('/api/login'.ctx= > {
  let { username, password } = ctx.request.body
  let user = userList.find(item= > item.username === username)
  if (user) {
    if (user.password === password) {
      ctx.body = {
        code: 200.data: {
          username
        },
        message: 'Login successful'}}else {
      ctx.body = {
        code: 400.message: 'Password error'}}}else {
    ctx.body = {
      code: 400.message: 'User does not exist'}}})/ / navigation
router.get('/api/nav'.ctx= > {
  ctx.body = {
    code: 200.data: bookNavData,
    message: 'navigation'
  }
})

app.use(bodyParser())
app.use(router.routes())

app.listen(84)
console.log(84)
Copy the code

koa-compose:

const Koa = require('koa')
const Router = require('koa-router')
const bodyParser = require('koa-bodyparser')
const cors = require('koa2-cors')
const static = require('koa-static')
const logger = require('koa-logger')
const compose = require('koa-compose')
const app = new Koa()
const router = new Router()
const { bookNavData } = require('./data')

// List of users
const userList = [{
  id: '001'.username: 'admin'.password: '123456'
}, {
  id: '002'.username: 'xu'.password: '123'
}, {
  id: '003'.username: 'a'.password: '123456'
}]

/ / login
router.post('/api/login'.ctx= > {
  let { username, password } = ctx.request.body
  let user = userList.find(item= > item.username === username)
  if (user) {
    if (user.password === password) {
      ctx.body = {
        code: 200.data: {
          username
        },
        message: 'Login successful'}}else {
      ctx.body = {
        code: 400.message: 'Password error'}}}else {
    ctx.body = {
      code: 400.message: 'User does not exist'}}})/ / navigation
router.get('/api/nav'.ctx= > {
  ctx.body = {
    code: 200.data: bookNavData,
    message: 'navigation'}})/ / / / cross domain
// app.use(cors())
/ / / / log
// app.use(logger())
// // Parses post requests
// app.use(bodyParser())
// // Static Resources
// app.use(static(__dirname + '/public'))
/ / / / routing
// app.use(router.routes())

const middlewares = compose([cors(), logger(), bodyParser(), static(__dirname + '/public'), router.routes()])
app.use(middlewares)


app.listen(84)
console.log(84)
Copy the code

Github.com/koajs/compo…

koa-router:

const Router = require('koa-router')

const router = new Router()

/ / navigation
router.get('/api/nav'.(ctx, next) = > {
  ctx.body = {
    code: 200.data: bookNavData,
    message: 'navigation'}})/ / login
router.post('/api/login'.async (ctx, next) => {
  let { username, password } = ctx.request.body
    
  ctx.body = {
    code: 200.data: {
      username
    },
    message: 'Login successful'}})/ / routing
app.use(router.routes())
Copy the code

 

www.npmjs.com/package/koa…

koa-static:

const static = require('koa-static')

// Static resources
//app.use(static('public'))
app.use(static(__dirname + '/public'))
Copy the code

@koa/multer multer(upload a single file):

const Koa = require('koa')
const Router = require('koa-router')
const bodyParser = require('koa-bodyparser')
const cors = require('koa2-cors')
const static = require('koa-static')
const logger = require('koa-logger')
const compose = require('koa-compose')
const multer = require('@koa/multer')
const app = new Koa()
const router = new Router()
const { bookNavData } = require('./data')

// List of users
const userList = [{
  id: '001'.username: 'admin'.password: '123456'
}, {
  id: '002'.username: 'xu'.password: '123'
}, {
  id: '003'.username: 'a'.password: '123456'
}]

const storage = multer.diskStorage({
  destination: (req, file, cb) = > {
    cb(null, __dirname + '/upload')},filename: (req, file, cb) = > {
    cb(null.`The ${Date.now()} - ${file.originalname}`)}})const upload = multer({ storage })

/ / login
router.post('/api/login'.ctx= > {
  let { username, password } = ctx.request.body
  let user = userList.find(item= > item.username === username)
  if (user) {
    if (user.password === password) {
      ctx.body = {
        code: 200.data: {
          username
        },
        message: 'Login successful'}}else {
      ctx.body = {
        code: 400.message: 'Password error'}}}else {
    ctx.body = {
      code: 400.message: 'User does not exist'}}})/ / navigation
router.get('/api/nav'.ctx= > {
  ctx.body = {
    code: 200.data: bookNavData,
    message: 'navigation'}})// Upload the file
router.post('/api/upload', upload.single('img'), ctx= > {
  ctx.body = {
    code: 200.data: ctx.request.file,
    message: 'Upload successful'}})/ / / / cross domain
// app.use(cors())
/ / / / log
// app.use(logger())
// // Parses post requests
// app.use(bodyParser())
// // Static Resources
// app.use(static(__dirname + '/public'))
/ / / / routing
// app.use(router.routes())

const middlewares = compose([cors(), logger(), bodyParser(), static(__dirname + '/public'), router.routes()])
app.use(middlewares)


app.listen(84)
console.log(84)
Copy the code

@koa/multer multer(upload multiple files):

const Koa = require('koa')
const Router = require('koa-router')
const bodyParser = require('koa-bodyparser')
const cors = require('koa2-cors')
const static = require('koa-static')
const logger = require('koa-logger')
const compose = require('koa-compose')
const multer = require('@koa/multer')
const app = new Koa()
const router = new Router()
const { bookNavData } = require('./data')

// List of users
const userList = [{
  id: '001'.username: 'admin'.password: '123456'
}, {
  id: '002'.username: 'xu'.password: '123'
}, {
  id: '003'.username: 'a'.password: '123456'
}]

const storage = multer.diskStorage({
  destination: (req, file, cb) = > {
    cb(null, __dirname + '/upload')},filename: (req, file, cb) = > {
    cb(null.`The ${Date.now()} - ${file.originalname}`)}})const upload = multer({ storage })

/ / login
router.post('/api/login'.ctx= > {
  let { username, password } = ctx.request.body
  let user = userList.find(item= > item.username === username)
  if (user) {
    if (user.password === password) {
      ctx.body = {
        code: 200.data: {
          username
        },
        message: 'Login successful'}}else {
      ctx.body = {
        code: 400.message: 'Password error'}}}else {
    ctx.body = {
      code: 400.message: 'User does not exist'}}})/ / navigation
router.get('/api/nav'.ctx= > {
  ctx.body = {
    code: 200.data: bookNavData,
    message: 'navigation'}})// Upload the file
router.post('/api/upload', upload.array('img'.9), ctx= > {
  ctx.body = {
    code: 200.data: ctx.request.files,
    message: 'Upload successful'}})/ / / / cross domain
// app.use(cors())
/ / / / log
// app.use(logger())
// // Parses post requests
// app.use(bodyParser())
// // Static Resources
// app.use(static(__dirname + '/public'))
/ / / / routing
// app.use(router.routes())

const middlewares = compose([cors(), logger(), bodyParser(), static(__dirname + '/public'), router.routes()])
app.use(middlewares)


app.listen(84)
console.log(84)
Copy the code

How to interrupt node debugging

Inspect inspections; To view; Look at; inspect

Instruction interpretation:

// Activate the inspector on host:port
--inspect[=[host:]port]   



// Activate the inspector on host:port with the break point in the first line by default
--inspect-brk[=[host:]port]  
Copy the code

 

Reference links:

Nodejs. Cn/API/cli. HTM…

// Start with node
node --inspect-brk app

// Start using nodemon
nodemon --inspect-brk app

// The first line is not broken by default
nodemon --inspect app
Copy the code

— Nolazy has no official documentation, please refer to this link:

Stackoverflow.com/questions/2…

 

In the Chrome address bar, enter:

chrome://inspect/#devices
Copy the code

Break points:

Look at the log:

Mysql > select * from ‘char’ where varchar = ‘varchar

Varchar (100) 100 represents one hundred characters

Char is fixed length, whereas VARCHAR uses storage space depending on the specific length

 

Reference link: blog.csdn.net/qq_21959403…

Mysql > select * from ‘mysql’

U

Select database
USE demo;
USE test2;

Drop database
DROP TABLE `admin`;

- the administrator
CREATE TABLE `admin` (
	`uid` INT UNSIGNED AUTO_INCREMENT,
	`username` VARCHAR(20) NOT NULL,
	`password` VARCHAR(30) NOT NULL,
	`create_time` DATETIME NOT NULL.PRIMARY KEY (`uid`)
);

- the teacher
DROP TABLE `teacher`;
CREATE TABLE `teacher` (
	`uid` INT UNSIGNED AUTO_INCREMENT PRIMARY KEY COMMENT 'Teacher ID',
	`username` VARCHAR(20) NOT NULL COMMENT 'Teacher's login user name',
	`password` VARCHAR(30) NOT NULL COMMENT 'Teacher's login password',
	`age` INT UNSIGNED COMMENT 'Age of teacher',
	`gender` enum('male'.'woman'.'secret') DEFAULT 'secret' COMMENT 'Sex of teacher',
	`email` VARCHAR(50) COMMENT 'email',
	`create_time` DATETIME NOT NULL COMMENT 'When teachers join the platform'
);

-- Displays information for each column of the table, including comments
SHOW FULL COLUMNS FROM teacher;

Check -
SELECT * FROM `admin`;
SELECT username FROM admin;
SELECT `password`, `username` FROM admin WHERE uid = 1;

-- LIKE can do fuzzy search AND AND OR OR
SELECT * FROM admin WHERE username LIKE '%admi%';
SELECT * FROM admin WHERE username LIKE '%a%' AND `password` = '123';
SELECT * FROM admin WHERE username LIKE '%a%' OR `password` = '123';

-- Query for two-digit user names starting with x
SELECT * FROM admin WHERE username LIKE 'x_';

Select * from user whose name does not contain a
SELECT * FROM admin WHERE username NOT LIKE '%a%';

-- The username contains either x or u or a or L
SELECT * FROM admin WHERE username RLIKE '[xual]';

REGEXP is the same as RLIKE
SELECT * FROM admin WHERE username REGEXP '[xa]';

- contains a
SELECT * FROM admin WHERE username RLIKE '[a]+';
SELECT * FROM admin WHERE username RLIKE 'a+';

- a beginning
SELECT * FROM admin WHERE username RLIKE '^[a]+';

-- begins with an X or a
SELECT * FROM admin WHERE username RLIKE '^[xa]+';

-- Queries two-digit user names starting with x, with "." matching a single character
SELECT * FROM admin WHERE username RLIKE 'x.';

SELECT username, `password`
FROM admin



-- Ascending by default, ascending: ASC ascend, descending: desc descend
SELECT * FROM admin ORDER BY username;
SELECT * FROM admin ORDER BY username ASC;
SELECT * FROM admin ORDER BY username DESC;

Sort by creation time, then by user name
SELECT * FROM admin ORDER BY create_time DESC, username ASC;

B: Just the first two
SELECT * 
FROM admin 
LIMIT 2;

The first number of pages is the starting point, starting from zero, and the second number is the number of pages per page
SELECT * FROM admin LIMIT 0.4;
SELECT * FROM admin LIMIT 4.1;

Same as LIMIT 4, 1
SELECT * FROM admin LIMIT 1 OFFSET 4;


-- Paging after sort
SELECT * FROM admin ORDER BY username ASC LIMIT 1.2;

-
SELECT COUNT(*) FROM admin;

-- Fully qualified table names
SELECT admin.username FROM admin;

- to add
INSERT INTO `admin` (`username`, `password`, `create_time`) VALUES ('admin'.'123456'.'the 2019-02-20 10:36:06');

-- Increase, automatically obtain the system time
INSERT INTO `admin` (`username`, `password`, `create_time`) VALUES ('xu'.'123', NOW());
INSERT INTO `admin` (`username`, `password`, `create_time`) VALUES ('zhangsan'.'123', NOW());
INSERT INTO `admin` (`username`, `password`, `create_time`) VALUES ('lisi'.'123', NOW());
INSERT INTO `admin` (`username`, `password`, `create_time`) VALUES ('wangwu'.'123', NOW());

-- Zhang Sanan, teacher No. 1
INSERT INTO `teacher` 
	(`username`, `password`, `age`, `gender`, `email`, `create_time`) 
	VALUES ('zhangsan'.'zhangsan'.30.'male'.'[email protected]', NOW());

-- No. 2 teacher Li Sinu
INSERT INTO `teacher` 
	(`username`, `password`, `age`, `gender`, `email`, `create_time`) 
	VALUES ('lisi'.'lisi123'.31.'woman'.'[email protected]', NOW());

-- No. 3 teacher Wang Wu gender confidentiality
INSERT INTO `teacher` 
	(`username`, `password`, `age`, `email`, `create_time`) 
	VALUES ('wangwu'.'wangwu123'.32.'[email protected]', NOW());

-- Teacher No. 4 Xu is both a teacher and an administrator
INSERT INTO `teacher`
	(`username`, `password`, `age`, `email`, `create_time`) 
	VALUES ('xu'.'xu'.30.'[email protected]', NOW());

INSERT INTO `teacher`
	(`username`, `password`, `age`, `email`, `create_time`)
	VALUES ('lilei'.'lilei'.36.'[email protected]', NOW());

SELECT * FROM teacher;
SELECT * FROM teacher WHERE age > 30;
SELECT * FROM teacher WHERE age > = 30;
SELECT * FROM teacher WHERE age ! = 30;
SELECT * FROM teacher WHERE age < 31;
SELECT * FROM teacher WHERE age < = 31;

Query two tables
SELECT * FROM admin, teacher;

SQL > alter table associative query
SELECT * FROM admin, teacher WHERE admin.username = teacher.username; 

Associative query, duplicate names with individual names
SELECT admin.username as 'Username in admin table', teacher.username as 'Username in teacher table'
	FROM admin, teacher WHERE admin.username = teacher.username;

Mysql > alter table 'username'
SELECT username FROM admin, teacher WHERE admin.username = teacher.username;

Another name -
SELECT username as `name` FROM admin;

-- When two tables have the same field
SELECT admin.username FROM admin, teacher;

SELECT admin.username as admin_username FROM admin, teacher;

-- does not equal sum! = as
SELECT * FROM teacher WHERE age <> 30;

- to heavy
SELECT DISTINCT age from teacher;

-- Merge the results of the two queries and de-duplicate them
SELECT username FROM admin
	UNION
	SELECT username FROM teacher;

Merge the results of the two queries and display them all
SELECT username FROM admin
	UNION ALL
	SELECT username FROM teacher;

- the sum
SELECT SUM(age) FROM teacher;

-- Find the average value
SELECT AVG(age) FROM teacher;

The number, o
SELECT COUNT(age) FROM teacher;

-- Group by age and count the number of groups
SELECT age, COUNT(age) FROM teacher GROUP BY age;

-- Sum by age group
SELECT age, SUM(age) FROM teacher GROUP BY age;

-- WITH ROLLUP
SELECT age, COUNT(age) FROM teacher GROUP BY age WITH ROLLUP;

-- Use COALESCE to convert null fields into "aggregates"
SELECT COALESCE(age, 'summary'), COUNT(age) FROM teacher GROUP BY age WITH ROLLUP;


-- Delete a teacher
DELETE FROM teacher WHERE uid = 1;

-- Delete an administrator
DELETE FROM `admin` WHERE uid = 2;

Change -
UPDATE admin SET `password` = '123456' WHERE uid = 2;
SELECT * FROM admin;

UPDATE admin SET username = 'xu123', `password` = '12' WHERE uid = 2;

- delete
DELETE FROM admin WHERE uid = 2;
Copy the code

Create the SQL:

Drop database
DROP TABLE IF EXISTS `admin`;

- the administrator
CREATE TABLE IF NOT EXISTS `admin` (
	`uid` INT UNSIGNED AUTO_INCREMENT,
	`username` VARCHAR(20) NOT NULL,
	`password` VARCHAR(30) NOT NULL,
	`create_time` DATETIME NOT NULL.PRIMARY KEY (`uid`)
);

- the teacher
DROP TABLE IF EXISTS `teacher`;
CREATE TABLE IF NOT EXISTS `teacher` (
	`uid` INT UNSIGNED AUTO_INCREMENT PRIMARY KEY COMMENT 'Teacher ID',
	`username` VARCHAR(20) NOT NULL COMMENT 'Teacher's login user name',
	`password` VARCHAR(30) NOT NULL COMMENT 'Teacher's login password',
	`age` INT UNSIGNED COMMENT 'Age of teacher',
	`gender` enum('male'.'woman'.'secret') DEFAULT 'secret' COMMENT 'Sex of teacher',
	`email` VARCHAR(50) COMMENT 'email',
	`create_time` DATETIME NOT NULL COMMENT 'When teachers join the platform'
);
Copy the code

insert.sql:

- to add
INSERT INTO `admin` (`username`, `password`, `create_time`) VALUES ('admin'.'123456'.'the 2019-02-20 10:36:06');

-- Increase, automatically obtain the system time
INSERT INTO `admin` (`username`, `password`, `create_time`) VALUES ('xu'.'123', NOW());
INSERT INTO `admin` (`username`, `password`, `create_time`) VALUES ('zhangsan'.'123', NOW());
INSERT INTO `admin` (`username`, `password`, `create_time`) VALUES ('lisi'.'123', NOW());
INSERT INTO `admin` (`username`, `password`, `create_time`) VALUES ('wangwu'.'123', NOW());
INSERT INTO `admin` (`username`, `password`, `create_time`) VALUES ('Abc'.'123', NOW());
INSERT INTO `admin` (`username`, `password`, `create_time`) VALUES ('bcd'.'123', NOW());
INSERT INTO `admin` (`username`, `password`, `create_time`) VALUES ('Bcd'.'123', NOW());


-- Zhang Sanan, teacher No. 1
INSERT INTO `teacher` 
	(`username`, `password`, `age`, `gender`, `email`, `create_time`) 
	VALUES ('zhangsan'.'zhangsan'.30.'male'.'[email protected]', NOW());

-- No. 2 teacher Li Sinu
INSERT INTO `teacher` 
	(`username`, `password`, `age`, `gender`, `email`, `create_time`) 
	VALUES ('lisi'.'lisi123'.31.'woman'.'[email protected]', NOW());

-- No. 3 teacher Wang Wu gender confidentiality
INSERT INTO `teacher` 
	(`username`, `password`, `age`, `email`, `create_time`) 
	VALUES ('wangwu'.'wangwu123'.32.'[email protected]', NOW());

-- Teacher No. 4 Xu is both a teacher and an administrator
INSERT INTO `teacher`
	(`username`, `password`, `age`, `email`, `create_time`) 
	VALUES ('xu'.'xu'.30.'[email protected]', NOW());

INSERT INTO `teacher`
	(`username`, `password`, `age`, `email`, `create_time`)
	VALUES ('lilei'.'lilei'.36.'[email protected]', NOW());

INSERT INTO `teacher`
	(`username`, `password`, `age`, `email`, `create_time`)
	VALUES ('Abc'.'Abc'.36.'[email protected]', NOW());
Copy the code

 select.sql:

Check -
SELECT * FROM `admin`;
SELECT * FROM teacher;

SELECT username FROM admin;
SELECT `password`, `username` FROM admin WHERE uid = 1;

-- LIKE can do fuzzy search AND AND OR OR
SELECT * FROM admin WHERE username LIKE '%admi%';
SELECT * FROM admin WHERE username LIKE '%a%' AND `password` = '123';
SELECT * FROM admin WHERE username LIKE '%a%' OR `password` = '123';

-- Query for two-digit user names starting with x
SELECT * FROM admin WHERE username LIKE 'x_';

Select * from user whose name does not contain a
SELECT * FROM admin WHERE username NOT LIKE '%a%';

-- The username contains either x or u or a or L
SELECT * FROM admin WHERE username RLIKE '[xual]';

REGEXP is the same as RLIKE
SELECT * FROM admin WHERE username REGEXP '[xa]';

- contains a
SELECT * FROM admin WHERE username RLIKE '[a]+';
SELECT * FROM admin WHERE username RLIKE 'a+';

- a beginning
SELECT * FROM admin WHERE username RLIKE '^[a]+';

-- begins with an X or a
SELECT * FROM admin WHERE username RLIKE '^[xa]+';

-- Queries two-digit user names starting with x, with "." matching a single character
SELECT * FROM admin WHERE username RLIKE 'x.';

SELECT username, `password`
FROM admin

-- Queries only user names starting with A, and is case sensitive
SELECT * FROM admin WHERE username LIKE BINARY('A%');
SELECT * FROM admin WHERE BINARY username LIKE 'a%';

- case-sensitive sort at https://www.jianshu.com/p/f8707b8461d3
SELECT * FROM admin ORDER BY username collate utf8mb4_bin;
SELECT * FROM admin ORDER BY username COLLATE utf8mb4_bin DESC;

-- Ascending by default, ascending: ASC ascend, descending: desc descend
SELECT * FROM admin ORDER BY username;
SELECT * FROM admin ORDER BY username ASC;
SELECT * FROM admin ORDER BY username DESC;

Sort by creation time, then by user name
SELECT * FROM admin ORDER BY create_time DESC, username ASC;

B: Just the first two
SELECT * 
FROM admin 
LIMIT 2;

The first number of pages is the starting point, starting from zero, and the second number is the number of pages per page
SELECT * FROM admin LIMIT 0.4;
SELECT * FROM admin LIMIT 4.1;

Same as LIMIT 4, 1
SELECT * FROM admin LIMIT 1 OFFSET 4;


-- Paging after sort
SELECT * FROM admin ORDER BY username ASC LIMIT 1.2;

-
SELECT COUNT(*) FROM admin;

-- Fully qualified table names
SELECT admin.username FROM admin;


SELECT * FROM teacher;
SELECT * FROM teacher WHERE age > 30;
SELECT * FROM teacher WHERE age > = 30;
SELECT * FROM teacher WHERE age ! = 30;
SELECT * FROM teacher WHERE age < 31;
SELECT * FROM teacher WHERE age < = 31;

Query two tables
SELECT * FROM admin, teacher;

SQL > alter table associative query
SELECT * FROM admin, teacher WHERE admin.username = teacher.username; 

Associative query, duplicate names with individual names
SELECT admin.username as 'Username in admin table', teacher.username as 'Username in teacher table'
	FROM admin, teacher WHERE admin.username = teacher.username;

Mysql > alter table 'username'
SELECT username FROM admin, teacher WHERE admin.username = teacher.username;

Another name -
SELECT username as `name` FROM admin;

-- When two tables have the same field
SELECT admin.username FROM admin, teacher;

SELECT admin.username as admin_username FROM admin, teacher;

-- does not equal sum! = as
SELECT * FROM teacher WHERE age <> 30;

- to heavy
SELECT DISTINCT age from teacher;

-- Merge the results of the two queries and de-duplicate them
SELECT username FROM admin
	UNION
	SELECT username FROM teacher;

Merge the results of the two queries and display them all
SELECT username FROM admin
	UNION ALL
	SELECT username FROM teacher;

- the sum
SELECT SUM(age) FROM teacher;

-- Find the average value
SELECT AVG(age) FROM teacher;

The number, o
SELECT COUNT(age) FROM teacher;

-- Group by age and count the number of groups
SELECT age, COUNT(age) FROM teacher GROUP BY age;

-- Sum by age group
SELECT age, SUM(age) FROM teacher GROUP BY age;

-- WITH ROLLUP
SELECT age, COUNT(age) FROM teacher GROUP BY age WITH ROLLUP;

-- Use COALESCE to convert null fields into "aggregates"
SELECT COALESCE(age, 'summary'), COUNT(age) FROM teacher GROUP BY age WITH ROLLUP;
Copy the code

other.sql:

Select database
USE demo;
USE test2;

-- Displays information for each column of the table, including comments
SHOW FULL COLUMNS FROM teacher;


-- Delete a teacher
DELETE FROM teacher WHERE uid = 1;

-- Delete an administrator
DELETE FROM `admin` WHERE uid = 2;

Change -
UPDATE admin SET `password` = '123456' WHERE uid = 2;
SELECT * FROM admin;

UPDATE admin SET username = 'xu123', `password` = '12' WHERE uid = 2;

- delete
DELETE FROM admin WHERE uid = 2;

-- Display the construction sentence
SHOW CREATE TABLE admin;
Copy the code

 

 

 

 

 

Mysql primary key

MySQL primary key design principle:

  • MySQL primary keys should be meaningless to users.
  • MySQL primary key should be single column, to improve efficiency of join and filter operations (of course compound primary key is possible, just not recommended)
  • Never update the MySQL primary key
  • MySQL primary key should not contain dynamically changing data, such as timestamp, create time column, modify time column, etc
  • MySQL primary key should be generated automatically by computer.

 

Primary keys:

(1). Self-increasing sequence;

(2). Random value generated by the UUID() function;

(3). Unique account name registered by the user. It is a string of 40 characters.

(4). Generate self-incrementing values based on a set of mechanisms, such as sequence generators;

 

Mysql use autoincrement primary key has any advantages: 1) database automatic number, fast, and incremental growth, clustering type of primary key stored in order, for retrieval is very beneficial.

2) Digital, small space, easy to sort, easy to pass in the program.

www.jianshu.com/p/b8d6d809f…

 

31. Install the VM

 

1) Obtain software

 

Link: pan.baidu.com/s/1aSNL99dF… Extraction code: VI1e

 

Win7, Win10, etc system mirror obtain url:

msdn.itellyou.cn/

2) Install, by default

Create a virtual machine from VMware

Attempting to start up from:

EFI VMware Virtual SCSI Hard Drive (0.0)… unsuccessful.

EFI VMware Virtual SATA CDROM Drive (1.0) unsuccessful.

EFI Network…

 

Solutions:

1. Locate the VMX file in the installation directory of the VM

2. Delete firmware=” efI”

3. Save the Settings and restart the VM

3) Create a VM and install Windows 7

4) Install VMware Tools

1. Insert the vmware Tools ISO image file into the CD-ROM drive of the WIN7 VM

2. Start the VM

3. From the Open VM menu, select install VMware Tools from the drop-down list

4. After a while, a dialog box will pop up. Click Run Setup. exe to install the software step by step

5. Restart the VM after the installation. Files in the system can be directly copied to the VM

 

32. Grind your notes

npm config list

npm init -y

npm install/i <package name> –save-dev / -D

npm install/i <package name> –save / -S

Registration Information:

registry.npmjs.org/react

Registry.npmjs.org/react/lates…

Update package (if already installed and installed again will not update, so need update command)

npm update react

Command line login to NPM:

D:\source\m-apps\demo\ts\npm>npm login

Username: xutongbao

Password:

Email: (this IS public) [email protected]

Logged in as xutongbao on registry.npmjs.org/.

Querying a mirror source:

D:\source\m-apps\demo\ts\npm>npm get registry

registry.npmjs.org/

Setting the mirror source:

npm set registry ‘registry.npmjs.org’

Use the third-party image source management tool to manage NPM images:

npm i nrm -g

nrm ls

* npm ——– registry.npmjs.org/

yarn ——- https://registry.yarnpkg.com/

cnpm ——- r.cnpmjs.org/

taobao —– https://registry.npm.taobao.org/

nj ——— registry.nodejitsu.com/

npmMirror — https://skimdb.npmjs.com/registry/

edunpm —– registry.enpmjs.org/

nrm use taobao

nrm use npm

Contract:

npm publish

“Version” : “1.0.2”

Big release, small feature release, patch release

Unpublish the package:

npm unpublish –force

Discard a bag:

npm deprecate <pkg>