案例要实现的内容
案例实现步骤
- 创建两个正则表达式,分别用来匹配 < style > 和 < script > 标签
- 使用 fs 模块,读取需要被处理的 HTML 文件
- 自定义 resolveCSS 方法,来写入 index.css 样式文件
- 自定义 resolveJS 方法,来写入 index.js 脚本文件
- 自定义 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文件写入成功!');
})
}
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/9830.html