Clock case –node splitting

HTML original code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>indexHomepage</title>
    <style>
        html,
        body {<!-- -->
            margin: 0;
            padding: 0;
            height: 100%;
            background-image: linear-gradient(to bottom right, red, gold);
        }
 
        .box {<!-- -->
            width: 400px;
            height: 250px;
            background-color: rgba(255, 255, 255, 0.6);
            border-radius: 6px;
            position: absolute;
            left: 50%;
            top: 40%;
            transform: translate(-50%, -50%);
            box-shadow: 1px 1px 10px #fff;
            text-shadow: 0px 1px 30px white;
 
            display: flex;
            justify-content: space-around;
            align-items: center;
            font-size: 70px;
            user-select: none;
            padding: 0 20px;
 
            /* Box projection */
            -webkit-box-reflect: below 0px -webkit-gradient(linear, left top, left bottom, from(transparent), color-stop(0%, transparent), to(rgba(250, 250, 250, .2) ));
        }
    </style>
</head>
 
<body>
    <div class="box">
        <div id="HH">00</div>
        <div>:</div>
        <div id="mm">00</div>
        <div>:</div>
        <div id="ss">00</div>
    </div>
 
    <script>
        window.onload = function () {<!-- -->
            // Timer, executed every 1 second
            setInterval(() => {<!-- -->
                var dt = new Date()
                var HH = dt.getHours()
                var mm = dt.getMinutes()
                varss = dt.getSeconds()
 
                //Assign values to elements on the page
                document.querySelector('#HH').innerHTML = padZero(HH)
                document.querySelector('#mm').innerHTML = padZero(mm)
                document.querySelector('#ss').innerHTML = padZero(ss)
            }, 1000)
        }
 
        // Zero padding function
        function padZero(n) {<!-- -->
            return n > 9 ? n : '0' + n
        }
    </script>
</body>
 
</html>

The code and explanation for splitting are as follows:

//Import related modules
const fs = require('fs')
const path = require('path')

//Define regular expressions to match <style></style> and <script></script> respectively
  // \s --matches any whitespace character; \S --matches any non-whitespace character * --can appear multiple times
    const regStyle = /<style>[\s\S]*<\/style>/;
    const regScript = /<script>[\s\S]*<\/script>/;

// read file
    fs.readFile(path.join(__dirname,'./index.html'),'utf8',function(err,dataStr){<!-- -->
        // Failed to read html file
        if (err) return console.log("Failed to read html file",err.message);
        //Read html file successfully: disassemble css js html files separately
        resolveCss(dataStr)
    })

// Custom function handles css js html style
    function resolveCss(htmlStr){<!-- -->
    // css
        // Use regular expressions to get the tags in the page
            //exec() return value: is an array,
        const r1 = regStyle.exec(htmlStr)
            //The content in the array contains three items, the first item is the matching content
        // Replace the extracted tags replace()
        const newCss = r1[0].replace("<style>","").replace("</style>","")
        // Call the write method to write the style to .index.css
        fs.writeFile(path.join(__dirname,'./index.css'),newCss,function(err){<!-- -->
            if (err) return console.log("Failed to write style",err.message);
            return console.log("Writing style successfully!!");
        })
    // js
        const s1 = regScript.exec(htmlStr)
        const newScript = s1[0].replace("<script>","").replace("</script>","")
        fs.writeFile(path.join(__dirname,'./index.js'),newScript,function(err){<!-- -->
            if (err) return console.log("Failed to write style",err.message);
            return console.log("Writing style successfully!!");
        })
    // html
        const newHtml = htmlStr.replace(regStyle,'<link rel="stylesheet" href="./index.css">')
                               .replace(regScript,'<script src="./index.js"></script>')
        fs.writeFile(path.join(__dirname,'./clock.html'),newHtml,err =>{<!-- -->
            if(err) return console.log("Failed to write style",err.message);
            return console.log("Writing style successfully!!");
        })
    }

