nodejs 热更新页面

现在由于写静态页面,每个改动都需要自己刷新页面,所以自己写了一个简单的node热更新

启动server

主要是启动一个server的服务

const http = require("http");
const port = 3000;
//设置默认文件
let defaultFile = path.join("./1.html");
//创建server
const server = http.createServer((req, res) => {
  res.writeHead(200, {"Content-Type": "text/html"});
  html = fs.readFileSync(defaultFile, "utf-8");
  res.end(html);
});
//启动服务
server.listen(port, "127.0.0.1", () => {
  console.log(`服务器运行在 http://:${port}/`);
});

监听文件改动

安装依赖

npm install chokidar

增加监听文件改动的回调

//启动文件监听
var watcher = chokidar.watch(dir, {
  //忽略文件
  ignored: [/^[^\s()<>]+\.(json|svg|js)$|node_modules$/],
  persistent: true,
});

const log = console.log.bind(console);
//监听回调 设置最近更新的文件path
watcher
  .on("add", (path) => {
    log(`File ${path} has been added`);
  })
  .on("change", (path) => {
    log(`File ${path} has been changed`);
    defaultFile = path;
  })
  .on("unlink", (path) => {
    log(`File ${path} has been removed`);
    defaultFile = path.join("./default.html");
  });

增加socket服务和发送msg

npm install socket.io

//启动socket

const io = require("socket.io")(server);
io.on("connection", (client) => {
  console.log("a user connected");
  // socket.on("chat message", (msg) => {
  //   io.emit("chat message", msg);
  // });
  client.on("disconnect", () => {
    console.log("disconnect");
  });
});
//监听到文件改动时,就更新defaultFile,方便服务器返回最新的文件内容
 //socket send
   io.sockets.emit("filechange");

浏览器刷新

//浏览器需要注入socket的代码
function handleHtml(html) {
  let index = html.indexOf("</body>");
  //增加socket代码
  let socketStirng = `<script src="/socket.io/socket.io.js"></script>
  <script>
    var socket = io();
    socket.on("filechange", function (msg) {
      location.reload();
      socket.close();
    });
  </script>`;
  let newhtml = html.slice(0, index - 1) + socketStirng + html.slice(index - 1);
  return newhtml;
}
//修改下createServe的res, 返回增加了socket的html
html = fs.readFileSync(defaultFile, "utf-8");
  let newhtml = handleHtml(html);
  res.end(newhtml);

总结

总体思路就是启动一个server服务和scoket服务,增加监听文件改动的方法,一旦文件改动,就通过scoket发送消息通知客户端,客户端就刷新浏览器,获取到最新的html代码

效果:

代码地址:https://github.com/rainbowChenhong/50project.git

posted @ 2021-08-11 15:26  黑黑哈哈  阅读(734)  评论(0编辑  收藏  举报