需求描述:Nodejs将html内的代码内部引用的css、js部分,处理为外部引用
boxDemo文件夹
运行splitBoxHtml.js文件作用:
创建三个文件,box.html、box.css、box.js
将指定内容写入其中
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}`就会报错
参数二:要写进去的内容
参数三:回调拿到操作是否成功