Node.js 入门 —— path 路径模块

1 前言

本文内容来自bilibili 黑马程序员

2 什么是 path 模块

path 模块是 Node.js 官方提供的用来处理路径的模块,它提供了一系列的方法和属性,用来满足用户对路径的处理需求

3 path 相关方法

3.1 path.join()

用来将多个路径片段拼接成一个完整的路径字符串

// path.join([...paths])

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

// 注意, '../' 会抵消上一层路径
// const pathStr = path.join('/a', '/b/c', '../', 'd', 'e')
// console.log(pathStr); // '/a/b/d/e'

const pathStr = path.join('/a', '/b/c', '../../', 'd', 'e')
console.log(pathStr); // '/a/d/e'

// fs.readFile(__dirname + '/files/1.txt')
// fs.readFile(__dirname + './files/1.txt') // 报错,会将 . 拼接到路径上
fs.readFile(path.join(__dirname, './files/1.txt'), 'utf-8', (err, data) => {
    
    
  if (err) {
    
    
    console.log('读取文件失败', err);
    return
  }
  console.log(data);
})

3.2 path.basename()

用来从路径字符串中,将文件名解析出来

// path.basename(path[, ext])

const path = require('path')

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

// const basename = path.basename(fpath)
// console.log(basename); // 'index.html

const basename = path.basename(fpath, '.html')
console.log(basename); // 'index'

3.3 path.extname()

用来从路径字符串中,将后缀名解析出来

// path.extname(path)

const path = require('path')

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

const extname = path.extname(fpath)
console.log(extname); // '.html

4 综合

将以下 HTML 文件拆分成 index.html 、 index.css 、 index.js 三个文件,并将三个文件,并将文件存放到 files 文件夹下

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    body{
      
      
      background-color: red;
    }
  </style>
</head>
<body>
  <h3>welcome to my channel</h3>

  <script>
    setTimeout(() => {
      
      
      console.log('welcome to my channel');
    }, 3000);
  </script>
</body>
</html>

4.1 实现步骤

  1. 创建两个正则表达式,分别用来匹配 <style><script> 标签
  2. 使用 fs 模块,读取需要被处理的 HTML 文件
  3. 自定义 resolveCss 方法,来写入 index.css 文件
  4. 自定义 resolveJs 方法,来写入 index.js 文件
  5. 自定义 resolveHtml 方法,来写入 index.html 文件

4.2 完整代码

// 1.1 导入 fs 模块
const fs = require('fs')
// 1.2 导入 path 模块
const path = require('path')

// 1.3 匹配 <style></style> 标签的正则
// /s:匹配空白字符 /S:匹配非空白字符 *:匹配任意次
const regStyle = /<style>[\s\S]*<\/style>/
// 1.4 匹配 <script></script> 标签的正则
const regScript = /<script>[\s\S]*<\/script>/

// 2.1 调用 fs.readFile() 方法读取文件
fs.readFile(path.join(__dirname, './index.html'), 'utf-8', (err, dataStr) => {
    
    
  // 2.2 读取 HTML 文件失败
  if (err) return console.log('读取文件失败', err);
  // 2.3 读取 HTML 文件成功,调用对应的三个方法
  resolveCss(dataStr)
  resolveJs(dataStr)
  resolveHtml(dataStr)
})

// 3.1 处理 css 样式
const resolveCss = (htmlStr) => {
    
    
  // 3.2 使用正则提取页面中的 <style></style> 标签
  const r1 = regStyle.exec(htmlStr)
  // 3.3 将提取出来的 css 字符串做进一步的处理
  const newCss = r1[0].replace('<style>', '').replace('</style>', '')
  // 3.4 将处理好的 css 字符串写入 index.css 文件中 
  fs.writeFile(path.join(__dirname, './files/index.css'), newCss, err => {
    
    
    if (err) return console.log('写入文件失败', err);
    console.log('写入文件成功');
  })
}

// 4.1 处理 js
const resolveJs = (htmlStr) => {
    
    
  // 3.2 使用正则提取页面中的 <script></script> 标签
  const r1 = regScript.exec(htmlStr)
  // 3.3 将提取出来的 js 字符串做进一步的处理
  const newJs = r1[0].replace('<script>', '').replace('</script>', '')
  // 3.4 将处理好的 js 字符串写入 index.js 文件中 
  fs.writeFile(path.join(__dirname, './files/index.js'), newJs, err => {
    
    
    if (err) return console.log('写入文件失败', err);
    console.log('写入文件成功');
  })
}

// 5.1 处理 html
const resolveHtml = (htmlStr) => {
    
    
  // 5.2 将内嵌的 style 和 script 标签替换成内联的 link 和 script 标签
  const newHtml = htmlStr.replace(regStyle, '<link rel="stylesheet" href="./index.css" />').replace(regScript, '<script src="./index.js"></script>')
  // 5.3 写入 index.html 文件
  fs.writeFile(path.join('./files/index.html'), newHtml, err => {
    
    
    if (err) return console.log('写入文件失败', err);
    console.log('写入文件成功');
  })
}

4.3 注意事项

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

猜你喜欢

转载自blog.csdn.net/weixin_36757282/article/details/128255619