前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >node.js读取、拆分HTML文件中的CSS、Script、HTML模块到不同文件

node.js读取、拆分HTML文件中的CSS、Script、HTML模块到不同文件

作者头像
倾盖
发布2022-08-16 14:33:48
4.1K0
发布2022-08-16 14:33:48
举报
文章被收录于专栏:RivenCabinRivenCabin

代码:

代码语言:javascript
复制
const fs = require('fs')
const path = require('path')

// 匹配style标签的正则 \s匹配所有空格;\S匹配所有非空格;*代表无限次
const regStyle = /<style>[\s\S]*<\/style>/
// 匹配script标签的正则
const regScript = /<script>[\s\S]*<\/script>/

// 读取文件
fs.readFile(path.join(__dirname, './009-index.html'), 'utf-8', function (err, dataStr) {
    // 读取失败时直接return
    if (err) return console.log('读取html文件失败了', err.message);
    // 读取成功后,调用对应的三个方法,分别拆解出css、js、html文件
    resolveCss(dataStr);
    resolveJS(dataStr);
    resolveHTML(dataStr);
})

// 定义处理css样式的方法
function resolveCss(htmlStr) {
    // 使用正则提取需要的内容
    const r1 = regStyle.exec(htmlStr)
    // 将提取出来的样式字符串,进行字符串的replace替换操作
    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('写入样式文件成功了!');
    })
}

// 定义处理script的方法
function resolveJS(htmlStr) {
    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('写入script失败!', err.message);
        console.log('写入script成功!');
    })
}

// 定义处理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失败!', er.message);
        console.log('写入HTML成功!');
    })
}

最终生成效果:

image-20220122001810336
image-20220122001810336
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档