fs 文件系统模块
fs 模块用来操作文件的模块。
JavaScript 中使用 fs 模块来操作文件,先引入。
const fs = require('fs')
1、fs.readFile()
使用 fs.readFile() 方法,可以读取指定文件中的内容
fs.readFile(path[, options],callback)
[ ]:可选参数
参数一:必选参数,字符串,表示文件的路径
参数二:可选参数,表示以什么编码格式来读取文件。
参数三:必选参数,文件读取完成后,通过回调函数拿到读取的结果。
const fs = require('fs')fs.readFile('./示例文件.tex','utf8',function(err,dataStr){console.log(err)console.log(dataStr)})
判读文件是否读取成功
成功:
err => null
dataStr => 读取的文本内容
失败:
err => 错误对象
dataStr => undefined
2、fs.writeFile()
使用 fs.writeFile() 方法,可以向指定的文件中写入内容。
fs.writeFile(file,data[, options],callback)
参数一:指定一个文件路径的字符串,表示文件的存放路径。
参数二:表示要写入的内容。
参数三:可选参数,表示以什么格式写入文件内容,默认值是 utf8。
参数四:文件写入完成后的回调函数。
注意:同名文件直接覆盖,没有文件会自动创建文件
const fs = require('fs')fs.writeFile('./示例文件.tex','hello ai','utf8',function(err){console.log(err)})
判断文件是否写入成功
例子:写入成绩
const fs = require('fs')fs.readFile('./cj.txt','utf8',function(err,dataStr){if(err){return console.log('读取出错' + err.message)}const arr = dataStr.split(' ')const arrNew = []arr.forEach(item =>{arrNew.push(item.replace('=',':'))})const newStr = arrNew.join('\r\n')fs.writeFile('./成绩.txt',newStr,function(err){if(err){return console.log('写入文件失败' + err.message)}console.log('成绩写入成功')})})
fs 路径动态拼接的问题
在使用 fs 模块操作文件时,如果提供操作路径以 ./ 或 ../ 开头的相对路径时,很容易出现动态路径拼接错误的问题。
原因:代码运行中,会以执行 node 命令时所处的目录,动态拼接出操作文件的完整路径
:::success
解决方案①:提供一个完整的文件存放路径,从盘符开始写。
缺点:移植性非常差、不易于维护
:::
fs.readFile('C:\\Users\\12102\\Desktop\\test\\es6\\test.js','utf8',function(err,dataStr){if(err){return console.log('读取文件失败!'+ err.message)}conosle.log('读取文件成功!' + dataStr)})
:::danger
注意:文件路径 \ 要写两个,因为一个是转义的意思。
:::
:::success
解决方案②:使用 node 提供的 dirname
dirname 表示当前文件所在的目录
:::
const fs = require('fs')console.log(__dirname)

