1. fs 文件系统模块
fs.readFile() 用来读取指定文件内容
//导入fs模块
const fs = require('fs')
//调用fs.readFile读取文件
//参数一 读取文件存放路径
//参数二 默认编码格式 utf-8
//参数三回调函数 读取到失败和成功的结果
fs.readFile('1.txt', 'utf-8', function (err, dataStr) {
if (err) {
return console.log("读取失败" + err.message)
} else {
console.log(dataStr)
}
})
fs.wirteFile() 用来向指定文件中写入内容
// 如何向指定文件写入内容
// fs.writeFile() 向指定文件写入内容
// 参数1 指定文件路径是一个字符串
// 参数2 表示要写入的内容
// 参数3 可选 表示文件写入格式
// 参数4 必选 文件完成的回调函数
//导入fs模块
const fs = require('fs')
//调用fs.writeFile()
fs.writeFile('1.txt', "2222222", function (err) {
//ruguow如果文件写入成功打印null
//如果文件写入失败则打印错误对象
// console.log(err)
if (err) {
console.log("文件写入失败", err.message)
}
console.log('文件写入成功')
})
2. 时钟案例
利用fs模块的读取和写入拆分 index.html(如下) ,将其拆分为三部分index.js,index.css,index.html
// 1.1 导入 fs 模块
const fs = require('fs')
// 1.2 导入 path 模块
const path = require('path')
//定义正则表达式,分别匹配 <style></style> 和 <script></script> 标签
const regStyle = /<style>[\s\S]*<\/style>/
const regScript = /<script>[\s\S]*<\/script>/
//调用fs.readFile()方法读取文件
fs.readFile(path.join(__dirname, '素材/index.html'), 'utf-8', function (err, dataStr) {
if (err) return err.message
//解析文件
// console.log(dataStr)
resolveCSS(dataStr)
resolveJS(dataStr)
resolveHTML(dataStr)
})
//处理css
function resolveCSS(htmlStr) {
// 3.2 使用正则提取需要的内容
const r1 = regStyle.exec(htmlStr)
// 3.3 将提取出来的样式字符串,进行字符串的 replace 替换操作
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('写入样式文件成功!')
})
}
//处理js
function resolveJS(htmlStr) {
const r2 = regScript.exec(htmlStr)
const newJs = r2[0].replace('<script>', '').replace('</script>', '')
fs.writeFile(path.join(__dirname, 'clock/index.js'), newJs, function (err) {
if (err) return err.message
console.log("写入脚本成功")
})
}
//处理html结构
function resolveHTML(htmlStr) {
const newHTML = htmlStr.replace(regStyle, '<link rel="stylesheet" href="index.css" />').replace(regScript, '<script src="index.js"></script>')
fs.writeFile(path.join(__dirname, 'clock/index.html'), newHTML,
function (err) {
if (err) return console.log('写入 HTML 文件失败!' + err.message)
console.log('写入 HTML 页面成功!')
})
}
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>
3. http模块
//导入http模块
const http = require('http')
//调用 http.createServer() 方法,即可快速创建一个 web 服务器实例
const server = http.createServer()
//为服务器实例绑定 request 事件,即可监听客户端发送过来的网络请求:
server.on('request', function (req, res) {
//req.url 是客户端请求url地址
const url = req.url
//req.method 是请求类型
const method = req.method
const str = `your request url is${url},and requset method is ${method}`
console.log(str)
//调用res.end()方法向客户端相应内容
res.end(str)
})
//启动服务器调用服务器实例的 .listen() 方法,即可启动当前的 web 服务器实例
server.listen(8080, function () {
console.log("server s at http://127.0.0.1:8080")
})
4.案例闹钟
//时钟案例
//导入http模块
const http = require('http')
//导入fs模块
const fs = require('fs')
//导入path模块
const path = require('path')
//创建web服务器
const server = http.createServer()
//监听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)
// 5.1 预定义一个空白的文件存放路径
let fpath = ''
if (url == '/') {
fpath = path.join(__dirname, './clock/index.html')
} else {
// /index.html
// /index.css
// /index.js
fpath = path.join(__dirname, '/clock', url)
}
//跟据“映射”過來的文件路徑讀取文件内容
fs.readFile(fpath, 'utf-8', (err, dataStr) => {
if (err) return res.end('404')
res.end(dataStr)
})
})
//启动服务其
server.listen(80, () => {
console.log('server running ar http://127.0.0.1')
})