Node.js的模块化系统

Node.js模块化系统介绍

  • 为了让Node.js的文件可以相互调用,Node.js提供了一个简单的模块系统。模块是Node.js 应用程序的基本组成部分,文件和模块是一一对应的。换言之,一个 Node.js 文件就是一个模块,这个文件可能是JavaScript 代码、JSON 或者编译过的C/C++ 扩展。
  • 模块分为三类
    • 内置模块 安装node环境时自带的模块
    • 自定义模块 我们自己写的模块
    • 第三方模块 别人写好的模块,放在网上供我们下载使用 本文不作介绍
  • 模块的使用都是先导入某个模块,然后将这个模块给一个变量,这个变量就包含了某个模块的所有内容
'定义'var/let/const '变量'=require(' 模块名 ')
  • 在本文中都不用node + 文件名的方法运行文件,而是使用nodemon + 文件名来实时监听文件的变化,因为node + 文件名文件每一次改变都需要重新运行一次。
    • nodemon的安装npm install nodemon -g

内置模块

一、 fs模块

//引入fs模块
const fs = require('fs')
1.文件读取

在这里插入图片描述

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

在这里插入图片描述

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

![在这里插入图片描述](https://img-blog.csdnimg.cn/20200309224936582.png)

  • 写上编码格式,读取汉字
fs.readFile("./html/index.html","utf-8",(err,data)=>{
    console.log("err",err)    //如果文件读取成功,err就是null
    console.log("data",data)  //data就是读取后的文件内容
})

在这里插入图片描述

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

fs.renameSync("./html/index.html","./html/about.html")
3.删除文件
//fs.unlinkSync('文件路径')
//同步
fs.unlinkSync("./html/index.html") 
//异步 
fs.unlink("./html/about.html",err=>{})  
4.删除文件目录
//fs.rmdir('文件路径')
//同步
fs.rmdirSync("./html/index.html")  
//异步
fs.rmdir("./html/about.html",err=>{})  

二、http模块

  • 模块代码
  • 创建了一个Web服务器
//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....")
})

  • 在浏览器中打开
    在这里插入图片描述
  • 设置的响应头res.writeHead(200,{"Content-Type":"text/html;charset=utf-8"})
    在这里插入图片描述

三、url模块

//引入url模块
const url = require("url")
1.url.parse(str,true) 返回对象 添加true 将query处理为对象
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'
		}
  • 不填 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)

在这里插入图片描述

  • 填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)

在这里插入图片描述

2.url.format(obj) 返回字符串
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))

在这里插入图片描述

四、querystring 模块

  • 处理查询字符串 如:?key=value&key2=value2
  • querystring.parse(str) 返回对象
  • querystring.stringify(obj) 返回字符串
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}))

在这里插入图片描述

五、path模块

path介绍
  • 编码
    • windows: c:\\user\\admin\\a.jpg
  • UI呈现(控制台的打印)
    • windows: c:\user\admin
  • API
    • 磁盘路径解析path.parse 得到一个对象
    • 片段合并 path.join 片段先后顺序不能更改
    • 魔术变量 _dirname node.js提供的一个全局变量 获取当前文件路径
    • 片段合并path.resolve 合并磁盘片段,从右到左找根路径,如果没有找到根,以当前文件路径为根路径
代码
//引入path系统mokuai
const path=require('path')

let str='c:\\windows\\images\\a.jpg'
// let str='windows/images/a.jpg'    两种写法都可以

//1. 磁盘路径解析 path.parse   得到一个对象  
console.log(path.parse(str))
/*
{
    root: 'c:\\',   盘符
    dir: 'c:\\windows\\images',  目录   
    base: 'a.jpg',  文件名
    ext: '.jpg',    扩展名
    name: 'a'   文件,不含扩展名
  }
*/
console.log(path.parse(str).ext)//    可以得到对象里任意一个属性  例如扩展名ext    .jpg


//2. 片段合并 path.join   片段先后顺序不能更改
let str1='c:\\windows'
let str2='images'
let str3='a.jpg'

console.log(path.join(str1,str2,str3))  //    c:\windows\images\a.jpg
console.log(path.join(str1,str2))      //       c:\windows\images      拼接完毕后会有盘符


//3. 魔术变量 _dirname   node.js提供的一个全局变量    获取当前文件路径
console.log(__dirname)      //C:\Users\admin\Desktop\file
console.log(path.join(__dirname,str2,str3))     //  C:\Users\admin\Desktop\file\images\a.jpg

//4. 片段合并path.resolve   合并磁盘片段,从右到左找根路径,如果没有找到根,以当前文件路径为根路径

//相当于   console.log(path.join(__dirname,str2,str3)) 
console.log(path.resolve(str2,str3))    //  C:\Users\admin\Desktop\file\images\a.jpg

console.log(path.resolve("c:\\",str2,str3))     // c:\images\a.jpg

//从右到左找到根路径  则根路径左侧的片段不参与合并
console.log(path.resolve("a","b","D:\\abc","c.jpg"))    //  D:\abc\c.jpg   

自定义模块

  • 写一个js文件,让其成为自定义模块
  • 在另一个js文件中引用

两种输出方法

exports.自定义属性 = 值 | any
  • 批量输出 都是属性

  • 可输出多次

  • 先写一个a.js文件

let a=10
let b='jack'
let fn=()=>{
    console.log('函数')
}

// 输出多次
exports.name=a
exports.b=b
exports.fn=fn
  • index.js文件中引入
//文件后缀  .js  可以省略不写
let a1=require('./mod/a.js')
console.log(a1)
a1.fn()

在这里插入图片描述

module.exports = 值 | any
  • 只能输出一次
  • 写一个b.js文件
let a=10
let b='jack'
let fn=()=>{
    console.log('函数')
}
class Person{
    constructor(){
        console.log('这是Person构造函数')
    }
    show(){
        console.log('这是show方法...')
    }
}

// 输出一次    只会输出  b  的值  
//module.exports=a;
//module.exports=b;


//写成对象就可以输出多个值
// module.exports={
//     a:a,
//     b:b,
//     fn:fn,
//     Person:Person
// }

// key值  和  value  值相同时   可以只写key值
module.exports={
    a,b,fn,Person
}
  • index.js文件中引入
let a1=require('./mod/b.js')

console.log(a1)

let person=new a1.Person()
person.show()

在这里插入图片描述

在官网查看文档学习

进入Node.js官网或者Node.js中文网查看文档学习

在这里插入图片描述
在这里插入图片描述

在这里插入图片描述

  • 方括号[ ]中的内容可以省略
    在这里插入图片描述
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值