单文件抽取
path.join() 路径拼接,dirname前面有两条下划线"_",表示当前文件路径。
// 用于将html里的js、css抽取
const path = require('path')
const fs = require('fs')
// 正则表达式
const regStyle = /<style>[\s\S]*<\/style>/
const regScript = /<script>[\s\S]*<\/script>/
fs.readFile(path.join(__dirname, './index.html'), 'utf8', function(err, dataStr) {
if (err) return console.log("读取HTML失败!", err.message)
resolveCSS(dataStr)
resolveJS(dataStr)
resolveHTML(dataStr)
})
// 抽取css
function resolveCSS(htmlStr) {
const r1 = regStyle.exec(htmlStr)
const newCSS = r1[0].replace('<style>', '').replace('</style>', '')
// console.log(newCSS)
fs.writeFile(path.join(__dirname, './clock/index.css'), newCSS, function(err) {
if (err) return console.log("写入CSS失败!", err.message)
console.log('写入样式文件成功!')
})
}
// 抽取JS
function resolveJS(htmlStr) {
const r1 = regStyle.exec(htmlStr)
const newJS = r1[0].replace('<script>', '').replace('</script>', '')
// console.log(newCSS)
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)
console.log('写入HTML文件成功!')
})
}