03.node模块分类


模块

分类

在node种有很多模块,有我们自己写的javascript文件,也会有javascript自带的,还有我们可以下载别人写好的javascript。主要分为三大类。

1. 内置模块

  • 在安装node的时候就自带的模块,比如说http、fs、path等。
  • 内置模块一般在我们安装node的目录中,如果是默认安装,一般在C:\Program Files\nodejs\node_modules\npm\node_modules
  • 引入内置模块require里面只需要写模块名称,node会自动给你找到模块的文件

util模块使用

  • Node中的工具方法模块
    • util.inspect是一个将任意对象转成为字符串的方法,通常用于调试和错误的输出
        const util = require('util')
        const obj = [
            {
                a: {
                    b: {
                        c: 2
                    }
                }
            }
        ]
        console.log(obj) // 带颜色,看不到最深的层级
        console.log(util.inspect(obj, false, 10)) // 不带颜色,查看更深的层级
    

http模块的使用

  • Node中提供了http模块,其中封装了高效的http服务器和http客户端(既可以作为客户端也可以作为服务端)
    • 创建一个的HTTP服务器
      • 使用http.Server类
          const http = require('http')
          // 创建一个实例
          const server = new http.Server()
          // 接受用户的请求
          server.on('request', (req,res)=>{
              // 查看前端请求地址、请求方式、请求头
              console.log(req.url)
              console.log(req.method)
              console.log(req.headers)
              // 书写响应状态码和响应的数据格式
              res.writeHead(200, {'Content-Type': 'text/html'})
              // 返回响应的内容
              res.write('hello world');
              // 结束响应,否则会一直等待结束
              res.end()
          })
          // 每启动一个服务都需要有一个端口号支持 此处我们使用的8080端口号
          server.listen(8080, ()=> {
              console.log('服务已在localhost:8080启动')
          })
      
      • 使用http.createServer方法
          const http = require('http')
          const con = http.createServer((req,res)=>{
              // 查看前端请求地址、请求方式、请求头
              console.log(req.url)
              console.log(req.method)
              console.log(req.headers)
          // 书写响应状态码和响应的数据格式
          res.writeHead(200, {'Content-Type': 'text/html'})
          // 返回响应的内容
          res.write('hello world');
          // 结束响应,否则会一直等待结束
          res.end()
          })
          // 每启动一个服务都需要有一个端口号支持 此处我们使用的8081端口号
          con.listen(8081, ()=> {
              console.log('服务已在localhost:8081启动')
          })
      
      • 接受get请求发送过来的数据,get请求的参数都是拼接在地址后面,Nodejs的url模块中的parse函数提供了这个功能
          const http = require('http')
          const url = require('url')
          http.createServer((req, res) => {
              // get方式在url地址后面,我们可以通过截取
              console.log(req.url)
              // 截取参数部分通过url模块
              console.log(url.parse(req.url).search)
              // 书写响应状态码和响应的数据格式
              res.writeHead(200, { 'Content-Type': 'text/html' })
              // 返回响应的内容
              res.write('hello world');
              res.end()
          }).listen(8080, () => {
              console.log('服务已在8080启动')
          })
      
      • 接受post请求发送过来的数据,post请求的参数是在请求体里面,获取需要一段一段接受,Nodejs里面querystring模块parse函数可以解析获取到的数据
          
          
          const http = require('http');
          const querystring = require('querystring')
          http.createServer((req, res) => {
              // post接受数据的方式是以流方式接收 一段一段接收
              // 定义一个变量用来保存所有数据
              let postData = ''
              req.on('data', function(chunk){
                  console.log(chunk);
                  // 将每一段数据拼接保留
                  postData+=chunk
              })
              // 当我们将整个数据接受结束之后会执行这个函数
              req.on('end', function(){
                  // 最终我们接受到的数据就是完整的数据
                  console.log(postData)
                  // 但是这个数据现在是字符串的格式
                  console.log(typeof postData)
                  // 需要利用node中自带模块querystring解析
                  const data = querystring.parse(postData)
                  console.log(data)
                  // 这样我们就可以使用这个数据了
                  console.log(data.username)
                  console.log(data.password)
              })
              // 书写响应状态码和响应的数据格式
              res.writeHead(200, { 'Content-Type': 'text/html' })
              // 返回响应的内容
              res.write('hello world');
              res.end()
          }).listen(8080, () => {
              console.log('服务已在8080启动')
          })
      
    • http.request是一个HTTP客户端工具
      • 利用http.get方法发起get请求,此处以获取千峰官网为例,其实这就可以做个简单的爬虫了
          const http = require('http')
          http.get('http://www.mobiletrain.org/?pinzhuanbdtg=biaoti', (res)=>{
              let html = ''
              res.on('data', (chunk)=>{
                  html+=chunk
              })
              res.on('end', ()=>{
                  console.log(html)
              })
          })
      
      • 利用http.request可以发起post和get请求
          const http = require('http')
          const querystring = require('querystring')
          const postData = querystring.stringify({
              'a': 1
          });
      
          const options = {
              hostname: 'localhost',
              port: 8080,
              path: '/',
              method: 'POST',
              headers: {
                  'Content-Type': 'application/x-www-form-urlencoded',
                  'Content-Length': Buffer.byteLength(postData)
              }
          };
      
          const req = http.request(options, (res) => {
              console.log(`状态码: ${res.statusCode}`);
              console.log(`响应头: ${JSON.stringify(res.headers)}`);
              res.setEncoding('utf8');
              res.on('data', (chunk) => {
                  console.log(`响应主体: ${chunk}`);
              });
              res.on('end', () => {
                  console.log('响应中已无数据。');
              });
          });
          req.on('error', (e) => {
              console.error(`请求遇到问题: ${e.message}`);
          });
          req.end();
      

