综合案例- 时钟案例

案例要实现的内容

案例实现步骤

  1. 创建两个正则表达式,分别用来匹配 < style > 和 < script > 标签
  2. 使用 fs 模块,读取需要被处理的 HTML 文件
  3. 自定义 resolveCSS 方法,来写入 index.css 样式文件
  4. 自定义 resolveJS 方法,来写入 index.js 脚本文件
  5. 自定义 resolveHTML 方法,来写入 index.html 文件
  • 导入模块
//导入fs模块
const fs = require('fs')
//导入path模块
const path = require('path')
  • 定义正则表达式
// 定义正则表达式
const regStyle = /<style>[\s\S]*<\/style>/
const regScript = /<script>[\s\S]*<\/script>/
  • 处理文档
//使用fs模块读取需要处理的html文件

fs.readFile(path.join(__dirname, './clock/index.html'), 'utf-8', (err, dataStr) => {
  //读取HTML文件失败
  if (err) return console.log('文件读取失败!' + err.message)
  resolveCSS(dataStr)
  //读取HTML文件成功后,调用方法
  resolveJS(dataStr)

  resolveHTML(dataStr)
})


function resolveCSS(htmlStr) {
  //使用正则表达式来提取出style标签里面的内容
  const r1 = regStyle.exec(htmlStr)
  //将提取出来的样式字符串,做进一步的处理(替换处理)
  const newCSS = r1[0].replace('<style>', '').replace('</style>', '')
  fs.writeFile(path.join(__dirname, './clock/index.css'), newCSS, err => {
    if (err) {
      return console.log('写入css样式失败!' + err.message);
    }
    console.log('写入CSS样式成功');
  })
}

function resolveJS(htmlStr) {
  //使用正则表达式提取出 script标签里面的内容
  const r2 = regScript.exec(htmlStr)
  const newJS = r2[0].replace('<script>', '').replace('</script>', '')

  fs.writeFile(path.join(__dirname, './clock/index.js'), newJS, err => {
    if (err) {
      return console.log('写入Js失败!' + err.message);
    }
    console.log('写入JS成功');
  })
}

//定义处理 HTML 结构的方法
function resolveHTML(htmlStr) {
  const newHTML = htmlStr
    .replace(regStyle, '<link rel="stylesheet" href="./index.css" />')
    .replace(regScript, '<script src="./index.js"></script>')
  //接下来写入文档中
  fs.writeFile(path.join(__dirname, './clock/index.html'), newHTML, err => {
    if (err) {
      return console.log('html文件写入失败' + err.message);
    }
    return console.log('html文件写入成功!');
  })

}

posted @ 2022-04-14 08:42  抗争的小青年  阅读(40)  评论(0编辑  收藏  举报