fs 文件系统模块

fs 模块用来操作文件的模块。
JavaScript 中使用 fs 模块来操作文件,先引入。

  1. const fs = require('fs')

1、fs.readFile()

使用 fs.readFile() 方法,可以读取指定文件中的内容

  1. fs.readFile(path[, options],callback)

[ ]:可选参数
参数一:必选参数,字符串,表示文件的路径
参数二:可选参数,表示以什么编码格式来读取文件。
参数三:必选参数,文件读取完成后,通过回调函数拿到读取的结果。

  1. const fs = require('fs')
  2. fs.readFile('./示例文件.tex','utf8',function(err,dataStr){
  3. console.log(err)
  4. console.log(dataStr)
  5. })

image.png
image.png

判读文件是否读取成功

成功:
err => null
dataStr => 读取的文本内容
失败:
err => 错误对象
dataStr => undefined

2、fs.writeFile()

使用 fs.writeFile() 方法,可以向指定的文件中写入内容。

  1. fs.writeFile(file,data[, options],callback)

参数一:指定一个文件路径的字符串,表示文件的存放路径。
参数二:表示要写入的内容。
参数三:可选参数,表示以什么格式写入文件内容,默认值是 utf8。
参数四:文件写入完成后的回调函数。

注意:同名文件直接覆盖,没有文件会自动创建文件

  1. const fs = require('fs')
  2. fs.writeFile('./示例文件.tex','hello ai','utf8',function(err){
  3. console.log(err)
  4. })

image.png

image.png

判断文件是否写入成功

成功:
err => null
失败:
err => 错误对象

例子:写入成绩

  1. const fs = require('fs')
  2. fs.readFile('./cj.txt','utf8',function(err,dataStr){
  3. if(err){
  4. return console.log('读取出错' + err.message)
  5. }
  6. const arr = dataStr.split(' ')
  7. const arrNew = []
  8. arr.forEach(item =>{
  9. arrNew.push(item.replace('=',':'))
  10. })
  11. const newStr = arrNew.join('\r\n')
  12. fs.writeFile('./成绩.txt',newStr,function(err){
  13. if(err){
  14. return console.log('写入文件失败' + err.message)
  15. }
  16. console.log('成绩写入成功')
  17. })
  18. })

image.png
image.png

fs 路径动态拼接的问题

在使用 fs 模块操作文件时,如果提供操作路径以 ./ 或 ../ 开头的相对路径时,很容易出现动态路径拼接错误的问题。

原因:代码运行中,会以执行 node 命令时所处的目录,动态拼接出操作文件的完整路径

:::success 解决方案①:提供一个完整的文件存放路径,从盘符开始写。
缺点:移植性非常差、不易于维护 :::

  1. fs.readFile('C:\\Users\\12102\\Desktop\\test\\es6\\test.js','utf8',
  2. function(err,dataStr){
  3. if(err){
  4. return console.log('读取文件失败!'+ err.message)
  5. }
  6. conosle.log('读取文件成功!' + dataStr)
  7. })

:::danger 注意:文件路径 \ 要写两个,因为一个是转义的意思。 ::: :::success 解决方案②:使用 node 提供的 dirname
dirname 表示当前文件所在的目录 :::

  1. const fs = require('fs')
  2. console.log(__dirname)

image.png

  1. fs.readFile(__dirname + '/test.js','utf8',function(err,dataStr){
  2. if(err){
  3. return console.log('读取文件失败!'+ err.message)
  4. }
  5. conosle.log('读取文件成功!' + dataStr)
  6. })

path 路径模块

path 模块用来处理路径的模块。

1、path.join()

path.join()方法,可以把多个路径片段拼接为完整的路径字符串。

  1. const path = require('path')
  2. const pathStr = path.join('/a','/b/c','../','./d','e')
  3. console.log(pathStr)
  4. const pathStr2 = path.join(__dirname,'./files/1.txt')
  5. console.log(pathStr2)

image.png :::danger 注意:. . / 会抵消前面的路径
今后涉及到路径拼接的操作,都要使用 path.join() 方法进行处理,不要使用 + 进行字符串的拼接。 :::

2、path.basename()

path.basename(),可以获取路径中的最后一部分,经常通过这个方法获取路径中的文件名。

  1. path.basename(path[, ext])

path:必选参数,表示一个路径的字符串
ext:可选参数,表示文件扩展名
返回: 表示路径中的最后一部分

  1. const path = require('path')
  2. const fpath = '/a/b/c/index.html' //文件的存放路径
  3. var fullName = path.basename(fpath)
  4. console.log(fullName) //输出 index.html
  5. var nameWithoutExt = path.basename(fpath,'.html')
  6. console.log(nameWithoutExt) //输出 index

3、path.extname()

使用 path.extname(),可以获取路径中的扩展名部分。

  1. path.extname(path)

path必选参数,表示一个路径的字符串
返回: 返回得到的扩展名字符串

  1. const path = require('path')
  2. const fpath = '/a/b/c/index.html'
  3. const fext = path.extname(fpath)
  4. console.log(fext) //输出 .html

