首页 > 编程语言 >Node.js(笔记04) - 时钟示例 - fs 和 path 模块结合应用

Node.js(笔记04) - 时钟示例 - fs 和 path 模块结合应用

时间:2022-12-22 20:03:03浏览次数:41  
标签:Node index fs console err 示例 写入 html

案例需求

将素材目录 ​./files​ 中的 index.html 页面,拆分成三个文件,分别是:

index.css

index.js

index.html

并且将拆分出来的3个文件,存放到 ​./files/clock​ 目录中;

这个index.html的全部源码:

<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>index首页</title>
<style>
html,
body {
margin: 0;
padding: 0;
height: 100%;
background-image: linear-gradient(to bottom right, red, gold);
}

.box {
width: 400px;
height: 250px;
background-color: rgba(255, 255, 255, 0.6);
border-radius: 6px;
position: absolute;
left: 50%;
top: 40%;
transform: translate(-50%, -50%);
box-shadow: 1px 1px 10px #fff;
text-shadow: 0px 1px 30px white;

display: flex;
justify-content: space-around;
align-items: center;
font-size: 70px;
user-select: none;
padding: 0 20px;

/* 盒子投影 */
-webkit-box-reflect: below 0px -webkit-gradient(linear, left top, left bottom, from(transparent), color-stop(0%, transparent), to(rgba(250, 250, 250, .2)));
}
</style>
</head>

<body>
<div class="box">
<div id="HH">00</div>
<div>:</div>
<div id="mm">00</div>
<div>:</div>
<div id="ss">00</div>
</div>

<script>
window.onload = function () {
// 定时器,每隔 1 秒执行 1 次
setInterval(() => {
var dt = new Date()
var HH = dt.getHours()
var mm = dt.getMinutes()
var ss = dt.getSeconds()

// 为页面上的元素赋值
document.querySelector('#HH').innerHTML = padZero(HH)
document.querySelector('#mm').innerHTML = padZero(mm)
document.querySelector('#ss').innerHTML = padZero(ss)
}, 1000)
}

// 补零函数
function padZero(n) {
return n > 9 ? n : '0' + n
}
</script>
</body>

</html>

效果如下:

Node.js(笔记04) - 时钟示例 - fs 和 path 模块结合应用_fs模块

其实源码内容不重要,重要的是如何把源码拆分出来:

Node.js(笔记04) - 时钟示例 - fs 和 path 模块结合应用_path模块_02

需求分析

1)创建两个正则表达式,分别用来匹配<style>和<script>标签;

2)使用 fs 模块,读取需要被处理的 HTML 文件;

3)自定义 resolveCSS() 方法,来写入 index.css 样式文件;

4)自定义 resolveJS() 方法,来写入 index.js 脚本文件;

5)自定义 revsolveHTML() 方法,来写入index.html;


代码实现

// 引入模块
const fs = require('fs')
const path = require('path')
// 定义正则,包含转义
const regStyle = /<style>[\s\S]*<\/style>/
const regScript = /<script>[\s\S]*<\/script>/
// 读取文件,使用path.join() 拼接路径
fs.readFile(path.join(__dirname, './files/index.html'), 'utf-8', (err, data) => {
// 判断,失败要 return
if (err) return console.log('出错了:', err.message)
// console.log(data);
// 调用三个方法分别写入 css,js和html
resolveCSS(data)
resolveJS(data)
resolveHTML(data)
})
// 提取css,写入新文件index.css
function resolveCSS(htmlStr) {
//提取css,替换style标签
let newCss = regStyle.exec(htmlStr)[0].replace('<style>', '').replace('</style>', '')
//写入文件
fs.writeFile(path.join(__dirname, './files/clock/index.css'), newCss, 'utf8', (err) => {
// 判断
if (err) return console.log("出错了:", err.message)
console.log('成功写入index.css');
})
}
// 提取js,写入新文件index.js
function resolveJS(htmlStr) {
let newJs = regScript.exec(htmlStr)[0].replace('<script>', '').replace('</script>', '')
fs.writeFile(path.join(__dirname, './files/clock/index.js'), newJs, 'utf8', (err) => {
if (err) return console.log("出错了:", err.message)
console.log('成功写入index.js');
})
}
// 替换link和script标签,写入新文件 index.html
function resolveHTML(htmlStr) {
let newHTML = htmlStr.replace(regStyle, '<link rel="stylesheet" href="./index.css" />').replace(regScript, '<script src="./index.js"></script>')
fs.writeFile(path.join(__dirname, './files/clock/index.html'), newHTML, 'utf8', (err) => {
if (err) return console.log('出错了:', err.message)
console.log('成功写入index.html');
})
}

提示1:两个正则的定义不难看懂;

提示2:使用fs模块读取文件也不难理解;

提示3:分别定义处理 css,js和html的三个方法;

提示4:reg.exec(sring),是正则执行,返回数组,索引为0的是匹配内容;

提示5:replace(str,str)方法返回的是匹配替换后的str,所以可以链式调用;

提示6:replace(reg,str)方法使用了正则匹配并链式调用;

提示7:所有判断 if(err) 后别忘了简写后的 return;


注意1:clock 文件夹手动建好, fs.writeFile() 只能建文件,不能建文件夹

注意2:重复执行会覆盖三个文件的内容


标签:Node,index,fs,console,err,示例,写入,html
From: https://blog.51cto.com/ahuiok/5963239

相关文章