文章目录
一、时钟页面实现准备
- 时钟效果图
HTML+CSS+JS代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>时钟首页</title>
<style>
.box {
width: 400px;
height: 250px;
border: 5px solid black;
margin: 100px auto;
line-height: 250px;
text-align: center;
font-size: 70px;
font-weight: 700;
background-color: pink;
}
</style>
</head>
<body>
<div class="box"></div>
<script>
setInterval(function () {
function getTimer() {
var time = new Date();
var h = time.getHours();
h = h < 10 ? '0' + h : h;
var m = time.getMinutes();
m = m < 10 ? '0' + m : m;
var s = time.getSeconds();
s = s < 10 ? '0' + s : s;
return h + ':' + m + ':' + s;
}
var box = document.querySelector('.box');
box.innerHTML = getTimer();
})
</script>
</body>
</html>
二、拆分时钟文件案例
1. 拆分要求和步骤分析
- Node.js拆分时钟案例要求
- 拆分实现步骤
2. 拆分实现步骤
步骤1 - 导入需要的模块并创建正则表达式
// 1.1 导入 fs 模块
const fs = require('fs');
// 1.2 导入 path 模块
const path = require('path');
// 1.3 定义正则表达式,分别匹配 <style></style> 和 <script></script> 标签
// 其中 \/ 表示对(/)进行转义;\s 表示匹配空白字符;\S 表示匹配非空白字符;* 表示匹配任意次
// 所以 [\s\S]* 表示匹配任意字符
const regStyle = /<style>[\s\S]*<\/style>/;
const regScript = /<script>[\s\S]*<\/script>/;
步骤2 - 使用 fs 模块读取需要被处理的 html 文件
// 2.1 调用 fs.readFile() 方法读取 html 文件
// E: \Code2022\Nodejs\day01\素材\index.html
// E: \Code2022\Nodejs\day01\code
fs.readFile(path.join(__dirname, '../素材/index.html'), 'utf8', function (err, dataStr) {
// 2.2 读取 HTML 文件失败
if (err) {
return console.log('读取HTML文件失败!' + err.message);
}
// 2.3 读取 HTML 文件成功后,调用相应的方法,拆解出 css、js 和 html 文件
resolveCSS(dataStr);
resolveJS(dataStr);
resolveHTML(dataStr);
})
步骤3 - 自定义 resolveCSS 方法
// 3.1 定义处理 css 样式的方法
function resolveCSS(htmlStr) {
// 3.2 使用正则提取页面中的 <style></style> 标签
const r1 = regStyle.exec(htmlStr);
// 3.3 将提取出来的样式字符串,进行字符串的 replace 替换操作,替换前后的 style 标签
const newCSS = r1[0].replace('<style>', '').replace('</style>', '');
// 3.4 调用 fs.writeFile() 方法,将提取的样式,写入到 clock 目录下的 index.css 文件中
fs.writeFile(path.join(__dirname, './clock/index.css'), newCSS, function (err) {
if (err) {
return console.log('写入 CSS 样式失败!' + err.message);
}
console.log('写入 CSS 样式成功!');
})
}
- 3.2 使用正则匹配页面中的 <style> 标签后的结果
- 3.3 将提取出来的字符串,进行替换操作,替换前后的 style 标签的结果
- 3.4 写入 index.css 成功
步骤4 - 自定义 resolveJS 方法
// 4.1 定义处理 js 样式的方法
function resolveJS(htmlStr) {
// 4.2 使用正则提取页面中的 <script></script> 标签
const r2 = regScript.exec(htmlStr);
// 4.3 将提取出来的脚本字符串,进行 replace 替换操作,替换前后的 script 标签
const newJS = r2[0].replace('<script>', '').replace('</script>', '');
// 4.4 调用 fs.writeFile() 方法,将提取的样式,写入到 clock 目录下的 index.js 文件中
fs.writeFile(path.join(__dirname, './clock/index.js'), newJS, function (err) {
if (err) {
return console.log('写入 JS 样式失败!' + err.message);
}
console.log('写入 JS 样式成功!');
})
}
- 4.2 使用正则匹配页面中的 <script> 标签后的结果
- 4.3 将提取出来的字符串,进行替换操作,替换前后的 script 标签的结果
步骤5 - 自定义 resolveHTML 方法
// 5.1 定义处理 html 结构的方法
function resolveHTML(htmlStr) {
// 5.2 将字符串调用 replace 方法,将内嵌的 style 和 script 标签,替换成外联的 link 和 script 标签
const newHTML = htmlStr
.replace(regStyle, '<link rel="stylesheet" href="./index.css">')
.replace(regScript, '<script src="./index.js"></script>');
// 5.3 写入 index.html 文件
fs.writeFile(path.join(__dirname, './clock/index.html'), newHTML, function (err) {
if (err) {
return console.log('写入 HTML 样式失败!' + err.message);
}
console.log('写入 HTML 样式成功!');
})
}
- 5.2 调用 replace 方法,将内嵌的 style 和 script 标签,替换成外联的 link 和 script 标签
- 目录结构
3. 拆分注意点
fs.writeFile()
方法只能用来创建文件,不能用来创建路径(目录)
例如,当删除目录结构中的clock目录时,会出现以下错误:
因此,需要提前创建好clock文件。- 重复调用
fs.writeFile()
写入同一个文件,新写入的内容会覆盖之前所有的旧内容。
三、 实现时钟的Web服务器
1. 核心思路
浏览器和磁盘目录之间是不可以相互访问,但是浏览器可以通过访问中间的Web服务器从而请求磁盘目录上的资源;然后Web服务器可以读取磁盘目录上的资源,把读取到的内容通过响应的形式发送给浏览器客户端。
其中,服务器充当媒介作用,充当了读文件的角色。
重点:把文件的实际存放路径,作为每个资源的请求url地址
。
2. 步骤分析
3. 具体实现
// 1.1 导入 http 模块
const http = require('http');
// 1.2 导入 fs 模块
const fs = require('fs');
// 1.3 导入 path 模块
const path = require('path');
// 2. 创建基本的 web 服务器
// 2.1 创建 web 服务器实例
const server = http.createServer();
// 2.2 为 web 服务器实例绑定 request 事件,监听客户端请求
server.on('request', (req, res) => {
// 3.1 获取到客户端请求的 url 地址(是不完整的路径)
// /clock/index.html
// /clock/index.css
// /clock/index.js
const url = req.url;
// 3.2 把请求的 url 地址,映射为具体文件的存储路径
const fpath = path.join(__dirname, url);
// 4. 读取文件的内容并响应给客户端
// 4.1 根据“映射”过来的文件路径读取文件
fs.readFile(fpath, 'utf8', (err, dataStr) => {
// 4.2 读取失败后,向客户端响应固定的“错误消息”
if (err) {
return res.end('404 Not found!');
}
// 4.3 读取成功后,向“读取成功的内容”响应给客户端
res.end(dataStr);
});
});
// 2.3 启动 web 服务器
server.listen(80, () => {
console.log('server running at http://127.0.0.1');
});
但是,在客户端浏览器请求index.html页面时,只能通过127.0.0.1/clock/index.html
进行访问,而在真实的网站中,可以通过127.0.0.1/
或127.0.0.1/index.html
都可进行访问首页。因此,我们需要对资源的请求路径进行优化:
// 3.2 把请求的 url 地址,映射为具体文件的存储路径
// const fpath = path.join(__dirname, url);
// *** 将 3.2 的代码改成如下形式 ****
// 5.1 预定义空白的文件存放路径
let fpath = '';
if (url === '/') {
fpath = path.join(__dirname, './clock/index.html');
} else {
// /index.html
fpath = path.join(__dirname, './clock', url);
}