侧边栏壁纸
博主头像
M酷博主等级

一帆风顺 ⛵️⛵️⛵️

  • 累计撰写 45 篇文章
  • 累计创建 40 个标签
  • 累计收到 454 条评论

目 录CONTENT

文章目录

Nodejs 向文件指定位置插入内容

M酷
2021-10-18 / 4 评论 / 16 点赞 / 4,709 阅读 / 1,822 字 / 正在检测是否收录...
广告 广告

背景

很多时候,我们希望直接通过执行命令的方式代替纯手工的重复性工作,比如通过执行 node 命令,往现有的文件中插入内容,提高效率。

例子

🍄 举个例子,我想在 index.html 中引入一个 webcomponent 组件。那么就可以通过 nodejs 实现向 index.html 头部或尾部插入相关资源和标签。

  1. 通过 fs.readFileSync 读取文件内容;
  2. 使用 split 方法按回车、换行符把文件内容分割为数组;
  3. 使用数组的 splice 方法进行增删改查;
  4. 使用 join 方法,按当前操作系统的行尾标记(EOL) 将数组转为字符串;
  5. 使用 fs.writeFileSync 写入修改后的内容。

以上方法适用于任意文件类型。

演示

① 新建一个 inject.js 文件,内容如下:

// 在index.html中插入icas组件相关文件
const injectToHtml = () => {
  const fs = require("fs");
  const { EOL } = require("os");
  const html = "./public/index.html";
  const source = fs.readFileSync(html, "utf8");
  if (source.indexOf("web-icas") > -1) return; // 若已注入则跳过
  const data = source.split(/\r?\n/gm);
  // head末尾插入资源
  data.splice(
    data.findIndex((c) => c.trim() === "</head>"),
    null,
    `  <link rel="stylesheet" href="./icas/web-icas.css" />
  <script src="https://unpkg.com/vue"></script>
  <script src="./icas/web-icas.min.js" async></script>`
  );
  // body末尾插入组件
  data.splice(
    data.findIndex((c) => c.trim() === "</body>"),
    null,
    `  <web-icas page-show="login"></web-icas>`
  );
  fs.writeFileSync(html, data.join(EOL));
};

injectToHtml();

② 直接在命令行执行 node inject.js 即可插入内容。

<!-- 插入前 -->
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
</head>
<body>
  <div id="app"></div>
</body>
</html>

<!-- 插入后 -->
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <link rel="stylesheet" href="./icas/web-icas.css" />
  <script src="https://unpkg.com/vue"></script>
  <script src="./icas/web-icas.min.js" async></script>
</head>
<body>
  <div id="app"></div>
  <web-icas page-show="login"></web-icas>
</body>
</html>
16
广告 广告

评论区