nodejs-fs文件读写功能

352 阅读1分钟

一、功能简介

一个简单的index.html页面,含有内联样式和js,使用fs功能将内联样式和js脚本替换成外部引用的方式。

二、文件结构

image.png

三、原始index.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>Document</title>
  <style>
    .wrap {
      width: 200px;
      height: 100px;
      display: flex;
      justify-content: center;
      align-items: center;
      background: pink;
    }

    h1 {
      font-size: 18px;
      font-weight: normal;
      color: #fff;
    }

    h1:hover {
      cursor: pointer;
    }
  </style>
</head>

<body>
  <div class="wrap">
    <h1 id="sayHello">你好</h1>
  </div>
  <script>
    window.onload = function () {
      const dom = document.getElementById("sayHello")
      dom.onclick = function () {
        dom.innerHTML = "你好,程序媛!"
        dom.style.color = 'black'
      }
    }
  </script>
</body>

</html>

四、读写处理文件的方法changeReference.js

//把index.html文件中的css和js文件使用外链的方式加载
const fs = require("fs")
const path = require("path")
//匹配样式style和script标签中的内容,\s\S为所有空白和非空白内容
const regStyle = /<style>[\s\S]*<\/style>/
const regScript = /<script>[\s\S]*<\/script>/

//读取index.html文件内容
fs.readFile(path.join(__dirname, 'index.html'), 'utf-8', (err, dataStr) => {
  //无错误
  if (err == null) {
    resolveCss(dataStr)
    resolveScript(dataStr)
    resolveHtml(dataStr)
  } else {
    console.log('读取文件失败' + err.message)
  }
})

//将css内容替换为外链形式
function resolveCss(htmlStr) {
  //使用正则表达式提取需要的内容
  const r1 = regStyle.exec(htmlStr)
  // 将<style></style>标签去掉
  const newCss = r1[0].replace('<style>', '').replace('</style>', '')
  //把css样式写入index.css文件中
  fs.writeFile(path.join(__dirname, './sayHello/index.css'), newCss, 'utf-8', err => {
    if (err) {
      return console.log('写入文件失败' + err.message)
    }
  })
}

//将js内容替换为外链形式
function resolveScript(htmlStr) {
  //使用正则表达式提取需要的内容
  const r2 = regScript.exec(htmlStr)
  // 将<style></style>标签去掉
  const newCss = r2[0].replace('<script>', '').replace('</script>', '')
  //把css样式写入index.css文件中
  fs.writeFile(path.join(__dirname, './sayHello/index.js'), newCss, 'utf-8', err => {
    if (err) {
      return console.log('写入文件失败' + err.message)
    }
  })
}

//处理html
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, "./sayHello/index.html"), newHtml, err => {
    if (err) {
      return console.log('写入文件失败' + err.message)
    }
  })
}

五、最终效果

执行node ./changeReference.js,sayHello文件夹下生成三个文件

  • sayHello/index.html image.png
  • sayHello/index.js image.png
  • sayHello/index.css image.png

六、知识点回顾

  1. fs.readFile(path,encode,callback[err,dataStr])
//读取文件
 fs.readFile('文件路径','编码格式',(err,dataStr)=>{
     if(err){
         console.log('读取文件错误',err.message)
     }else{
         //处理读取的文件字符串
     }
 })
  1. fs.writeFile(path,dataStr,callback[err])
//写入文件
fs.writeFile('文件路径','文件内容',err=>{
    if(err){
        console.log('读取文件错误',err.message)
    }else{
         //处理读取的文件字符串
     }
})
  1. path.join(path1,path2,....)
//拼接路径,__dirname为当前目录
path.join(__dirname,'index.html')
  1. path.basename(path,suffix)
//获取路径中的文件名 ,suffix可选填,为后缀名,
//若suffix传'js',得到的结果将为index
//若suffix不传,得到的结果将为index.js
path.basename('./clock/index.js',suffix)
  1. path.extname(path)
//获取文件扩展名 
path.extname('./clock/index.js')