本章知识点
fs文件系统模块
先导入
const fs = require('fs)
fs.readFile()
方法:用来读取指定文件中的内容
// 语法:fs.readFile(path [,options] ,callback )
onst fs = require('fs')
fs.readFile('./file/123.txt','utf8',function(err,result){
// 判断文件是否读取成功 err = null成功
if(err){
return console.log('文件读取失败',err.message)
}
console.log('文件读取成功' + result)
})
fs.writeFile()
方法:用来向指定的文件中写入内容
// 语法:fs.writeFile(file,data[,option],callback)
const fs = require('fs')
fs.writeFile('./file/2.txt','hello node.js',function(err){
// 判断文件是否写入成功 err=null成功
if(err){
return console.log("文件写入失败" + err.message);
}
console.log("文件写入成功")
})
fs案例 - 考试成绩整理
核心实现步骤:
- 导入需要的fs文件系统模块
- 使用
fs.readFile()
方法,读取素材目录下的成绩txt
文件 - 判断文件是否读取失败
- 文件读取成功后,处理成绩数据
- 将处理完的成绩数据,调用
fs.writeFile()
方法,写入到新文件成绩-ok.txt
中
//【1】导入需要的 fs 文件系统模块
const fs = require('fs')
//【2】使用 fs.readFile() 方法,读取素材目录下的 成绩.txt 文件
fs.readFile('./file/成绩.txt','utf8',function(err,dataStr){
//【3】判断文件是否读取失败
if(err){
return console.log("读取文件失败",err.message)
}
//【4】文件读取成功后,处理成绩数据
// 4.1对数据用空格进行分割
const arrOld = dataStr.split(' ')
// 4.2循环分割后的数据,进行字符串的替换
const arrNew = []
arrOld.forEach(item => {
arrNew.push(item.replace('=',":"))
})
// 4.3把新数组的每一项进行合并,形成一个新数组
const newStr = arrNew.join('\r\n')
//【5】将处理完成的成绩数据,调用 fs.writeFile() 方法,写入到新文件成绩-ok.txt 中
fs.writeFile('./file/成绩-ok.txt', newStr ,function(err){
if(err){
return console.log("写入文件失败" + err.message)
}
console.log("写入文件成功")
})
})
path路径模块
先导入
const path = require('path')
path.join()
方法:用来将多个路径拼接成一个完整的路径字符串
// path.join([...paths])
const pathStr = path.join('/a','/b/c','../','./d','e')
console.log(pathStr) // \a\b\d\e
path.basename()
方法:用来从路径字符串中,将文件名解析出来
// path.basename(path[,ext])
const fpath = '/a/b/c/index.html'
const fullName = path.basename(fpath)
console.log(fullName) //index.html
path.extname()
方法:可以获取路径中的扩展名部分
// path.extname(path)
const path1 = '/a/b/c/index.html'
const path2 = path.extname(path1)
console.log(path2) //.html
path案例-时钟案例
实现步骤:
- 创建两个正则表达式,分别用来匹配 和 标签
- 使用 fs 模块,读取需要被处理的 HTML 文件
- 自定义 resolveCSS 方法,写入index.css文件
- 自定义 resolveJS 方法,写入index.js文件
- 自定义 resolveHTML 方法,写入index.html文件
// 【目的:index.html拆分成三个文件】
const fs = require('fs')
const path = require('path')
//【1】创建两个正则表达式,分别用来匹配 <style> 和 <script> 标签
const regStyle = /<style>[\s\S]*<\/style>/
const regScript = /<script>[\s\S]*<\/script>/
//【2】使用 fs 模块,读取需要被处理的 HTML 文件
fs.readFile(path.join(__dirname,'./index.html'),'utf8',(err,dataStr)=>{
// 判断读取成功还是失败
if(err) return console.log("读取HTML文件失败" + err.message)
// 读取成功后,调用相应的方法
resolveCSS(dataStr)
resolveJS(dataStr)
resolveHTML(dataStr)
})
//【3】自定义 resolveCSS 方法
function resolveCSS(htmlStr){
// 3.1 使用正则提取页面中的<style></style>标签
const r1 = regStyle.exec(htmlStr)
// 3.2 对提取出来的样式字符串,需做进一步的处理
const newCSS = r1[0].replace('<style>', '').replace('</style>', '')
// 3.3 将提取出来的CSS样式,写入到index.css文件中
fs.writeFile(path.join(__dirname,'./案例clock/index.css'),newCSS,err => {
if(err) return console.log("写入CSS样式失败" + err.message)
console.log('写入CSS样式成功')
})
}
// 【4】自定义 resolveJS 方法
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,err => {
if(err) return console.log("写入JS样式失败" + err.message)
console.log("写入JS文件成功")
})
}
// 【5】自定义 resolveHTML 方法
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,err => {
if(err) return console.log("写入HTML文件失败" + err.message)
console.log("写入HTML页面成功")
})
}
http模块
先导入
const http = require('http')
创建web服务器的基本步骤
//【1】导入 http 模块
const http = require('http')
//【2】调用 http.createServer(),创建 web 服务器实例
const server = http.createServer()
//【3】为服务器实例绑定 request 事件
server.on('request',(req,res) => {
// 只要有客户端来请求服务器,就会触发request,从而调用这个事件处理函数
console.log('Someone visit our web server')
})
//【4】启动服务器
server.listen(8080,() => {
console.log('server running at http://127.0.0.1:8080')
})
根据不同的URL显示不同的页面:
- 获取请求的 url 地址
- 设置默认的响应内容为 404 Not found
- 判断用户请求的是否为 / 或 /index.html 首页
- 判断用户请求的是否为 /about.html 关于页面
- 设置 Content-Type 响应头,防止中文乱码
- 使用 res.end() 把内容响应给客户端
const http = require('http')
const server =http.createServer()
server.on('request',(req,res)=>{
// 获取请求的 url 地址
const url = req.url
// 设置默认的响应内容为 404 Not found
let content = '<h1>404 Not found</h1>'
// 判断用户请求的是否为 / 或 /index.html 首页
if(url ==='/' || url === '/index.html'){
content = '<h1>首页</h1>'
}else if(url === '/about.html'){ // 判断用户请求的是否为 /about.html 关于页面
content = '<h1>关于页面</h1>'
}
// 设置 Content-Type 响应头,防止中文乱码
res.setHeader('Content-Type','text/html;charset=utf-8')
// 使用 res.end() 把内容响应给客户端
res.end(content)
})
server.listen(80,()=>{
console.log('server listen at http://127.0.0.1')
})
path案例-时钟
//【1】导入需要的模块
const http = require('http')
const fs = require('fs')
const path = require('path')
const server = http.createServer()
//【2】创建基本的 web 服务器
server.on('request',(req,res)=>{
//【3】将资源的请求 url 地址映射为文件的存放路径
const url = req.url
//【5】优化资源的请求路径
let fpath =''
if(url === '/'){
fpath = path.join(__dirname,'./clock/index.html')
}else {
fpath = path.join(__dirname,'./clock',url)
}
// const fpath = path.join(__dirname,url)
//【4】读取文件内容并响应给客户端
fs.readFile(fpath,'utf8',(err,dataStr)=>{
if(err) return res.end('404 Not found')
res.end(dataStr)
})
})
//【5】优化资源的请求路径
server.listen(80,()=>{
console.log('server listen at http://127.0.0.1')
})