nodejs第一天

一、fs模块——读写文件

/**
 * 目标:使用 fs 模块,读写文件内容
 * 语法:
 * 1. 引入 fs 模块
 * 2. 调用 writeFile 写入内容
 * 3. 调用 readFile  读取内容
 */
// 1. 引入 fs 模块
const fs = require('fs')
// 2. 调用 writeFile 写入内容
// 注意:建议写入字符串内容,会覆盖目标文件所有内容
fs.writeFile('./text.txt', '欢迎使用 fs 模块读写文件内容', err => {
  if (err) console.log(err)
  else console.log('写入成功')
})
// 3. 调用 readFile  读取内容
fs.readFile('./text.txt', (err, data) => {
  if (err) console.log(err)
  else console.log(data.toString()) // 把 Buffer 数据流转成字符串类型
})

二、path模块——路径处理

  1. 为什么:Node.js 执行 JS 代码时,代码中的路径都是以终端所在文件夹出发查找相对路径,而不是以我们认为的从代码本身出发,会遇到问题,所以在 Node.js 要执行的代码中,访问其他文件,建议使用绝对路径
const fs = require('fs')
console.log(__dirname) // D:\备课代码\2_node_3天\Node_代码\Day01_Node.js入门\代码\03

// 1. 加载 path 模块
const path = require('path')
// 2. 使用 path.join() 来拼接路径
const pathStr = path.join(__dirname, '..', 'text.txt')
console.log(pathStr)

fs.readFile(pathStr, (err, data) => {
  if (err) console.log(err)
  else console.log(data.toString())
})

三、压缩前端html

/**
 * 目标一:压缩 html 里代码
 * 需求:把 public/index.html 里的,回车/换行符去掉,写入到 dist/index.html 中
 *  1.1 读取 public/index.html 内容
 *  1.2 使用正则替换内容字符串里的,回车符\r 换行符\n
 *  1.3 确认后,写入到 dist/index.html 内
 */
const fs = require('fs')
const path = require('path')
// 1.1 读取 public/index.html 内容
fs.readFile(path.join(__dirname, 'public', 'index.html'), (err, data) => {
  const htmlStr = data.toString()
  // 1.2 使用正则替换内容字符串里的,回车符\r 换行符\n
  const resultStr = htmlStr.replace(/[\r\n]/g, '')
  // 1.3 确认后,写入到 dist/index.html 内
  fs.writeFile(path.join(__dirname, 'dist', 'index.html'), resultStr, err => {
    if (err) console.log(err)
    else console.log('压缩成功')
  })
})

四、压缩前端js

/**
 * 目标二:压缩 js 里代码,并整合到 html 中一起运行
 *  2.1 读取 public/index.js 内容
 *  2.2 使用正则替换内容字符串里的,回车符\r 换行符\n 打印语句console.log('xxx');
 *  2.3 确认后,拼接 html 内容写入到 dist/index.html 内
 */
const fs = require('fs')
const path = require('path')
fs.readFile(path.join(__dirname, 'public', 'index.html'), (err, data) => {
  const htmlStr = data.toString()
  const resultStr = htmlStr.replace(/[\r\n]/g, '')

  // 2.1 读取 public/index.js 内容
  fs.readFile(path.join(__dirname, 'public', 'index.js'), (err, data) => {
    const jsStr = data.toString()
    // 2.2 使用正则替换内容字符串里的,回车符\r 换行符\n 打印语句console.log('xxx');
    const jsResultStr = jsStr.replace(/[\r\n]/g, '').replace(/console.log\('.+?'\);/g, '')
    const result = `<script>${jsResultStr}</script>`
    console.log(result)

    // 2.3 确认后,拼接 html 内容写入到 dist/index.html 内
    fs.writeFile(path.join(__dirname, 'dist', 'index.html'), resultStr + result, err => {
      if (err) console.log(err)
      else console.log('压缩成功')
    })
  })


})

五、http模块——创建web服务

/**
 * 目标:使用 http 模块,创建 Web 服务
 * Web服务:一个程序,用于提供网上信息浏览服务
 * 步骤:
 *  1. 引入 http 模块,创建 Web 服务对象
 *  2. 监听 request 事件,对本次请求,做一些响应处理
 *  3. 启动 Web 服务监听对应端口号
 *  4. 运行本服务在终端,用浏览器访问 http://localhost:3000/ 发起请求(localhost 是本机域名)
 * 注意:终端里启动了服务,如果想要终止按 ctrl c 停止即可
 */
