【Node.js】A complete guide to getting started with node

Article directory

1. First introduction to Node.js

(1) JS parsing engine

  • Definition:解析 and执行JS code, giving the running results
Browser Chrome Firefox Travel JSCore
JS parsing engine IE V8 OdinMonkey Chakra

(2) JS running environment

  • Definition: The necessary environment required for the code to run properly
    • Browser: V8 engine + built-in API (BOM, DOM, Canvas, ajax, JS built-in objects) + third-party library (jQuery, art-template)
    • Node.js: V8 engine + built-in API (fs, path, http, JS built-in objects, querystring) + third-party library (express + mysql)

(3) Node.js

1. Function

frame Express Electron restify
Function Build web applications Build cross-platform desktop apps Build API interface project

2. Command

  • Open terminalwin + e
  • Switch directorycd 目标目录
  • View version numbernode -v
  • Execute JS codenode js文件路径
  • Open the target directory terminalshift + 文件位置鼠标右键 + powershell
  • Quickly locate the last executed command↑ 键
  • Quick path completiontab 键
  • Quickly clear the current input commandesc 键
  • Clear the terminalcls 键

2. fs file system module

(1) fs module

  • Definition: A module officially provided by Node.js and used for操作文件
  • Import:const fs = require('fs')

(2) Method

1、fs.readFile()

  • Usage:读取Specify file content
  • Syntax: fs.readFile(path[, options], callback(err, dataStr))

path: string of file path
options: encoding format for reading files, default utf8
callback: after the file reading is completed, pass The callback function gets the reading result

  • Notice
    • It can only be used to create files and does not support creating paths.
    • Repeated calls write to the same file, and the new content overwrites the old content.

2、fs.writeFile()

  • Usage: To specify the file写入content
  • 语法:fs.writeFile(path, data[, options], callback(err, dataStr))

data: the content to be written

3. Path dynamic splicing

  • Cause: When providing 相对路径 starting with ./ or …/, a path dynamic splicing error occurs in the directory where the node command is executed
解决方案
盘符出发的完整路径
__dirname + '/相对路径'
移植性差不易维护
\为转义字符需要改为\\

3. path path module

(1) path module

  • Usage: Node.js official module provided for处理路径
  • Import:const path = require('path')

(2) Method

1、path.join()

  • Usage: Path fragments are spliced ​​into the complete path.
  • Syntax: path.join([paths…])
    • path.join(‘/a’,‘/b/c’,‘../’,‘./d’,‘e’) // \a\b\d\e
    • path.join(__dirname, ‘/filename’) // The directory where the current file is located\filename

2、path.basename()

  • Usage: Parse filename from end of path string
  • Syntax: path.basename(path[, ext])
    • path.basename(‘/a/b/c/index.html’) // index.html
    • path.basename(‘/a/b/c/index.html’, ‘.html’) // index

path: full path string
ext: file extension

3、path.basename()

  • Usage: Get path extension
  • Syntax: path.extname(path)
    • path.extname(‘/a/b/c/index.html’) // .html

4. http module

(1) http module

  • Usage: Node.js official module provided for创建 web 服务器
  • Import:const http = require('http')

(2) Web services

  • Backend: The server has web 服务器软件 installed, making it different from a regular computer. Third-party web server software such as IIS and Apache
  • Front-end: Based on the http module provided by Node.js,通过代码手写服务器软件, thereby providing external web services

(3) Server related concepts

  • IP address: on the Internet每台计算机的唯一地址, usually expressed as 点分十进制 in the form of a.b.c.d, both are decimal integers between 0-255
  • Domain name: In order to avoid the problem that the IP address is not intuitive and difficult to remember, use the字符型地址scheme
  • Domain name server: The one-to-one correspondence between DNS, IP address and domain name is stored in the domain name server, providing IP 地址和域名之间的转换service
  • Port number: There are many web services running on a computer, and each web service corresponds to a unique port number. Through the port number, the network request sent by the client can be accurately processed and submitted to对应 web 服务 for processing
    • Each port number cannot be occupied by multiple web services at the same time
    • In practical applications, the URL80端口可以被省略

(4) Create web server

1. Create a basic web server

  • Import http module
  • Create web server instance
  • Bind the request event to the server instance and listen for client requests
  • Start the server
(1)req
  • req:请求对象, contains client-related data and properties
    • req.url: request address (after port number)
    • req.method: request method
(2)res
  • res:响应对象, contains server-related data and properties
    • Solve Chinese garbled characters: manually set the content encoding format, res.setHeader(‘Content-Type’, ‘text/html; charset=utf-8’)
    • res.end(): Send the specified content to the client and end the request processing process
// 1、导入 http 模块
const http = require('http')
// 2、创建 web 服务器实例
const server = http.createServer()
// 3、调用 server.on() 方法,为服务器绑定 request 事件
server.on('request', (req, res) => {
    
    
    const str = `你请求的地址为${
      
      req.url},请求的 method 为${
      
      req.method}`
    // 3.1、解决中文乱码
    res.setHeader('Content-Type','text/html;charset=utf-8')    
    // 3.2、向客户端发送指定内容,并结束请求
    res.end(str)
})
// 4、调用 server.listen(端口号,回调) 方法,启动 web 服务器
server.listen(80, () => {
    
    
    console.log('http running at http://127.0.0.1');
})

