Nodejs学习第一天:fs模块,path模块,压缩前端代码

108 阅读2分钟

一、fs 模块 - 读写文件

模块:类似插件,封装了方法/属性 fs 模块:封装了与本机文件系统进行交互的,方法/属性 语法:

  1. 加载 fs 模块对象
  2. 写入文件内容
  3. 读取文件内容

案例:

 * 目标:基于 fs 模块读写文件内容
 *  1. 加载 fs 模块对象
 *  2. 写入文件内容
 *  3. 读取文件内容
 */
// 1. 加载 fs 模块对象
const fs = require('fs')
// 2. 写入文件内容
fs.writeFile('./test.txt', 'hello, Node.js', (err) => {
  if (err) console.log(err)
  else console.log('写入成功')
})
// 3. 读取文件内容
fs.readFile('./test.txt', (err, data) => {
  if (err) console.log(err)
  // data 是 buffer 16 进制数据流对象
  // .toString() 转换成字符串
  else console.log(data.toString())
})

运行结果:

02.js.png

二、path模块-路径处理

建议:在 Node.js 代码中,使用绝对路径 建议:在 Node.js 代码中,使用绝对路径 补充:__dirname 内置变量(获取当前模块目录-绝对路径)

windows: D:\备课代码\3-B站课程\03_Node.js与Webpack\03-code\03

mac: /Users/xxx/Desktop/备课代码/3-B站课程/03_Node.js与Webpack/03-code/03

注意:path.join() 会使用特定于平台的分隔符,作为定界符,将所有给定的路径片段连接在一起

语法: 加载 path 模块,使用 path.join 方法,拼接路径

案例:

目标:在 Node.js 环境的代码中,应使用绝对路径
原因:代码的相对路径是以终端所在文件夹为起点,而不是 Vscode 资源管理器
容易造成目标文件找不到的错误
const fs = require('fs')
// 1. 引入 path 模块对象
const path = require('path')
// 2. 调用 path.join() 配合 __dirname 组成目标文件的绝对路径
console.log(__dirname)
fs.readFile(path.join(__dirname, '../test.txt'), (err, data) => {
  if (err) console.log(err)
  else console.log(data.toString())
})

运行结果:

03.js.png

三、压缩前端代码

案例 - 压缩前端 html 需求:把 回车符(\r)和换行符(\n)去掉后,写入到新 html 文件中 步骤:

  1. 读取源 html 文件内容
  2. 正则替换字符串
  3. 写入到新的 html 文件中
const fs = require('fs')
const path = require('path')
fs.readFile(path.join(__dirname, 'public/index.html'), (err, data) => {
  if (err) console.log(err)
  else {
    const htmlStr = data.toString()
    // 1.2 正则替换字符串
    const resultStr = htmlStr.replace(/[\r\n]/g, '')
    console.log(resultStr)
    // 1.3 写入到新的 html 文件中
    fs.writeFile(path.join(__dirname, 'dist/index.html'), resultStr, err => {
      if (err) console.log(err)
      else console.log('写入成功')
    })
  }
})

运行结果:

04.js.png

04.js1.png