Node.js modular system

Node.js modular system introduced

  • To make Node.js file can call each other, Node.js provides a simple 模块系统. Node.js module is the basic component of the application, and the module file is one to one. In other words, 一个 Node.js 文件就是一个模块this document may be the JavaScript code, JSON or compiled C / C ++ extensions.
  • Module is divided into three categories
    • 内置模块 Comes with installation node environment module
    • 自定义模块 Write our own modules
    • 第三方模块 Others written module, on the web for download and use this article we will not be introduced
  • Use modules are the first to import a module, then this module to a variable that contains the entire contents of a module
'定义'var/let/const '变量'=require(' 模块名 ')
  • In this article we are not node + 文件名the way to run a file, but the use nodemon + 文件名to monitor file changes in real time, as node + 文件名every file change needs to run once again.
    • nodemoninstallationnpm install nodemon -g

Built-in module

A, fs module

//引入fs模块
const fs = require('fs')
1. File Read

Here Insert Picture Description

  • Asynchronous read
// 文件读取
// fs.readFile('地址',回调函数)  异步读取   必须写回调函数
fs.readFile("./html/index.html",(err,data)=>{
    console.log("err",err)    //如果文件读取成功,err就是null
    console.log("data",data)  //data就是读取后的文件内容
})

Here Insert Picture Description

  • Synchronous read
// fs.readFileSync   同步读取  
let data = fs.readFileSync("./html/index.html")
console.log("data",data)  

! [Insert Picture description here] (https://img-blog.csdnimg.cn/20200309224936582.png)

  • Write encoding format, read Chinese characters
fs.readFile("./html/index.html","utf-8",(err,data)=>{
    console.log("err",err)    //如果文件读取成功,err就是null
    console.log("data",data)  //data就是读取后的文件内容
})

Here Insert Picture Description

2. Change the file name
//异步  改名  必须有回调函数
//fs.rename('改前','改后',err=>{})
//同步 改名
//fs.renameSync("改前","改后")

fs.renameSync("./html/index.html","./html/about.html")
3. Delete Files
//fs.unlinkSync('文件路径')
//同步
fs.unlinkSync("./html/index.html") 
//异步 
fs.unlink("./html/about.html",err=>{})  
4. Delete the file directory
//fs.rmdir('文件路径')
//同步
fs.rmdirSync("./html/index.html")  
//异步
fs.rmdir("./html/about.html",err=>{})  

Two, http module

  • Module code
  • Creating a Web server
//1.引入http模块
const http = require("http")

//2.创建http服务对象
//http.createServer(回调函数)
const app = http.createServer((req,res)=>{
    console.log("前端访问我了...")

    //后端需要设置响应头  
    res.writeHead(200,{"Content-Type":"text/html;charset=utf-8"})//需要配置响应头才能够显示中文  不然会发生乱码
    
    
    // res.write("你好!")
    res.write(`<!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
    </head>
    <body>
        你好呀!大兄弟
    </body>
    </html>`)//可以用模板字符串  传递元素

    res.end() //后端需要结束响应  必须要填写  如果不填写  页面会一直加载
})

//3.监听端口
app.listen(8000,"localhost",()=>{
    console.log("server in running....")
})

  • Open the browser
    Here Insert Picture Description
  • Set response headerres.writeHead(200,{"Content-Type":"text/html;charset=utf-8"})
    Here Insert Picture Description

Three, url module

//引入url模块
const url = require("url")
1. url.parse(str,true)Returns true object is added to the query processing target
str -> obj  返回 对象  true 
Url{
		protocol: 'http:',	协议
		slashes: true,	双斜杠
		auth: null,   作者
		host: 'localhost:8002',  主机
		port: '8002',	端口
		hostname: 'localhost',  baidu
		hash: '#title',	哈希(锚)
		search: '?username=sdfsdf&content=234234',	查询字符串
		query: 'username=sdfsdf&content=234234',	数据
		pathname: '/aaa',	文件路径
		path: '/aaa?username=sdfsdf&content=234234',	文件路径
		href: 'http://localhost:8002/aaa?username=sdfsdf&content=234234#title'
		}
  • Do not fill true url.parse(str)
let str = "http://www.baidu.com:80/app/html/index.html?a=1&b=2#title" 
let obj = url.parse(str)
console.log(obj)

Here Insert Picture Description

  • Fill true url.parse(str,true)
let str = "http://www.baidu.com:80/app/html/index.html?a=1&b=2#title" 
let obj = url.parse(str,true)
console.log(obj)

Here Insert Picture Description

2. url.format(obj)Returns a string
const url = require("url")
let str = "http://www.baidu.com:80/app/html/index.html?a=1&b=2#title" 
let obj = url.parse(str,true)
console.log(url.format(obj))

Here Insert Picture Description

Four, querystring module

  • Processing the query string, such as:? Key = value & key2 = value2
  • querystring.parse(str) Returns the object
  • querystring.stringify(obj) Returns a string
const querystring = require("querystring")

let str = "a=1&b=2&c=3"

//str => obj
console.log(querystring.parse(str))


//obj => str
console.log(querystring.stringify({a:1,b:2}))

Here Insert Picture Description

Custom Modules

  • Write a js file, let it become a custom module
  • In another reference js file
// 这个文件就是一个我自己创建的自定义模块

// 可以在  自定义模块中  写一些方法
function fn1() {
  console.log('我是 a 模块里面的 fn1 方法')
}

function fn2() {
  console.log('我是 a 模块里面的 fn2 方法')
}


// 要把模块里面的方法导出
// 别的文件再导入 a.js 文件的时候才能得到 a 模块里面的方法
/*
  每一个 js 文件都是一个独立的模块
    + 每一个 js 文件里面天生自带一个变量叫做 module, 是一个对象
    + 每一个 module 里面有一个成员叫做 exports, 是一个对象
    + 这个 module.exports 就是这个文件向外导出的内容
    + 我们把想要向外暴露的内容添加再找个对象里面就可以了
*/

module.exports.fn1 = fn1
module.exports.fn2 = fn2

/*
  相当于再找个文件向外导出了一个对象
  {
    fn1: function fn1() {}
    fn2: function fn2() {}
  }
  谁导入 a.js 文件的时候, 谁就得到了这个对象
*/


// 我是一个 b.js 文件

// 我要导入 a.js 文件
// 我这个变量 a 得到的就是 a.js 文件里面导出的内容
const a = require('./a.js')

// 就可以使用 a 模块导出的方法了
a.fn1()
a.fn2()

Here Insert Picture Description

Learn to view documents in the official website

Enter Node.js official website or Node.js Chinese network to view the document learning

Here Insert Picture Description
Here Insert Picture Description

Here Insert Picture Description

  • Brackets [ ]content may be omitted
    Here Insert Picture Description
Published 12 original articles · won praise 74 · views 7663

Guess you like

Origin blog.csdn.net/k464746/article/details/104758466