NodeJs core API

Without further ado, let’s dive right into the theme and go to nodeJs for more

Fs file operation

The paths of the following files are relative paths, there will be problems, there will be optimization later

ReadFile — fs.readfile

  • ReadFile takes three parameters:
    • Parameter 1: path (the path of the file to be read)
    • Parameter 2: option (in which format the contents of the read file are compiled, utF-8 is often used)
    • Parameter 3: callback (the callback function that takes two arguments after reading the file)
      • Parameter 1: Error (result of failed file reading)
      • Parameter 2: data (result of successful file reading)
const fs = require('fs')
fs.readFile('./1.txt'.'utf-8'.function (err, data) {
  if (err) return console.log('File reading failed' + err.message)
  console.log('File read successfully' + data)
})
Copy the code

2, file write — fs.writefile

Repeat write will not report an error, will overwrite the last file content

  • WriteFile takes four arguments:
    • Parameter 1: file (path of the file to be read)
    • Parameter 2: the content to be written to the file
    • Parameter 3: option (in what format is written to the file to be compiled, default is UTF-8)
    • Parameter 4: callback (callback function, operation after writing to file, receiving one argument)
      • Parameter: Error (result of failed to read the file)
Fs.writefile ('./2. TXT ',' October ',function (err) {console.log(err); //null })Copy the code

Add file — fs.appendFile

The appending file path does not exist. The default is to create a file first and then append to the file

  • AppendFile takes four arguments:
    • Parameter 1: file (path to the appended file)
    • Parameter 2: the content to be written to the file
    • Parameter 3: option (in what format is written to the file to be compiled, default is UTF-8)
    • Parameter 4: callback (callback function, operation after writing to file, receiving one argument)
      • Parameter: Error (result of failed to read the file)
fs.appendFile('./2.txt'.'hello'.function (err) {
  console.log(err)  //null
})
Copy the code

4, About path optimization __dirname:

  • Use a relative path, if the execution is in the current folder, there will be no problem, how not to execute in the current file, an error will be reported (can not find the file to execute)
[Error: ENOENT: no such file or directory, open 'D:\demo\file\2.txt'] {
  errno: -4058.code: 'ENOENT'.syscall: 'open'.path: 'D:\\demo\\file\\2.txt'
}
Copy the code
  • Solution: Use __dirname to concatenate the path of the file to be executed

    • __dirname: indicates the absolute path of the executing file

    Example:

fs.appendFile(__dirname+'/file/2.txt'.'hello'.function (err) {
  console.log(err)
})
Copy the code

5. The __filename method is similar to __dirname

  • __filename Understood: Indicates the full path of the currently executed file. The path contains the name of the file

6. File status fs.stat

  • fs.statThere are three parameters:
    • Parameter 1: path of the detected file
    • Parameter 2: Whether the value in the returned Fs. Stats object is of type BIGint. Default value: false.
    • Parameter 3: Callback callback function: it takes two arguments
      • Parameter 1: Error Indicates that the file status fails to be retrieved
      • Parameter 2: stats: is an object that contains all the state information about the file (size, creation time, whether it is a file or directory, and so on)

7, copy the file fs.copyfile

  • fs.copyFileThere are four parameters:
    • Parameter 1: The source file name to copy

    • Parameter 2: the target file name of the copy operation.

    • Parameter 3: Modifiers for copy operations. Default value: 0.

    • Parameter 4: callback callback function, one parameter: Error, the return value of whether the copy was successful

Path Path operation

1, path.join() path join: the parameter is a path join, application scenarios: AppendFile (path.join(__dirname,’/file/2.txt’), ‘hello ‘, function (err) {console.log(err)})

2. Path. sep Obtains the system separator (/ for Windows and \ for Linux)

3. Path. basename Indicates the last part of the path

  • Two parameters:
    • Parameter 1: The path to which the last part needs to be retrieved
    • Parameter 2: Ext optional file extension. When the last parameter is specified, the returned value removes the extension

4. Path. dirname Gets the directory name of path. The result is the last/previous path with only one parameter: path path

5. Path,extname Gets the extension of the file. Only one parameter, path path, is accepted

Simple introduction to single threading and asynchrony

1. Remember three sentences:

  • JavaScript parsing and execution is always single-threaded, but the host environment (browser or Node) is multithreaded

  • Asynchronous tasks are completed by the host environment by opening child threads, and through the event driver, callback function, queue, the completed task to the main thread execution

  • The JavaScript parsing engine is always doing a job of pulling tasks from the task queue and executing them on the main thread

Modular specification

CommonJs is not supported in browsers because modules are loaded asynchronously. Each module has module, require, and exports attributes. 4. AMD/CMD is commonJs browser-side solution. Under AMD/CMD modules are loaded asynchronously (no longer available). It is now a mainstream modular solution for browsers and servers

The introduction of the package

1. What is a bag?

  • Packages are further abstractions based on modules.
  • The purpose of the package: to facilitate the distribution and promotion of applications or libraries implemented based on the CommonJS specification;
  • Packages can be thought of as a separate scope composed of modules, code, and other resources.

2. Standard package structure

  • Packages need to exist in a separate directory
  • Package. json must be in the top-level directory of the package
  • The package.json file must be in JSON format and contain the following three properties: name, version, and main
    • Name: indicates the name of the package
    • Version: indicates the package version number
    • Main: indicates the entry file of the package
  • Binaries should be in the bin directory;
  • JavaScript code should be in the lib directory;
  • The document should be in doc;
  • Unit tests should be in the test directory;
  • Node.js is not so strict about packages, as long as there is package.json in the top-level directory and it conforms to the basic specification.

3. Package description file package.json

  • Name: the name of the package, which must be unique
  • Description: A brief description of the package
  • Version: version string that conforms to the semantic version recognition specification
  • Keywords: keyword data, usually used for search
  • Maintainers: An array of maintainers. Each element contains name, email, and Web optional fields
  • Ficol3: An array of contributors, in the same format as Maintainers. The seat of the package should be the first element of the contributor data
  • Bugs: The address where bugs are submitted. This can be a web address or email address
  • Licenses: License array, each element containing the Type and URL fields
  • Repositories: Repositories hosts an array of addresses, each containing the Type, URL, and Path fields
  • Dependencies: An associative array of package names and version numbers.
  • DevDependencies: Development dependencies, which represent the dependencies that a package uses during development

4. Package file structure: Take the packaging calculator as an example

5. Introduction of NPM package

  • Global installation and local installation
    • Global installation: the package installed into the global environment of the computer, called the global package; Installed global packages can be accessed directly from the command line in any directory on the current computer.
      • Installation:NPM install package name -g
      • Path:C:\Users\ Users\ Folder \AppData\Roaming\ NPM
      • uninstallNPM uninstall Package name -g
    • Local installation: packages installed along with the project, called local packages; Local packages are installed in node_modules;
      • Install: NPM I package name –save
      • Path: node_moudles in project root directory
      • Uninstall: NPM uninstall package name –save
  • npmCommon commands:
    • — Save stands for -s

    • — Save-dev stands for -d

    • The abbreviation for install is I

    • Note: The dependencies node indicates the dependencies required when the project is deployed online. The devDependencies node represents the dependencies that the project needs during the development phase, but the packages in the devDependencies node are no longer needed when the project is ready to deploy.

    • Note: When using NPM I for quick package loading, NPM checks the package.json file for all dependencies and installs them into the project for us

    • –production Install only the packages recorded in the dependencies node and not the packages in the devDependencies node. The –production command is used when the project is about to go live

Node build server

6. Node builds the server

  • CreateServer: use const server = http.createserver () to create a server;
  • Bind listener events: bind events with server.on(‘request’, function(req, res) {request handler}) and specify handler functions;
  • Start the server: start the server by server.listen(port, IP address, successfully started callback function);
  • Prevent Chinese garbled characters in response
    • You can specify the encoding Type of the response Content by setting the content-Type of the response header to prevent garbled characters:
    res.writeHeader(200, { 
    'Content-Type': 'text/plain; charset=utf-8'}
    Copy the code
  • Returns different text content based on different urls
    • Use req.url to obtain the URL requested by the client
  • Returns different HTML pages based on different urls
    • Main idea: use FS module to read the CORRESPONDING HTML page content of URL, and use res.end() to respond to the client.
  • The final implementation of the code
const http = require('http')
const fs = require('fs')
const path = require('path')

const server = http.createServer()

server.on('request'.function (req, res) {
  // Req client-specific parameters, res represents server-specific parameters and methods

  let url = req.url
  if (url==='/') url='/view/index.html'
  fs.readFile(path.join(__dirname,url),function (err,buffer) { 
    if(err) return res.end('404. Not Found.')
    res.end(buffer)
   })
})

server.listen(3000.'127.0.0.1'.function () {
  console.log('Server running at http://127.0.0.1:3000')})Copy the code

7. Node renders dynamic pages with art-template

  • art-templatewebsite: http://aui.github.io/art-template/zh-cn/.
  • Example project: Initialize the projectnpm init
  • Install the art-template dependency package:npm install art-template
  • Create a JS file, build a simple server, and import the art-template package
  • Create an HTML file,
  • The complete code is as follows:
    • Js code:

const http  = require("http");

const template  = require("art-template");
const path  = require("path");

// Create a server
const server=http.createServer()

server.on('request'.function (req,res) { 
  const url=req.url
  if (url==='/') {
    const htmlStr=template(path.join(__dirname,'./index.html'), {name:'ls'.age:'12'.aihao: ['sleep'.'the number of money'.'ha ha']})
    res.end(htmlStr)

  }
 })

 server.listen(8080.'127.0.0.1'.function () { 
  console.log('Server running at: http://127.0.0.1:8080');
  })
Copy the code
  • The HTML code
 <! DOCTYPEhtml>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
  <title>Document</title>
</head>
<body>
  <div>Dynamic rendering</div>
  <p>Name: {{name}}</p>
  <p>Age: {{age}}</p>
  <p>{{each aihao}}<span>{{$value}}</span>
    {{/each}}
  </p>
</body>
</html>
Copy the code

8. Use of Nodemon tools

  • Function: can real-time monitor the current project, file changes; As long as the file changes are monitored, The Nodemon tool will automatically restart the Web server to make the latest code take effect. It saves programmers from having to restart the server manually;

  • How to install: Run the NPM I nodemon-g global installation.

  • How to use:

    • Previously, node.js code was run using the file path to execute node;
    • Now run the Node.js code using the file path that Nodemon wants to execute;
  • Note: When developing Web projects in the future, it is recommended to start the Web server using Nodemon

Express framework

9. Express, a framework for developing Web projects in Node

  • expresswebsite: https://www.expressjs.com.cn/.
  • Express framework features:
    • Based on the Node.js platform, HTTP modules are further encapsulated to provide a more user-friendly API
    • Using Express to create web sites is more convenient than using the native HTTP module.
    • Instead of overlaying methods in the native HTTP module, Express builds on native methods with friendlier encapsulation for a better user experience
  • Installation and basic use of the Express framework
    • Install: Run NPM I Express-S to install
    • Create a basic Express server:
      • Import express third-party module;
      • To create an instance of the server, call const app = express();
      • App.get () or app.post() to listen for client GET or POST requests.
        • App.get (‘ request address ‘, (req, res) => {handler})
        • App.post (‘ request address ‘, (req, res) => {handler})
      • Start the Express server: start the server through app.listen(port, IP address, callback function after successful startup);
  • Shortcuts in Express
    • res.send()
      • Content-type: text/ HTML;
      • Supports sending objects or arrays content-Type: application/json
      • Support to send Buffer at this time as a file download
    • res.sendFile()
      • Res.sendfile (path.join(__dirname, ‘./view/index.html’))
      • Res.sendfile (‘./view/movie.html’, {root: __dirname})
      • Note: res.sendfile () can send static pages to the browser;
  • Static resource hosting for express.static()
    • Syntax 1: app.use(express.static(‘public’));
      • The app.use() method is used specifically to register middleware;
      • Express. static is express’s built-in middleware;
const express  = require("express");

const app=express()

// Use app.use to register middleware

app.use(express.static('./view'))

app.listen(8080.() = >{
  console.log('http://127.0.0.1:8080');
})

Copy the code
  • Syntax 2: app.use(‘/ virtual directory ‘, express.static(‘public’))
    • Prefixes the access path with the public path
const express  = require("express");

const app=express()

// Use app.use to register middleware

app.use('/page',express.static('./view'))

app.listen(8080.() = >{
  console.log('http://127.0.0.1:8080');
})
Copy the code
  • Configure the template engine to render dynamic pages for the Express framework (EJS background engine)
    • Install ejS template engine NPM I EJS-S

    • Configure the default template engine app.set(‘view engine’, ‘ejs’) using app.set()

    • App.set (‘views’, ‘./views’)

    • Res.render (‘index.ejs’, {data object to render});

    • Js code

const express  = require("express");


const app=express()

// Set the template engine with app.set()
app.set('view engine'.'ejs')

app.set('views'.'./ejs_page')

app.get('/'.(req,res) = >{
  res.render('index.ejs', {name:'zs'.age:'20'.hobby: ['eat'.'sleep']})
})

app.listen(8090.() = >{
  console.log('http://127.0.0.1:8090');
})
Copy the code
  • Ejs template engine code: = is output <% %> is template syntax format
<! DOCTYPEhtml>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
  <title>Document</title>
</head>
<body>
  <div>This is the page rendered using EJS</div>
  <p>Name: <%= name %></p>
  <p>Age: <%= age %><! <% %> is the template syntax format -->
  </p>

  <% hobby.forEach(item=>{ %>
  <p> <%= item %></p>The < %}) % ></body>
</html>
Copy the code
  • Configure art-template in Express
    • Install two packages CNPM I art-template express-art-template-s

    • Custom template engine app.engine(‘ Custom template engine name ‘, rendering function)

    • App.set (‘ View engine’, ‘name of specific template engine’)

    • App.set (‘views’, ‘path ‘)

    • Js code

const express = require('express');


const app=express()

// HTML is the name of the custom template engine and the name of the suffix used to create the template engine
app.engine('html'.require('express-art-template'))

app.set('view engine'.'html')

app.set('views'.'./art_page')


app.get('/'.(req,res) = >{
  res.render('index.html', {name:'ls'.age:12.hobby: ['1'.'2'.'3']})
})
app.listen(8099.() = >{
  console.log('http://127.0.0.1:8099');
})
Copy the code
  • Template engine HTML code
<! DOCTYPEhtml>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
  <title>Document</title>
</head>
<body>
  <div>This is the page rendered using art-Template</div>

  <div>Name: {{name}}</div>
  <div>Age {{age}}</div>
{{each hobby}}
  <div>
    {{$index}}
    {{$value}}
  </div>

{{/each}}
</body>
</html>
Copy the code
  • Distribute requests using routes provided in the Express framework (introduction to routing)
    • What is routing: Routing is correspondence;
    • Back-end routing: The URL address requested by the front-end must correspond to a back-end processing function. The mapping between the URL address and the processing function is called back-end routing.
    • In Express, the primary responsibility of routing is to distribute requests to the corresponding handlers;
    • How do you define and use routes in Express?
// 1. Encapsulate separate router.js routing module files
  const express = require('express')
  // Create a routing object
  const router = express.Router()

  router.get('/'.(req, res) = >{})
  router.get('/movie'.(req, res) = >{})
  router.get('/about'.(req, res) = >{})

  // Export the route object
  module.exports = router 
Copy the code
  • Express app server, how to use the routing module?
// Import your own routing module
const router = require('./router.js')
// Use app.use() to register the route
app.use(router)
Copy the code

The concept of middleware in the Express framework

  • What is middleware
    • Definition: Middleware is a processing function; This function takes three parameters: req, RES, and next

Note the three parameters in the middleware method:

  • Req: request object;

  • Res: response object;

  • Next: Next () can be called to call the next middleware method;

  • 5 Categories of Middleware in the Express Framework

    • App.get (‘URL ‘, (req, res, next) => {});
    • Router.get (‘ URL ‘, (req, res, next)=>{})
    • Error level middleware: App.use ((err, req, res, next)=>{})
    • Only built-in middleware: express.static()
    • Third party middleware: middleware that is not provided by the Express framework and requires manual installation by programmers; Body-parser parses POST form data
  • Custom middleware that parses form data

const express  = require("express");
const querystring  = require("querystring");

const app=express()

app.use((req,res,next) = >{
  let dataStr=' '
  // Whenever the client submits a form to the server, req's data event is emitted
  // The data event can fetch incomplete data submitted by the client each time
  req.on('data'.chunk= >{
    dataStr+=chunk
  })


  // As long as reQ triggers the end event, the form data has been submitted, and the data stored in dataStr is the complete form data
  req.on('end'.() = >{
    console.log('the end',dataStr);
    // Get form data formatted, queryString.parse ()
    let str=querystring.parse(dataStr)

    req.body=str
    / / attention! In middleware, the next() method must be properly called at the end, otherwise the server will not be able to terminate the response
    next()
  })
})

app.get('/'.(req,res) = >{
  res.sendFile('./index.html', {root:__dirname})
})

app.post('/formSub'.(req,res) = >{
  // Get the data submitted from the client
  
  res.send(req.body)
})
app.listen(9090.function () { 
  console.log('the sercer running at http://127.0.0.1:9090');
 })
Copy the code

Basic I temporarily learned here, behind will continue to update