// 1. 引入 http 模块,创建 Web 服务对象
const http = require('http')
const server = http.createServer()
// 2. 监听 request 事件,对本次请求,做一些响应处理
server.on('request', (req, res) => {
  res.end('hello, world') // 一次请求只能对应一次响应
})
// 3. 启动 Web 服务监听对应端口号
server.listen(3000, () => {
  console.log('Web 服务启动了')
})

六、案例——返回省市

/**
 * 目标:基于 Web 服务,开发-城市列表数据接口
 * 步骤:
 *  1. 判断 req.url 资源路径+查询字符串,路径前缀匹配/api/city
 *  2. 借助 querystring 模块的方法,格式化查询参数字符串
 *  3. 读取 city.json 城市数据,匹配省份名字下属城市列表
 *  4. 返回城市列表,启动 Web 服务测试
 */
const qs = require('querystring')
const fs = require('fs')
const path = require('path')
const http = require('http')
const server = http.createServer()
server.on('request', (req, res) => {
  // 省份列表接口
  if (req.url === '/api/province') {
    fs.readFile(path.join(__dirname, 'data/province.json'), (err, data) => {
      res.setHeader('Content-Type', 'application/json;charset=utf-8')
      res.end(data.toString())
    })
    // 1. 判断 req.url 资源路径+查询字符串,路径前缀匹配/api/city
  } else if (req.url.startsWith('/api/city')) {
    // 城市列表接口
    // 2. 借助 querystring 模块的方法,格式化查询参数字符串
    // req.url: '/api/city?pname=辽宁省'
    // 以?分隔符分割,拿到'pname=辽宁省'查询参数字符串
    const str = req.url.split('?')[1]
    // 把查询参数字符串 转成 JS 对象结构
    const query = qs.parse(str)
    // 获取前端发来的省份名字
    const pname = query.pname
    // 3. 读取 city.json 城市数据,匹配省份名字下属城市列表
    fs.readFile(path.join(__dirname, 'data/city.json'), (err, data) => {
      // 把 JSON 文件内对象格式字符串,转成对象结构
      const obj = JSON.parse(data.toString())
      // 省份名字作为 key,去obj对象里取到对应城市列表 value 值
      const cityList = obj[pname]
      // 4. 返回城市列表,启动 Web 服务测试
      // 响应的是 JSON 字符串内容
      res.setHeader('Content-Type', 'application/json;charset=utf-8')
      res.end(JSON.stringify(cityList))
    })
  } else {
    res.setHeader('Content-Type', 'text/html;charset=utf-8')
    res.end('你要访问的资源路径不存在')
  }
})
server.listen(3000, () => {
  console.log('Web 服务启动了')
})

七、案例——返回时钟网页

/**
 * 目标:编写 web 服务,监听请求的是 /index.html 路径的时候,返回 dist/index.html 时钟案例页面内容
 * 步骤:
 *  1. 基于 http 模块,创建 Web 服务
 *  2. 使用 req.url 获取请求资源路径,并读取 index.html 里字符串内容返回给请求方
 *  3. 其他路径,暂时返回不存在提示
 *  4. 运行 Web 服务,用浏览器发起请求
 */
const fs = require('fs')
const path = require('path')
// 1. 基于 http 模块,创建 Web 服务
const http = require('http')
const server = http.createServer()
server.on('request', (req, res) => {
  // 2. 使用 req.url 获取请求资源路径,并读取 index.html 里字符串内容返回给请求方
  if (req.url === '/index.html') {
    fs.readFile(path.join(__dirname, 'dist/index.html'), (err, data) => {
      res.setHeader('Content-Type', 'text/html;charset=utf-8')
      res.end(data.toString())
    })
  } else {
    // 3. 其他路径,暂时返回不存在提示
    res.setHeader('Content-Type', 'text/html;charset=utf-8')
    res.end('你要访问的资源路径不存在')
  }
})
server.listen(8080, () => {
  console.log('Web 服务启动了')
})
posted @ 2025-08-01 06:31  技术蓝鱼  阅读(10)  评论(0)    收藏  举报