node.js fs 文件模块 学习笔记 二

原创 maolego 2022年10月31日 150 0

案例 :

 读取 demo.html 页面内容,将内容拆分成 3个文件,
    分别是:
    index.html
    index.css
    index.js
 并且将拆分出来的这3个文件,存放到 files 目录中
目录结构:
demo2
  |- demo.js    # 代码文件 
  |- demo.html  # 案列文件

 

demo.html 页面预览:

demo.html  案列 :
<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> 
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>电子时钟特效</title>

<style>
* {
    margin: 0;
    padding: 0;
}

body {
    color: #ffffff;
    background-color: #000000;
    
}

main {
    text-align: center;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%,-50%);
    padding: 15px;
    border: solid 5px #ffffff;
    font-family: 'digital-7', sans-serif;
}


/* DAYS OF THE WEEK */
div.days {
    margin: 0 auto;
    color: #131212;
}

div.days .day {
    display: inline-block;
}

div.days .day p {
    font-size: 12px;
    font-weight: bold;
    font-family: sans-serif;
    text-transform: uppercase;
}


/* CLOCK */
div.clock {
    margin: 5px 0;
}

div.clock div{
    display: inline-block;
    position: relative;
}

div.clock div p{
    font-size: 100px;
    position: relative;
    z-index: 100;
}

div.clock .placeholder {
    color: #131212;
    position: absolute;
    top: 0;
    z-index: 50;
}/*END CLOCK*/


/* AM OR PM*/
.am-pm {
    font-family: sans-serif;
    text-transform: uppercase;
    width: 20px;
}

div.am-pm div p {
    font-size: 12px;
    font-weight: bold;
    width: 100%;
}

.am, .pm {
    color: #131212;
}

.light-on {
    color: #ffffff;
}
</style>
</head>
<body>
    <div class="htmleaf-container">
        <main>
            <!-- DAY OF THE WEEK -->
            <div class="days">
            
                <div class="day">
                    <p class="sunday">星期日</p>
                </div>

                <div class="day">
                    <p class="monday">星期一</p>
                </div>

                <div class="day">
                    <p class="tuesday">星期二</p>
                </div>

                <div class="day">
                    <p class="wednesday">星期三</p>
                </div>

                <div class="day">
                    <p class="thursday">星期四</p>
                </div>

                <div class="day">
                    <p class="friday">星期五</p>
                </div>

                <div class="day">
                    <p class="saturday">星期六</p>
                </div>

            </div>
            <!-- CLOCK -->
            <div class="clock">
                <!-- HOUR -->
                <div class="numbers">
                    <p class="hours"></p>
                    <p class="placeholder">88</p>
                </div>

                <div class="colon">
                    <p>:</p>
                </div>

                <!-- MINUTE -->
                <div class="numbers">
                    <p class="minutes"></p>
                    <p class="placeholder">88</p>
                </div>

                <div class="colon">
                    <p>:</p>
                </div>

                <!-- SECOND -->
                <div class="numbers">
                    <p class="seconds"></p>
                    <p class="placeholder">88</p>
                </div>
                
                <!-- AM / PM -->
                <div class="am-pm">

                    <!-- AM -->
                    <div>
                        <p class="am">am</p>
                    </div>

                    <!-- PM -->
                    <div>
                        <p class="pm">pm</p>
                    </div>
                </div>

            </div><!-- END CLOCK -->

        </main>
    </div>
    
    <script>
        //invokes functions as soon as window loads
        window.onload = function(){
            time();
            ampm();
            whatDay();
            setInterval(function(){
                time();
                ampm();
                whatDay();
            }, 1000);
        };


        //gets current time and changes html to reflect it
        function time(){
            var date = new Date(),
                hours = date.getHours(),
                minutes = date.getMinutes(),
                seconds = date.getSeconds();

            //make clock a 12 hour clock instead of 24 hour clock
            hours = (hours > 12) ? (hours - 12) : hours;
            hours = (hours === 0) ? 12 : hours;

            //invokes function to make sure number has at least two digits
            hours = addZero(hours);
            minutes = addZero(minutes);
            seconds = addZero(seconds);

            //changes the html to match results
            document.getElementsByClassName('hours')[0].innerHTML = hours;
            document.getElementsByClassName('minutes')[0].innerHTML = minutes;
            document.getElementsByClassName('seconds')[0].innerHTML = seconds;
        }

        //turns single digit numbers to two digit numbers by placing a zero in front
        function addZero (val){
            return (val <= 9) ? ("0" + val) : val;
        }

        //lights up either am or pm on clock
        function ampm(){
            var date = new Date(),
                hours = date.getHours(),
                am = document.getElementsByClassName("am")[0].classList,
                pm = document.getElementsByClassName("pm")[0].classList;
            
                
            (hours >= 12) ? pm.add("light-on") : am.add("light-on");
            (hours >= 12) ? am.remove("light-on") : pm.remove("light-on");
        }

        //lights up what day of the week it is
        function whatDay(){
            var date = new Date(),
                currentDay = date.getDay(),
                days = document.getElementsByClassName("day");

            //iterates through all divs with a class of "day"
            for (x in days){
                //list of classes in current div
                var classArr = days[x].classList;

                (classArr !== undefined) && ((x == currentDay) ? classArr.add("light-on") : classArr.remove("light-on"));
            }
        }
    </script>