fs.readFile(__dirname + '/test.js','utf8',function(err,dataStr){if(err){return console.log('读取文件失败!'+ err.message)}conosle.log('读取文件成功!' + dataStr)})
path 路径模块
1、path.join()
path.join()方法,可以把多个路径片段拼接为完整的路径字符串。
const path = require('path')const pathStr = path.join('/a','/b/c','../','./d','e')console.log(pathStr)const pathStr2 = path.join(__dirname,'./files/1.txt')console.log(pathStr2)
:::danger
注意:. . / 会抵消前面的路径
今后涉及到路径拼接的操作,都要使用 path.join() 方法进行处理,不要使用 + 进行字符串的拼接。
:::
2、path.basename()
path.basename(),可以获取路径中的最后一部分,经常通过这个方法获取路径中的文件名。
path.basename(path[, ext])
path
ext
返回:
const path = require('path')const fpath = '/a/b/c/index.html' //文件的存放路径var fullName = path.basename(fpath)console.log(fullName) //输出 index.htmlvar nameWithoutExt = path.basename(fpath,'.html')console.log(nameWithoutExt) //输出 index
3、path.extname()
使用 path.extname(),可以获取路径中的扩展名部分。
path.extname(path)
path
返回:
const path = require('path')const fpath = '/a/b/c/index.html'const fext = path.extname(fpath)console.log(fext) //输出 .html
案例:把一个index.html分成多个模块
const fs = require('fs')const { resolve } = require('path')const path = require('path')const regStyle = /<style>[\s\S]*<\/style>/const regScript = /<script>[\s\S]*<\/script>/// fs.readFile(path.join(__dirname,'..'))fs.readFile(path.join(__dirname, '../素材/index.html'), 'utf8', function (err, dataStr) {if (err) {return console.log('文件读取失败' + err.message)}resolveCSS(dataStr)resolveJS(dataStr)resolveHTML(dataStr)})function resolveCSS(htmlStr) {const r1 = regStyle.exec(htmlStr)// 将style变成""const newCSS = r1[0].replace('<style>', '').replace('</style>', '')fs.writeFile(path.join(__dirname,'../clock/index.css'),newCSS,function(err){console.log(path.join(__dirname,'../clock'))if(err) {console.log('写入文件错误' + err.message)}console.log('写入css文件成功')})}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脚本成功')})}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 模块
http 模块是 Node.js 官方提供的、用来创建 web 服务器的模块。通过 http 模块提供的方法(http.createServer),可以把一台普通电脑,变成一台 Web 服务器,从而对外提供 Web 资源服务。
1、创建 web 服务器
① 导入 http 模块
② 创建 web 服务器实例
③ 为服务器实例绑定 request 事件,监听客户端的请求
④ 启动服务器
①导入 http 模块
const http = require('http')
② 创建 web 服务器实例
const server = http.createServer()
③ 为服务器实例绑定 request 事件
server.on('request',(req,res) => {//只要有客户端请求我们自己服务器,就会触发 request 事件,从而调用这个事件处理函数console.log('Someone visit our web server.')})
④ 启动服务器
调用服务器实例的 .listen() 方法,可以启动当前的 web 服务器实例。
//调用 server.listen(端口号,cb回调)方法,可以启动 web 服务器server.listen(80, ()=>{console.log('http server running at http://127.0.0.1')})
const http = require('http')const server = http.createServer()server.on('request',(req,res)=>[console.log('someone visit server')])server.listen(80,function(){console.log('server running at 127.0.0.1')})
2、req 请求对象
:::danger
req 是请求对象,它包含了与客户端相关的数据和属性
req.url 是客户端请求的 URL 地址
req.method 是客户端的 method 请求类型
:::
const http = require('http')const server = http.createServer()server.on('request',(req,res)=>{console.log(req.url)console.log(req.method)})server.listen('8087',()=>{console.log('server running at localhost')})
3、res 响应对象
在服务器的 request 事件处理函数中,如果想访问与服务器相关的数据或属性,可以用如下的方法:
server.on('request',(req,res)=>{//res 是响应对象,它包含与服务器相关的数据和属性//例如:要发送到客户端的字符串const str = 'abc'//res.end:向客户端发送指定的内容,并结束这次请求的处理过程res.end(str)})
4、解决中文乱码的问题
当调用 res.end() 方法,向客户端发送中文内容的时候,会出现乱码问题,这个时候,需要手动设置内容的编码格式。
server.on('request',(req,res) => {//发送的内容包含中文const str = '请求地址为127.0.0.1'//为了防止中文显示乱码的问题,需要设置响应头 Content-Type 的值为 text/html:charset=utf-8res.setHeader('Content-Type','text/html; charset=utf-8')//把包含中文的内容,响应给客户端res.end(str)})
5、根据不同 url 响应不同的 html 内容
核心实现步骤
① 获取请求的 url 地址
② 设置默认的响应内容为 404 Not found
③ 判断用户请求的是否为 / 或 /index.html 首页
④ 判断用户请求的是否为 /about.html 关于页面
⑤设置 Content-Type 响应头,防止中文乱码
⑥ 使用 res.end( ),把内容响应给客户端
动态响应内容
server.on('request', function(req,res){const url = req.url //获取请求的 url 地址let content = '<h1>404 Not found</h1>' //设置默认内容为404 Not foundif (url === '/' || url === '/index.html'){content = '<h1>首页</h1>'} else if (url === '/about.html') {content = '<h1>关于页面</h1>' //用户请求的是关于页面}res.setHeader('Content-Type','text/html; charset=utf-8') //防止乱码res.end(content)})





