0
点赞
收藏
分享

微信扫一扫

【Node.JS 练习】时钟案例


目录

​​案例要求​​

​​实现​​

​​步骤​​

​​创建 正则表达式​​

​​使用相关模块,读取需要被处理的html文件​​

​​自定义resolve方法​​

​​css​​

​​ js​​

​​ html​​

案例要求

 将素材目录下的index.html页面,拆分成三个文件,分别是:index.css,index.js,index.html

并且将拆分出的三个文件存放到clock目录中。

<style>
body {

background-image: linear-gradient(to bottom right, rgb(157, 30, 18), rgb(242, 197, 1));
background-attachment: fixed;
}

.container {
width: 50%;
height: 50vh;
background-color: rgb(255, 255, 255);
opacity: 0.2;
position: relative;
margin: 0 auto;
top: 25vh;
}

.container div {
line-height: 150px;
text-align: center;
font-size: 50px;
width: 50%;
height: 150px;
display: inline-block;
position: absolute;
inset: 0;
margin: auto;
}
</style>
</head>

<body>

</body>
<div class="container">
<div>
<span>
11:11:00
</span>
<h2>index</h2>
</div>
</div>

<script>

</script>

【Node.JS 练习】时钟案例_node.js

实现

步骤

  1. 创建两个正则表达式,分别用来匹配<style>和<script>标签。
  2. 使用fs模块,读取需要被处理的html文件。
  3. 自定义resolveCSS方法,来写入index.css样式文件
  4. 自定义resolveJS方法,来写入index.js脚本文件
  5. 自定义resolveHTML方法,来写入index.html文件

创建 正则表达式

const fs = require('fs');
const path = require('path');
//定义正则表达式
const restyle = /<style>[\s\S]*<\/style>/
const rescript = /<script>[\s\S]*<\/script>/

引入fs模块和路径模块。

用正则表达式来匹配style标签,包含内部所有的空白和非空白字符,数量是任意个。

使用相关模块,读取需要被处理的html文件

fs.readFile(path.join(__dirname, '/index.Html'), 'utf-8', function (err, data) {
if (err) {
console.log('读取文件失败' + err);
} else {
console.log('读取文件成功');
}

resolveCss(data);
})

自定义resolve方法

css

function resolveCss(cssStr) {
//正则匹配css
const r1 = restyle.exec(cssStr);
//替换掉非必要标签
const newCss = r1[0].replace('<style>', '').replace('</style>', '');
//将提取内容写入到clock目录中一个index.css中
fs.writeFile(path.join(__dirname, '/clock/index.css'), newCss, function (err) {
if (err) {
return console.log('导入css样式失败' + err);
} else {
console.log('写入样式成功');
}

})

}

【Node.JS 练习】时钟案例_html_02

生成了一个css文件

【Node.JS 练习】时钟案例_前端_03

 js

function resolveJS(jsStr) {
//正则匹配js
const r1 = rescript.exec(jsStr);
//替换掉非必要标签
const newJs = r1[0].replace('<script>', '').replace('</script>', '');
//将提取内容写入到clock目录中一个index.js中
fs.writeFile(path.join(__dirname, '/clock/index.js'), newJs, function (err) {
if (err) {
return console.log('导入js样式失败' + err);
} else {
console.log('写入样式成功');
}
})

}

 html

function resolveHtml(htmlStr) {
const newHtml = htmlStr.replace(restyle, '<link rel="stylesheet" href="./index.css"/>')
.replace(rescript, '<script src = "./index.js"></script>')
fs.writeFile(path.join(__dirname, '/clock/index.html'), newHtml, function (err) {
if (err) {
console.log('导入html文件失败' + err);
} else {
console.log('导入成功');
}
})
}

【Node.JS 练习】时钟案例_node.js_04

【Node.JS 练习】时钟案例_node.js_05

 

 

举报

相关推荐

0 条评论