Running it directly on the terminal will generate three corresponding split files in the current directory:

The three split files are:
clock.html

<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>indexHomepage</title>
    
    <link rel="stylesheet" href="./index.css">
</head>
 
<body>
    <div class="box">
        <div id="HH">00</div>
        <div>:</div>
        <div id="mm">00</div>
        <div>:</div>
        <div id="ss">00</div>
    </div>
 
    <script src="./index.js"></script>
</body>
 
</html>

index.css

        html,
        body {<!-- -->
            margin: 0;
            padding: 0;
            height: 100%;
            background-image: linear-gradient(to bottom right, red, gold);
        }
 
        .box {<!-- -->
            width: 400px;
            height: 250px;
            background-color: rgba(255, 255, 255, 0.6);
            border-radius: 6px;
            position: absolute;
            left: 50%;
            top: 40%;
            transform: translate(-50%, -50%);
            box-shadow: 1px 1px 10px #fff;
            text-shadow: 0px 1px 30px white;
 
            display: flex;
            justify-content: space-around;
            align-items: center;
            font-size: 70px;
            user-select: none;
            padding: 0 20px;
 
            /* Box projection */
            -webkit-box-reflect: below 0px -webkit-gradient(linear, left top, left bottom, from(transparent), color-stop(0%, transparent), to(rgba(250, 250, 250, .2) ));
        }
    

index.js

        window.onload = function () {<!-- -->
            // Timer, executed every 1 second
            setInterval(() => {<!-- -->
                var dt = new Date()
                var HH = dt.getHours()
                var mm = dt.getMinutes()
                varss = dt.getSeconds()
 
                //Assign values to elements on the page
                document.querySelector('#HH').innerHTML = padZero(HH)
                document.querySelector('#mm').innerHTML = padZero(mm)
                document.querySelector('#ss').innerHTML = padZero(ss)
            }, 1000)
        }
 
        // Zero padding function
        function padZero(n) {<!-- -->
            return n > 9 ? n : '0' + n
        }
    

Read the file content and respond to the client

path:

//Import related modules
    const fs = require('fs')
    const path = require('path')
    const http = require('http')

//Create web server
    const server = http.createServer()
// Listen to the request event of the web server
    server.on('request',(req,res)=>{<!-- -->
        // Get the url address requested by the client
            // /clock/index.html
            // /clock/index.css
            // /clock/index.js
        const url = req.url

        // Map the requested URL address to the storage path of the specific file
        // let fpath = path.join(__dirname,url)
        //Optimize the path problem of user access
        let fpath = '' // Define an empty path to store the path
        // Since it is not defined, the page cannot be found under the root path, so it needs to be defined. If the user inputs an incomplete path, help the user complete the path.
        url === '/' ? fpath = path.join(__dirname,'/clock/index.html'):fpath = path.join(__dirname,'/clock',url)

        //Read the file according to the mapped file path
        fs.readFile(fpath,'utf-8',(err,dataStr)=>{<!-- -->
            // Failed to read the file, respond to the client with a fixed error message
            if(err) return res.end('404 Not Found!')
            // After successfully reading the file, respond to the user with the corresponding content
            res.end(dataStr)
        })
    })
// Start the server
    server.listen(80,()=>{<!-- -->
        console.log('server running at http://127.0.0.1');
    })

Additional relevant rules:

In regular form:
\s: Matches any whitespace character, including spaces, tabs, form feeds, etc.
\S : matches any non-whitespace character

Four commonly used regular methods:
test(): Verify whether the string matches the regular expression (returns true if it matches, false if it does not match)

exec(): Capture the matching content in the string, only once.
is an array. If there is no grouping, the content in the array contains three items, namely the matching content, the starting index of the matching content, and the original string:

  • The first item is the matching content
  • The second item is the starting index of the matched content
  • The third item is the original string

match(): Capture the matching content in the string

replace(): replace