fs模块的使用

  • fs模块用于对系统文件及目录进行读写操作。

  • fs设计到文件的操作,文件操作会受到文件大小的影响,所以代码执行的时间是无法预估的,node提供了同步和异步的操作方式。

  • 同步

    • fs.mkdirSync 创建目录
    • fs.rmdirSync 删除目录
    • fs.readdirSync 读取目录
    • ...
  • 异步

    • fs.mkdir 创建目录
    • fs.rmdir 删除目录
    • fs.readdir 读取目录
    • fs.stat 查看文件或者文件夹信息
    • fs.readFile 读取文件
    • fs.writeFile 写入文件 文件不存在会自动创建 会覆盖之前文件内容
    • fs.appendFile 追加写入文件 文件不存在会自动创建 会在原来内容的后面追加
    • ...

path模块的使用

  • node中提供的处理文件和目录的路径的模块
  • 路径的常量
    • __dirname 当前模块的目录名
    • __filename 当前模块的文件名
        console.log(__dirname) // E:\node
        console.log(__filename) // E:\node\path.js
    
  • path的方法
    • path.basename(path[, ext]) 返回路径的最后一部分
    • path.dirname(path) 返回路径的目录名
    • path.extname(path) 返回路径的后缀名
    • path.join([...paths]) 用来拼接几个路径
    • path.normalize(path) 格式化路径 去除多余的部分
    • path.parse(path) 解析一个路径 返回一个对象
    • path.resolve([...paths]) 将路径或路径片段的序列解析为绝对路径
    • path.relative(from, to) 根据当前工作目录返回从 from 到 to 的相对路径
    console.log(__dirname) // E:\node
    console.log(__filename) // E:\node\path.js
    const path = require('path')
    // 返回路径的最后一部分
    console.log(path.basename(__dirname + '/a/b/c/file.html')) // file.html
    console.log(path.basename(__dirname + '/a/b/c')) // c
    // 返回路径的目录名
    console.log(path.dirname(__filename)) // E:\node 相当于__dirname
    console.log(path.dirname('/a/b/c/file.html')) // /a/b/c
    // 返回路径的后缀名
    console.log(path.extname(__filename)) // .js
    console.log(path.extname('/a/b/c/file.html')) // .html
    console.log(path.extname('/a/b/c')) // 空
    // 用来拼接几个路径
    console.log(path.join(__dirname, 'a','b')) // E:\node\a\b
    console.log(path.join(__dirname, 'a','file.html')) // E:\node\a\file.html
    console.log(path.join(__dirname, '/a','b')) // E:\node\a\b
    console.log(path.join(__dirname, './a','b')) // E:\node\a\b
    console.log(path.join(__dirname, '../a','b')) // E:\a\b
    console.log(path.join(__dirname, '//a','b')) // E:\node\a\b
    // 格式化路径 去除多余的部分
    console.log(path.normalize('/a//b//c///d/e')) // \a\b\c\d\e
    console.log(path.normalize('/a//b//c//../d/e')) // \a\b\d\e
    // 解析一个路径 返回一个对象
    console.log(path.parse('http://www.baidu.com/a/b/c/index.html')) 
    /* 
        {
            root: '',
            dir: 'http://www.baidu.com/a/b/c',
            base: 'index.html',
            ext: '.html',
            name: 'index'
        }
    */
    console.log(path.parse('D:/a/b/c/index.html')) 