2. Respond to different html according to different urls

  • Obtain请求的 url 地址
  • 设置默认响应内容为 404 Not found
  • Judge users请求的页面类型
  • Settings Content-Type 响应头 to prevent Chinese garbled characters
  • Use res.end() to respond the content to the client
server.on('request',(req, res) => {
    
    
    // 1、获取请求的 url 地址
    const url = req.url
    // 2、设置默认响应内容为 404 Not Found
    let content =  `<h1>404 Not Found</h1>`
    // 3、判断用户请求页面类型
    if(url === '/' || url === '/index.html'){
    
    
        content = `<h1>首页</h1>`
    }else if(url === '/about.html'){
    
    
        content = `<h1>关于页面</h1>`
    }
    // 4、设置 Content-Type 响应头,防止中文乱码
    res.setHeader('Content-Type', 'text/html; charset=utf-8')
    // 5、内容响应给客户端
    res.end(content)
})

3. Implement web server

(1) Core ideas
  • Put the file实际存放路径 as each resource请求 url 地址
    Insert image description here
(2) Implementation steps
  • Import required modules
  • Create a basic web server
  • Map the request URL address of the resource to the storage path of the file
  • Read the file content and respond to the client
  • Optimize resource request path
// 1、导入模块,处理服务器、文件、路径问题
const http = require('http')
const fs = require('fs')
const path = require('path')

// 2、创建web服务器
const server = http.createServer()
// 3、添加web服务器的request事件
server.on('request', (req, res) => {
    
    
    const url = req.url
    // 3.1、路径直接拼接
    // const fpath = path.join(__dirname, url)
    // 3.2、优化资源请求路径
    let fpath = ''
    if(url === '/'){
    
    
        fpath = path.join(__dirname, '/clock/index.html')
    }else{
    
    
        fpath = path.join(__dirname, '/clock', url)
    }
    // 4、根据映射来的文件路径读取文件
    fs.readFile(fpath, 'utf-8', (err, dataStr) => {
    
    
        if(err) return res.end('404 Not Found')
        // 成功读取的内容响应给客户端
        res.end(dataStr)
    })
})
// 5、启动服务器
server.listen(80, ()=>{
    
    
    console.log('server running at http://127.0.0.1');
})

5. Node modularization

(1) Basic concepts of modularization

  • Modularization: follow fixed rules and split large files into multiple independent and interdependent small modules
  • advantage
    • Improve code reusability
    • Improve code maintainability
    • Implement on-demand loading

(2) Node.js module classification

1. Three types of modules

  • Built-in modules: Node.js 官方提供, such as fs, path, http
  • Custom module: Each .js file of 用户创建
  • Third-party module:第三方开发module, download and use

2. Load the module

  • Syntax: require(‘name/path’)
  • Difference: fill in the name when loading built-in and third-party modules, fill in the relative path when loading custom modules
  • Note: Loading a module will execute the code in the loaded module.

3. Module scope

  • Definition: Similar to function scope, variables, methods, etc. in custom modules只能在当前模块被访问
  • Advantages: Prevent global variable pollution

4. Share members in the module scope externally

(1) module object
  • Each .js custom module has a module object that stores information related to the current module.
Module {
    
    
  id: '.',
  path: 'C:\\Users\\Administrator\\Desktop\\files',
  exports: {
    
    },
  filename: 'C:\\Users\\Administrator\\Desktop\\files\\module.js',
  loaded: false,
  children: [],
  paths: [
    'C:\\Users\\Administrator\\Desktop\\files\\node_modules',
    'C:\\Users\\Administrator\\Desktop\\node_modules',
    'C:\\Users\\Administrator\\node_modules',
    'C:\\Users\\node_modules',
    'C:\\node_modules'
  ]
}
(2) module.exports object
  • module.exports: used for externally shared module members in custom modules. When the outside world uses require() to import custom modules, what they get ismodule.exports 指定对象
  • exports: simplified version of the code,默认情况下 module.exports 和 exports 指向同一个对象, the final sharing result is subject to the object pointed to by module.exports
  • In the same module, avoid using module.exports and exports at the same time
    Insert image description here

5. Modular specifications

  • Node.js follows the CommonJS modularity specification - module features and how modules depend on each other
    • Inside each module, the module variable represents the current module
    • The module variable is an object whose exports attribute is the external interface
    • The require() method is used to load a module, that is, load the module.exports attribute of the module

(3) npm and packages

1 package

  • Definition: in Node.js 第三方模块 also known as package
  • Source: Third-party development, free and open source
  • npm: The world’s largest package sharing platform, Click here to download
  • step
    • Use the npm package management tool to install the corresponding package in the project
    • Use require() to import packages
    • Refer to the official API documentation for use
