Node中内置模块、模块化(module.exports与exports)

Node.js

Node.js 是一个基于 Chrome V8 引擎的 JavaScript 运行环境 。

Node 运行环境包含两个部分,分别是:

  • V8 引擎,主要负责解析 JavaScript 代码
  • 内置 API,我们学习 Node.js 重点就是学习这些内置的 API,从而能够完成后台的开发

内置模块

fs文件系统

fs模块是node.js官方提供的,用来操作文件的模块,他提供了一系列的属性和方法

fs.readFile()

用来读取指定文件的内容

fs.readFile(path,[,option],callback);

path:表示文件的路径
option:表示以什么编码格式读取文件
callback:文件读取后通过回调函数拿到读取结果

// 1. 导入 fs 模块,来操作文件
const fs = require('fs')

// 2. 调用 fs.readFile() 方法读取文件
//    参数1:读取文件的存放路径
//    参数2:读取文件时候采用的编码格式,一般默认指定 utf8
//    参数3:回调函数,拿到读取失败和成功的结果  err  dataStr
fs.readFile('./files/11.txt', 'utf8', function(err, dataStr) {
  // 2.1 打印失败的结果
  // 如果读取成功,则 err 的值为 null
  // 如果读取失败,则 err 的值为 错误对象,dataStr 的值为 undefined
  console.log(err)
  console.log('-------')
  // 2.2 打印成功的结果
  console.log(dataStr)
})

fs.writeFile()

用来向指定文件写入内容

fs.writeFile(path,data,[,option],callback);

path:表示文件的路径

data:表示要写入的内容

option:表示以什么编码格式读取文件

callback:文件读取后通过回调函数拿到读取结果

// 1. 导入 fs 文件系统模块
const fs = require('fs')

// 2. 调用 fs.writeFile() 方法,写入文件的内容
//    参数1:表示文件的存放路径
//    参数2:表示要写入的内容
//    参数3:回调函数
fs.writeFile('./files/3.txt', 'ok123', function(err) {
  // 2.1 如果文件写入成功,则 err 的值等于 null
  // 2.2 如果文件写入失败,则 err 的值等于一个 错误对象
  // console.log(err)

  if (err) {
    return console.log('文件写入失败!' + err.message)
  }
  console.log('文件写入成功!')
})

注意

  • fs.writeFile()只能用来创建文件,不能用来创建路径
  • 重复调用fs.write()写入同一个文件,新内容会覆盖之前的旧内容

path路径

path模块是node.js官方提供的,用来处理路径的模块,他提供了一系列的属性和方法

  • path.join() 方法,用来将多个路径片段拼接成一个完整的路径字符串
  • path.basename() 方法,用来从路径字符串中,将文件名解析出来

使用 path 模块来处理路径 必须先引入

const path=require('path');
path.join()

用来路径拼接

path.join(__dirname,[...path]);

__dirname:表示当前文件的目录

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

// 注意:  ../ 会抵消前面的路径
// const pathStr = path.join('/a', '/b/c', '../../', './d', 'e')
// console.log(pathStr)  // \a\b\d\e

// fs.readFile(__dirname + '/files/1.txt')

fs.readFile(path.join(__dirname, './files/1.txt'), 'utf8', function(err, dataStr) {
  if (err) {
    return console.log(err.message)
  }
  console.log(dataStr)
})

以后涉及到路径拼接的操作都要使用path.join()方法进行处理不能直接使用+号拼接

path.basename()

获取路径中的文件名

path.basename(path,[.ext]);
path<string>必选 一个路径的字符串
ext<string>可选 文件扩展名


const path = require('path')

// 定义文件的存放路径
const fpath = '/a/b/c/index.html'

// const fullName = path.basename(fpath)
// console.log(fullName)

const nameWithoutExt = path.basename(fpath, '.html')
console.log(nameWithoutExt)  //结果:index

path.extname()

获取路径中的扩展部分

path.extname(path);
path<string>必选 一个路径的字符串


const path = require('path')

// 这是文件的存放路径
const fpath = '/a/b/c/index.html'

const fext = path.extname(fpath)
console.log(fext)

http

http 模块是 Node.js 官方提供的、用来创建 web 服务器的模块。通过 http 模块提供的 http.createServer() 方法,就能方便的把一台普通的电脑,变成一台 Web 服务器,从而对外提供 Web 资源服务.

创建基本的web服务器
  1. 导入http模块
  2. 创建web服务器实例
  3. 为服务器实例绑定request事件
  4. 启动服务器
// 1. 导入 http 模块
const http = require('http')
    // 2. 创建 web 服务器实例
const server = http.createServer()
    // 3. 为服务器实例绑定 request 事件,监听客户端的请求
server.on('request', function(req, res) {
        console.log('Someone visit our web server.')
    })
    // 4. 启动服务器
server.listen(8080, function() {
    console.log('server running at http://127.0.0.1:8080')
})
req请求对象

只要访问接收到客户端的请求,就会调用通过server.on()为服务器绑定的request事件处理程序req包含了客户端相关的数据和属性

req.url 获取用户请求的url地址

req.method 获取用户的请求方式

const http = require('http')
const server = http.createServer()
    // req 是请求对象,包含了与客户端相关的数据和属性