案例:把一个index.html分成多个模块

  1. const fs = require('fs')
  2. const { resolve } = require('path')
  3. const path = require('path')
  4. const regStyle = /<style>[\s\S]*<\/style>/
  5. const regScript = /<script>[\s\S]*<\/script>/
  6. // fs.readFile(path.join(__dirname,'..'))
  7. fs.readFile(path.join(__dirname, '../素材/index.html'), 'utf8', function (err, dataStr) {
  8. if (err) {
  9. return console.log('文件读取失败' + err.message)
  10. }
  11. resolveCSS(dataStr)
  12. resolveJS(dataStr)
  13. resolveHTML(dataStr)
  14. })
  15. function resolveCSS(htmlStr) {
  16. const r1 = regStyle.exec(htmlStr)
  17. // 将style变成""
  18. const newCSS = r1[0].replace('<style>', '').replace('</style>', '')
  19. fs.writeFile(path.join(__dirname,'../clock/index.css'),newCSS,function(err){
  20. console.log(path.join(__dirname,'../clock'))
  21. if(err) {
  22. console.log('写入文件错误' + err.message)
  23. }
  24. console.log('写入css文件成功')
  25. })
  26. }
  27. function resolveJS(htmlStr){
  28. const r2 = regScript.exec(htmlStr)
  29. const newJS = r2[0].replace('<script>','').replace('</script>','')
  30. fs.writeFile(path.join(__dirname,'../clock/index.js'),newJS, err =>{
  31. if(err){
  32. return console.log('写入js文件失败'+ err.message)
  33. }
  34. console.log('写入js脚本成功')
  35. })
  36. }
  37. function resolveHTML(htmlStr){
  38. const newHTML = htmlStr.replace(regStyle,'<link rel="stylesheet" href="./index.css" />').replace(regScript,'<script src="./index.js"></script>')
  39. fs.writeFile(path.join(__dirname,'../clock/index.html'),newHTML, err =>{
  40. if(err){
  41. return console.log('写入HTML文件失败' + err.message)
  42. }
  43. console.log('写入HTML页面成功')
  44. })
  45. }

http 模块

http 模块是 Node.js 官方提供的、用来创建 web 服务器的模块。通过 http 模块提供的方法(http.createServer),可以把一台普通电脑,变成一台 Web 服务器,从而对外提供 Web 资源服务。

1、创建 web 服务器

① 导入 http 模块
② 创建 web 服务器实例
③ 为服务器实例绑定 request 事件,监听客户端的请求
④ 启动服务器


①导入 http 模块

  1. const http = require('http')

② 创建 web 服务器实例

  1. const server = http.createServer()

③ 为服务器实例绑定 request 事件

  1. server.on('request',(req,res) => {
  2. //只要有客户端请求我们自己服务器,就会触发 request 事件,从而调用这个事件处理函数
  3. console.log('Someone visit our web server.')
  4. })

④ 启动服务器
调用服务器实例的 .listen() 方法,可以启动当前的 web 服务器实例。

  1. //调用 server.listen(端口号,cb回调)方法,可以启动 web 服务器
  2. server.listen(80, ()=>{
  3. console.log('http server running at http://127.0.0.1')
  4. })
  1. const http = require('http')
  2. const server = http.createServer()
  3. server.on('request',(req,res)=>[
  4. console.log('someone visit server')
  5. ])
  6. server.listen(80,function(){
  7. console.log('server running at 127.0.0.1')
  8. })

image.png
运行结果:
image.png

2、req 请求对象

:::danger req 是请求对象,它包含了与客户端相关的数据和属性
req.url 是客户端请求的 URL 地址
req.method 是客户端的 method 请求类型 :::

  1. const http = require('http')
  2. const server = http.createServer()
  3. server.on('request',(req,res)=>{
  4. console.log(req.url)
  5. console.log(req.method)
  6. })
  7. server.listen('8087',()=>{
  8. console.log('server running at localhost')
  9. })

image.png
运行结果:
image.png

3、res 响应对象

在服务器的 request 事件处理函数中,如果想访问与服务器相关的数据或属性,可以用如下的方法:

  1. server.on('request',(req,res)=>{
  2. //res 是响应对象,它包含与服务器相关的数据和属性
  3. //例如:要发送到客户端的字符串
  4. const str = 'abc'
  5. //res.end:向客户端发送指定的内容,并结束这次请求的处理过程
  6. res.end(str)
  7. })

image.png

4、解决中文乱码的问题

当调用 res.end() 方法,向客户端发送中文内容的时候,会出现乱码问题,这个时候,需要手动设置内容的编码格式。
image.png

  1. server.on('request',(req,res) => {
  2. //发送的内容包含中文
  3. const str = '请求地址为127.0.0.1'
  4. //为了防止中文显示乱码的问题,需要设置响应头 Content-Type 的值为 text/html:charset=utf-8
  5. res.setHeader('Content-Type','text/html; charset=utf-8')
  6. //把包含中文的内容,响应给客户端
  7. res.end(str)
  8. })

image.png

5、根据不同 url 响应不同的 html 内容

核心实现步骤

① 获取请求的 url 地址
② 设置默认的响应内容为 404 Not found
③ 判断用户请求的是否为 / 或 /index.html 首页
④ 判断用户请求的是否为 /about.html 关于页面
⑤设置 Content-Type 响应头,防止中文乱码
⑥ 使用 res.end( ),把内容响应给客户端

动态响应内容

  1. server.on('request', function(req,res){
  2. const url = req.url //获取请求的 url 地址
  3. let content = '<h1>404 Not found</h1>' //设置默认内容为404 Not found
  4. if (url === '/' || url === '/index.html'){
  5. content = '<h1>首页</h1>'
  6. } else if (url === '/about.html') {
  7. content = '<h1>关于页面</h1>' //用户请求的是关于页面
  8. }
  9. res.setHeader('Content-Type','text/html; charset=utf-8') //防止乱码
  10. res.end(content)
  11. })