npm install 包名 // 完整版
npm i 包名 // 简写版
npm i 包名@版本(点分十进制:大版本.功能大版本.Bug修复版本) // 指定版
npm i 包名 --save-dev // 仅项目开发阶段使用的包复杂版
npm i 包名 -D // 仅项目开发阶段使用的包简写版

2. Package management configuration file

(1) Multi-person collaboration issues
  • The size of the third-party package is too large and it is inconvenient for team members to share the project source code. Node_modules needs to be eliminated when sharing.
(2) Package management configuration file
  • 项目根目录Must have package.json package management configuration file, which records the configuration information related to the project. It is convenient to share the project source code among team members after removing the node_modules directory.
    • Project name, version number, description
    • Packages used in the project
    • Packages used during development
    • Packages used during development and deployment
① Quickly create package.json
  • In the directory where the command is executed, use the shortcut command npm init -y to quickly create the package.json package management configuration file
    • Only supports running under英文目录, spaces are not supported
    • After running npm install, the npm package management tool automatically records the package's 名称 and 版本号 to package.json
② Install all packages at once
  • After getting the project with node_modules removed, you need to download all the packages into the project before it can run normally.
  • Run npm install/i command to directly read the dependencies node in package.json and download it all at once
③ Uninstall package
  • npm uninstall 包名, automatically remove the uninstalled package from the dependencies node in package.json
④ devDependencies
  • 仅项目开发阶段使用's package requires npm i 包名 -D to install and record the package to the devDependencies node
  • 开发和项目上线都使用's package npm i 包名 installs and records the package to dependencies node

3. Packet downloading speed is slow

  • Reason: npm packages use foreign servers by default, and network data transmission passes through long submarine cables.
  • Mirror: Taobao has built a server in China specifically to synchronize foreign official packages, greatly improving the speed of package downloading.
// 查看当前下包镜像源
npm config get registry
// 将下包镜像源切换为淘宝镜像源
npm config set registry=https://registry.npm.taobao.org/
// 检查镜像源是否下载成功
npm config get registry
  • nrm: Quickly view and switch package mirror sources
// 安装 nrm 为全局工具
npm i nrm -g
// 查看所有镜像源
nrm ls
// 将下包镜像源切换为 taobao 镜像
nrm use taobao

4. Bag classification

  • Global package:npm i -g, tool nature, refer to the official documentation for use
  • Project package: package installed into the project node_modules directory
    • Development dependency packages: packages recorded in the DevDependencies node,仅开发期间使用
    • Core dependency packages: packages recorded in the dependencies node,开发和上线期间使用
  • i5thing_toc: Tool for converting md documents into html pages
// 安装全局包
npm i -g i5ting_toc
// 调用包
i5ting_toc -f md文件路径 -o

5. Create and publish packages

(1) Create a new folder as the root directory of the package
(2) Basic documents
  • package.json: package management configuration file
{
    
    
  "name":"包名",
  "version":"1.0.0", //版本号
  "main":"index.js", // 入口文件
  "description":"包简介",
  "keywords":['关键词1', '关键词2', '关键词3',],
  "license":"ISC" // 开源许可协议
}
  • src: package function file
module.exports = {
    
    功能函数名} // 暴露给入口文件
  • index.js: package entry file
const exp = require('功能文件路径') //接收功能文件
module.export = {
    
    ...exp} // 暴露给外部
  • README.md: Package usage instructions
(3) Release
  • Switch the terminal to the root directory of the package and run the npm publish command
(4) Delete
  • operation npm unpublish 包名 --force command
    • Only supports deleting packages released within 72 hours
    • Deleted packages are not allowed to be republished within 24 hours.

(4) Module loading mechanism

1. Load from cache first

  • The module will be cached after being loaded for the first time. Calling require() multiple times will not cause the module code to be executed repeatedly, improving module loading efficiency.

2. Module loading mechanism

(1) Built-in modules have the highest loading priority
  • Node.js official release module with the same name is loaded first
(2) Custom module loading
  • must specify 路径标识符 starting with ./ or.../, otherwise node will treat it as 内置模块 or 第三方模块 Load
  • If you ignore the file extension when importing a custom module, node will try to load the following files in order.
    • 确切文件名
    • Complete .jsExhibition name
    • Complete .jsonExhibition name
    • Complete .nodeExhibition name
    • Loading failed and the terminal reported an error
(3) Third-party module loading
  • When there is a non-built-in module and no path at the beginning, Node.js starts from the parent directory of the current module and tries to load the third-party module from the node_modules folder.
  • If the corresponding third-party module is not found, move to the upper parent directory to load until the root directory of the file system.
(4) Directory as module
  • Find the package.json file in the directory being loaded, and look for the main attribute as the require() loading entry
  • If the package.json file does not exist or the main entry does not exist/cannot be resolved, node.js loads index.js in the directory
  • If the above two steps fail, Node.js will print an error message in the terminal: Error:Cannot find module ‘xxx’

Guess you like

Origin blog.csdn.net/weixin_64210950/article/details/127831432