</body>
</html>

 

代码:

demo.js

/ 引入  path 模块
const path = require('path');
// 引入  fs 模块
const fs = require("fs");


/**
 *  匹配 style script 标签
 *   其中 \s 表示空白字符 \S非空白字符
 */
// style
let style = /<style>[\s\S]*<\/style>/;
// script
let script = /<script>[\s\S]*<\/script>/;
/**
 * 文件路径 
 */
let filename = path.join(__dirname,"demo.html");

/**
 * 判断 files 目录是否存在,如果不存在创建
 *  */ 
if(!fs.existsSync(path.join(__dirname,"files"))){
   let dir =  fs.mkdirSync(path.join(__dirname,"files"));
}


// // 读取文件
fs.readFile(filename,"utf-8",(err,data)=>{
    if(err){
        return console.error("读取文件失败");
    }

    /** 
     *  style.exec(data) 通过正则 ,提取内容CSS
     */
    writeData(style.exec(data),"style","index.css");
   /** 
     *  script.exec(data) 通过正则 ,提取内容Script
     */
    writeData(script.exec(data),"script","index.js");
    // 写入 index.html
    writeHtml(data);

});
/** 
 * 写入内容 CSS 和 script
 *
 *  resReg       正则表达式
 *  setReplace   替换标签 <style></style> <script></script>
 *  fileName    写入文件名 index.css index.js
*/
function writeData(resReg,setReplace="",fileName=""){

  /**
   *  将提取的内容 ,进行字符串 replace 的 替换操作
   */
   let newsData = resReg[0].replace("<"+setReplace+">","").replace("</"+setReplace+">","");
   
   /**
    * 写入文件操作
    *  将在 files目录下 生成 index.css index.js
    * */ 
    fs.writeFile(path.join(__dirname,"files",fileName),newsData ,(err)=>{
        if(err){
            return console.error(fileName+" 文件内容写入失败");
        }
        console.log("fileName文件内容写入成功");
    })
}
/**
 * 写入 index.html 页面
 * @param {*} data 内容
 */
function writeHtml(data){
    /**
     *  将提取的内容 使用 字符串replace方法 ,将 <style> 和 <script>标签,替换成 外链的 link 和 script 
     */
   let html = data.replace(style,'<link rel="stylesheet" href="./index.css" />').replace(script,"<script src='./index.js'></script>");
   // 写入文件内容
   //   将在 files目录下 生成 index.html
   fs.writeFile(path.join(__dirname,"files","index.html"),html,(err)=>{
    if(err){
        return console.error("index.html 文件内容写入失败");
    }
    console.log("index.html 文件内容写入成功");
   });
}

 

运行上述代码:

node demo.js
最终目录结构
demo2
  |- demo.js    # 代码文件 
  |- demo.html  # 案列文件
+ |- /files
+   |- index.css   
+   |- index.js
+   |- index.html

 

本文地址: https://maolego.com/458.html
温馨提示: 本站所收集的部分公开资料来源于互联网,转载的目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议
相关文章 关键词:

发表回复

*