nodejs 热更新页面

如今因为写静态页面,每一个改动都须要本身刷新页面,因此本身写了一个简单的node热更新html

启动server

主要是启动一个server的服务node

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}/`);
});

监听文件改动

安装依赖git

npm install chokidar

增长监听文件改动的回调github

//启动文件监听
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

//启动socketnpm

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代码json

效果:浏览器

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

相关文章
相关标签/搜索