fs 读取文件模块

let oldtext = ''

// 读取
fs.readFile(__dirname + '/input.txt', 'utf-8', (err, text) => {
  if(err) { return console.log(err) }

  oldtext = text
  console.log(text)
})

// 写
fs.writeFile(__dirname + '/input.txt', oldtext + '\r\nconsole.log("hello world!")', (err, text) => {
  if(err) { return console.log(err) }

  console.log(text)
})

__dirname :代表当前js文件所在目录的路径(绝对路径)(也就是当前js的上一级目录), 如果直接用相对路径 './input.txt', 如果在不同级文件运行命令则会报错,所以要用绝对路径或这种拼接。
__filename: 代表当前js文件的路径(绝对路径)

path 路径模块

path.join() 拼接成路径 './' '/' '../'自动整合

path.join(__dirname, 'input.txt')

path.basename

获取路径最后一部分 文件名+后缀

path.basename('E:/web/node/uploadServer/input.txt') // input.txt
path.basename('E:/web/node/uploadServer/input.txt', '.txt') // input

path.extname

获取后缀

path.extname('E:/web/node/uploadServer/input.txt') // .txt

小作业

input.txt 小红=99 六=55 阿斯顿=12 问我=33 后端=12 转换成

const fs = require('fs')
const path = require('path')

let handleText = ''

fs.readFile(path.join(__dirname, 'input.txt'), 'utf-8', (err, text) => {
  if(err) { return console.log(err) }


  handleText = text.split(' ').map(item => item.replace(/=/, ':')).join('\r\n')

  fs.writeFile(path.join(__dirname, 'input.txt'), handleText, (err, text) => {
    if(err) { return console.log(err) }

    console.log(text)
  })
})

小作业2

将html文件种的 html js css 分离 出来
html chatRoom.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>聊天室</title>
  <style>
    li{
      list-style: none;
    }
  </style>
</head>
<body>
  <h3>聊天室</h3>
  <p>当前在线人数:<span class="total">0</span></p>
  <ul></ul>
  <input type="text" placeholder="请输入发送信息">
  <button>发送</button>

  <script>
    const btn = document.querySelector('button')
    const input = document.querySelector('input')
    const ul = document.querySelector('ul')
    const totalDom = document.querySelector('.total')
    const ws = new WebSocket('ws://localhost:8000')
    let userName = ''
    let total = 0

    btn.addEventListener('click', sendMsg, false)
    ws.addEventListener('open', () => {
      console.log('前端:连接成功')
      userName = location.href.split('?')[1].split('=')[1]
      ws.send(JSON.stringify({ text: userName + '进入了聊天室'}))
    })
    ws.addEventListener('message', getMsg, false)
    ws.addEventListener('error', () => {console.warn('前端:连接失败')})
    ws.addEventListener('close', () => {console.warn('前端:断开连接')})

    function sendMsg() {
      userName = location.href.split('?')[1].split('=')[1]
      ws.send(JSON.stringify({ name: userName, time: new Date(), text: input.value}))
    }

    function getMsg(e) {
      console.log('前端:获取聊天消息成功:' + e.data)
      const msg = JSON.parse(e.data)
      const li = document.createElement('li')

      totalDom.textContent = msg.total

      li.innerHTML = `
        <span><strong>${msg.name || ''}</strong><span> <span>${msg.time || ''}</span>
        <br/>
        <span>${msg.text}</span>
      `

      ul.appendChild(li)
    }
  </script>
</body>
</html>

node index.js

const fs = require('fs')
const path = require('path')

// 读取html文件
fs.readFile(path.join(__dirname, 'public/chatRoom.html'), 'utf-8', (err, text) => {
  if (err) { return console.log(err) }

  const regGetScript = /<script>([\s\S]*)<\/script>/
  const regGetStyle = /<style>([\s\S]*)<\/style>/
  let js = regGetScript.exec(text)[1].replace(/(\s){2,10000}/g, ';') // 匹配两个空格以上的转为;
  const exString = /`(.*)`/g.exec(js)[0].replace(/;/g, '') // 将模板字符串里的;去除
  const style = regGetStyle.exec(text)[1].replace(/\s/g, '')
  const html = text.replace(/(\s){2,}|(<script>[\s\S]*<\/script>)|(<style>[\s\S]*<\/style>)/g, '') // 去掉空格

  js = js.replace(/`.*`/g, exString)
  // 创建 dist 文件
  fs.mkdir(path.join(__dirname, './dist'), {
    recursive: true
  }, (err) => {
    if (err) { return console.log(err) }

    fs.writeFile(path.join(__dirname, 'dist/index.js'), js, (err, text) => {
      if (err) {  console.log(err) }
      console.log(text)
    })

    fs.writeFile(path.join(__dirname, 'dist/index.css'), style, (err, text) => {
      if (err) { return console.log(err) }
      console.log(text)
    })

    fs.writeFile(path.join(__dirname, 'dist/index.html'), html, (err, text) => {
      if (err) { return console.log(err) }
      console.log(text)
    })
  })
})

最后打包结果

posted on 2023-08-02 15:03  京鸿一瞥  阅读(25)  评论(0编辑  收藏  举报