使用nodejs将html文件里的js、css抽取

单文件抽取
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文件成功!')
    })
}
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值