server.on('request', (req, res) => {
    // req.url 是客户端请求的 URL 地址
    const url = req.url
        // req.method 是客户端请求的 method 类型
    const method = req.method
    const str = `Your request url is ${url}, and request method is ${method}`
    console.log(str)
        // 调用 res.end() 方法,向客户端响应一些内容
        // res.end(str)
})
server.listen(80, () => {
    console.log('server running at http://127.0.0.1')
})
res响应对象

访问与服务器相关的数据和属性

const http = require('http')
const server = http.createServer()

server.on('request', (req, res) => {
  // 1. 获取请求的 url 地址
  const url = req.url
  // 2. 设置默认的响应内容为 404 Not found
  let content = '<h1>404 Not found!</h1>'
  // 3. 判断用户请求的是否为 / 或 /index.html 首页
  // 4. 判断用户请求的是否为 /about.html 关于页面
  if (url === '/' || url === '/index.html') {
    content = '<h1>首页</h1>'
  } else if (url === '/about.html') {
    content = '<h1>关于页面</h1>'
  }
  // 5. 设置 Content-Type 响应头,防止中文乱码
  res.setHeader('Content-Type', 'text/html; charset=utf-8')
  // 6. 使用 res.end() 把内容响应给客户端
  res.end(content)
})

server.listen(80, () => {
  console.log('server running at http://127.0.0.1')
})

模块化

模块化是指解决一个复杂问题时,自顶向下逐层把系统划分成若干模块的过程。对于整个系统来说,模块是可组合、分解和更换的单元

node.js中的模块化

Node.js 中根据模块来源的不同,将模块分为了 3 大类,分别是:

  1. 内置模块(内置模块是由 Node.js 官方提供的,例如 fspathhttp 等)
  2. 自定义模块(用户创建的每个 .js 文件,都是自定 义模块)
  3. 第三方模块(由第三方开发出来的模块,并非官方提供的内置模块,也不是用户创建的自定义模块,使用前需要先下载
使用 require 方法加载模块

使用强大的 require() 方法,可以加载需要的内置模块用户自定义模块第三方模块进行使用。例如:

// 1. 加载内置的 fs 模块
const fs = require("fs");

// 2. 加载用户的自定义模块
const custom = require("./custom.js");

// 3. 加载第三方模块,(使用第三方模块,下面会进行讲解)
const moment = require("moment");

注意事项 1: 使用 require() 方法加载其他模块时,会执行被加载模块中的代码

// 加载模块.js
require("./被加载的模块.js");
// 被加载模块.js
console.log("我会被打印");

注意事项 2: 在使用 require 加载用户自定义模块期间,可以省略 .js 后缀名

// 加载模块.js
require("./被加载的模块");
模块作用域

和函数作用域类似,在自定义模块中定义的变量、方法等成员,只能在当前模块内被访问,外部文件是访问不到的,这种模块级别的访问限制,叫做模块作用域

**好处 **:防止了全局变量污染、文件依赖等问题的产生 。

module对象

在每个 .js 自定义模块中都有一个 module 对象,它里面存储了和当前模块有关的信息 。

  1. 在自定义模块中,可以使用 module.exports 对象,将模块内的成员共享出去,供外界使用
  2. 外界用 require() 方法导入自定义模块时,得到的就是 module.exports 所指向的对象
// 被加载的模块.js

// 向 module.exports 对象上挂载 username 属性
module.exports.username = "zs";

// 向 module.exports 对象上挂载 sayHello 方法
module.exports.sayHello = function() {
  console.log("Hellp");
};

注意点:使用 require() 方法导入模块时,导入的结果,永远以 module.exports指向的对象为准

// 加载模块.js
const mo = require("./被加载的模块.js");

console.log(mo); // { username: '小黑', sayHi: [Function: sayHi] }


// 被加载模块.js

// 当外界使用 require 导入一个自定义模块的时候,得到的成员,就是模块中,通过 module.exports 指向的那个对象
// console.log(module)

// 向 module.exports 对象上挂载 username 属性
module.exports.username = "zs";

// 向 module.exports 对象上挂载 sayHello 方法
module.exports.sayHello = function() {
  console.log("Hellp");
};

// 使用 module.exports 指向一个全新的对象
module.exports = {
  username: "小黑",
  sayHi() {
    console.log("小黑");
  },
};
exports对象

由于 module.exports 单词写起来比较复杂,为了简化向外共享成员的代码,Node 提供了 exports 对象。默认情况下,exportsmodule.exports 指向同一个对象。最终共享的结果,还是以 module.exports 指向的对象为准

console.log(exports);

console.log(module.exports);

// 默认情况下,`exports` 和 `module.exports` 指向同一个对象
console.log(exports === module.exports); // true


// 将私有成员共享出去
exports.username = "zs";

// 直接挂载方法
exports.sayHello = function() {
  console.log("Hellp");
};
使用exports与module.exports的注意点
  1. require() 模块时,得到的永远是 module.exports 指向的对象
  2. 为了防止混乱,建议大家不要在同一个模块中同时使用exports和module.exports
CommonJS模块化规范
  1. Node.js 遵循了 CommonJS 模块化规范,CommonJS规定了模块的特性和各模块之间如何相互依赖
  2. CommonJS 规定:
  • 每个模块内部,module 变量代表当前模块
  • module 变量是一个对象,它的 exports 属性(即 module.exports)是对外的接口
  • 加载某个模块,其实是加载该模块的 module.exports 属性。require() 方法用于加载模块
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值