/* 
    {
        root: 'D:/',
        dir: 'D:/a/b/c',
        base: 'index.html',
        ext: '.html',
        name: 'index'
    }
*/
// 将路径或路径片段的序列解析为绝对路径
console.log(path.resolve('a','b','c')) // E:\node\a\b\c
console.log(path.resolve('/a','b','c')) // E:\a\b\c
// 将路径或路径片段的序列解析为相对对路径
console.log(path.relative('/data/orandea/test/aaa', '/data/orandea/impl/bbb')) // ..\..\impl\bbb
console.log(path.relative('/a', '/b')) // ..\b

url模块的使用

  • url 模块提供用于网址处理和解析的实用工具
  • 一个完整url组成https://sub.example.com:8080/p/a/t/h?query=string#hash
    • 完整地址(href) https://sub.example.com:8080/p/a/t/h?query=string#hash
    • 协议(protocol ) https://
    • 域名(hostname) sub.example.com
    • 主机名(host) sub.example.com:8080
    • 源(origin) https://sub.example.com:8080
    • 端口号(port) 8080
    • 路径(pathname) /p/a/t/h
    • 请求参数
      • query query=string
      • search ?query=string
    • 哈希值(hash) #hash
  • url的属性
    • url.href
    • url.protocol
    • url.host
    • url.hostname
    • url.origin
    • url.port
    • url.pathname
    • url.query
    • url.search
    • url.hash
  • url的方法
    • url.parse(myUrl) 解析一个网址的部分
        const url = require('url')
        // 创建一个地址
        const myUrl = 'https://sub.example.com:8080/p/a/t/h?query=string#hash'
        // 解析网址部分
        console.log(url.parse(myUrl))
        /* 
            Url {
                protocol: 'https:',
                slashes: true,
                auth: null,
                host: 'sub.example.com:8080',
                port: '8080',
                hostname: 'sub.example.com',
                hash: '#hash',
                search: '?query=string',
                query: 'query=string',
                pathname: '/p/a/t/h',
                path: '/p/a/t/h?query=string',
                href: 'https://sub.example.com:8080/p/a/t/h?query=string#hash'
            }
        */
    
    • url.format(obj)
        const url = require('url')
        // 创建一个地址
        const obj = {
            protocol: 'https:',
            slashes: true,
            auth: null,
            host: 'sub.example.com:8080',
            port: '8080',
            hostname: 'sub.example.com',
            hash: '#hash',
            search: '?query=string',
            query: 'query=string',
            pathname: '/p/a/t/h',
            path: '/p/a/t/h?query=string',
            href: 'https://sub.example.com:8080/p/a/t/h?query=string#hash'
        }
        // 将一个对象转换成字符串的地址 
        console.log(url.format(obj)) // https://sub.example.com:8080/p/a/t/h?query=string#hash
    
    • url.resolve(from, to) 模拟浏览器访问地址 from是当前的页面地址 to是要访问页面地址
        const url = require('url');
        url.resolve('/one/two/three', 'four');         // '/one/two/four'
        url.resolve('http://example.com/', '/one');    // 'http://example.com/one'
        url.resolve('http://example.com/one', '/two'); // 'http://example.com/two'
    

querystring的使用

  • querystring模块提供了用于解析和格式化请求携带参数的方法。
  • 方法
    • querystring.parse(str) parse这个方法是将一个字符串反序列化为一个对象。
    • querystring.stringify(obj) stringify这个方法是将一个对象序列化成一个字符串,与querystring.parse相对。
        const querystring = require('querystring')
        console.log(querystring.parse("name=whitemu&sex=man&sex=women"))  // { name: 'whitemu', sex: [ 'man', 'women' ] }
        console.log(querystring.stringify({ name: 'whitemu', sex: [ 'man', 'women' ] })) // "name=whitemu&sex=man&sex=women"
    

2. 第三方模块

  • 第三方模块也称为第三方依赖,一般我们使用的时候需要下载,然后才能使用
  • 下载也不需要我们自己去网上找然后下载,只需要通过npm工具
  • 比如说我们后来会使用到的mysql,默认node并没有自带,用的时候需要安装
  • 引入第三方模块require里面也只需要写模块名称,node会自动给你找到模块的文件

3. 第三方模块

  • 自定义模块是我们自己实现业务逻辑的javascript文件
  • 引入自定义模块需要在require里面写文件的相对地址