Skip to content

三、fs和path的时钟案例

js
// 获取fs模块
const fs = require('fs');
// 获取path模块
const path = require('path');

fs.readFile(path.join(__dirname,'/index.html'), 'utf8',(err,result)=>{
    if(err) return console.log(err)
    resolveCss(result)
    resolveJs(result)
    resolveHtml(result)
});

// 写入css文件
const resolveCss=(htmlText)=>{
    let styleReg=/<style>[\s\S]*<\/style>/;
    let styleText=styleReg.exec(htmlText)

    let newStyleText=styleText[0].replace('<style>','').replace('</style>','')

    // 写入index.css文件
    fs.writeFile(path.join(__dirname,'/clock/index.css'),newStyleText,'utf8',err=>{
        if(err) return console.log(err)
        console.log('index.css文件写入成功!');
    })
}
// 写入js文件
const resolveJs=(htmlText)=>{
    let jsReg=/<script>[\s\S]*<\/script>/;
    let jsText=jsReg.exec(htmlText)

    let newJsText=jsText[0].replace('<script>','').replace('</script>','')

    // 写入index.css文件
    fs.writeFile(path.join(__dirname,'/clock/index.js'),newJsText,'utf8',err=>{
        if(err) return console.log(err)
        console.log('index.js文件写入成功!');
    })
}
// 写入html文件
const resolveHtml=(htmlText)=>{
    let styleReg=/<style>[\s\S]*<\/style>/;
    let jsReg=/<script>[\s\S]*<\/script>/;

    let newHtmlText=htmlText.replace(styleReg,'  <link rel="stylesheet" href="./index.css">')
    .replace(jsReg,'<script src="./index.js"></script>')

    // 写入index.html文件
    fs.writeFile(path.join(__dirname,'/clock/index.html'),newHtmlText,'utf8',err=>{
        if(err) return console.log(err)
        console.log('index.html文件写入成功!');
    })
}

注意:

  • fs.writeFile()方法只能用来创建文件,不能用来创建路径
  • 重复调用fs.writeFile()写入同一个文件,新写入的内容会覆盖之前的旧内容