Nodejs fs、path简单应用

需求描述:Nodejs将html内的代码内部引用的css、js部分,处理为外部引用

boxDemo文件夹

运行splitBoxHtml.js文件作用:

  1. 创建三个文件,box.html、box.css、box.js

  1. 将指定内容写入其中


boxDemo下的box.html(源文件)

<html>
    <head>
        <title>盒子</title>
        <style>
            #box{
                height: 200px;
                background-color: aquamarine;
            }
        </style>
    </head>
    <body>
        <div id="box"></div>
        <input type="button" onclick="clickButton()" value="变色">
    
        <script>
            var box = document.getElementById('box');
            var flag = true;
            function clickButton(){
                if(flag === true){
                    box.style.background = 'red';
                    flag = false;
                } else {
                    box.style.background = 'aquamarine';
                    flag = true;
                };
            }
        </script>
    </body>
</html>

splitBoxHtml.js处理boxDemo下的box.html(源文件)

const fs = require('fs');
const path = require('path');
// css正则
const regStyle = /<style>[\s\S]*<\/style>/g
// js正则
const regScript= /<script>[\s\S]*<\/script>/g

// 读文件
fs.readFile(path.join(__dirname,'/box.html'),'utf-8',(err,data)=>{
    if(err){
        console.log(err);
    } else {
        //拿到css写入指定文件
        let strStyle = regStyle.exec(data)[0].replace('<style>','').replace('</style>','');
        resolveText(strStyle,'box.css');
        // 拿到js写入指定文件
        let strScript = regScript.exec(data)[0].replace('<script>','').replace('</script>','');
        resolveText(strScript,'box.js');
        // 拿到html写入指定文件
         let newHtml = data.replace(regStyle,'<link rel="stylesheet" href="./resolveCss.css">').replace(regScript,'<script src="./resolveScript.js"></script>');
        resolveText(newHtml,'box.html');
        
    }
})
// 写入指定文件
function resolveText(target,fileName){
    // 将target写进指定fileName的文件
    fs.writeFile(path.join(__dirname,`/box/${fileName}`),target,(err)=>{
        if(err == null){
            console.log(`写入${fileName}成功`);
        } else {
            console.log(`写入${fileName}失败`);
        }
    })
}

运行结果图

box文件下产生三个文件,开始为空


三个文件内容为:


注意事项:

fs.writeFile(path.join(__dirname,`/box/${fileName}`),target,(err)=>{
        if(err == null){
            console.log(`写入${fileName}成功`);
        } else {
            console.log(`写入${fileName}失败`);
        }
    })
  • 参数一:路径,该路径下如果没有此文件,就会新建该文件,再写,有该文件,就会直接写;如果路径写错了,并不会新建路径,比如此处`/box/${fileName}`前提是存在box文件夹,如果是`/box1/${fileName}`就会报错

  • 参数二:要写进去的内容

  • 参数三:回调拿到操作是否成功

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值