0
点赞
收藏
分享

微信扫一扫

从零开始Node.js—02文件路径path应用

爱我中华8898 2022-03-12 阅读 40

path模块的API

const fpath = 'E:\nodejs\fs\path.js'

path.join([...options]);
path.basename(fpath); //返回文件名 path.js
path.extname(fpath); //返回后缀名 .js

小练习——拆分HTML文件

  1. 已有一个HTML文件index.html,其中有style和script标签
  2. 想将样式和js提取出来,分别存到new文件夹中
  3. 最后new文件夹有三个文件index.htmlindex.cssindex.js
// 拆分HTML文件

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

// 正则表达式
// <style>之间的正则 \s空白字符 \S非空白字符 *任意多次
const regStyle = /<style>[\s\S]*<\/style>/;
const regScript = /<script>[\s\S]*<\/script>/;

// 2 读取HTML文件
const fpath = path.join(__dirname, './file/index.html');
 fs.readFile(fpath,'utf8',(err,data)=>{
   if(err) throw console.error(err.message);

   resolveCSS(data);
   resolveJS(data);
   resolveHTML(data);

 });

 // 拆分为函数 功能 or 处理对象
function resolveCSS(data){
  // 获取style标签之间的部分
  let cssStr = data.match(regStyle)[0];
  // 去掉style标签
  cssStr = cssStr.replace('<style>','').replace('</style>','');

  // 存储文件
  fs.writeFile(path.join(__dirname,'./clock','index.css'),cssStr,(err)=>{
    if(err) throw err;
  });
}

function resolveJS(data){
  // 获取script标签之间的部分
  let jsStr = data.match(regScript)[0];
  // 去掉script标签
  jsStr=jsStr.replace('<script>','').replace('</script>','');
  // 存储文件
  fs.writeFile(path.join(__dirname,'./clock','index.js'),jsStr,(err)=>{
    if(err) throw err;
  });
}

function resolveHTML(data){
  const css = '<link rel="stylesheet" href="./index.css" />';
  const js = '<script src="./clock/index.js"></script>';
  const htmlStr = data.replace(regStyle,css).replace(regScript,js);

  // 存储文件
  fs.writeFile(path.join(__dirname,'./clock','index.html'),htmlStr,(err)=>{
    if(err) throw err;
  });
}

感悟

1、函数抽象🍔

将复杂的逻辑拆成好用的函数,可以从两个方面思考。以这个练习为例
1 面向功能
正则提取字符串-》处理字符串-》输出字符串
若对每个步骤分别抽象出一个处理函数,因为同时要对三个文件操作,每个函数的接口非常多,不利于处理。所以不适合这种场景
2 面向对象
涉及到三个文件对象的处理,三个文件处理细节上有所不同,所以给每个文件都设置一个处理函数。

2、正则规则

尖括号不需要转译<>
正则还是要学学

举报

相关推荐

0 条评论