blog icon indicating copy to clipboard operation
blog copied to clipboard

修改代码后, 监听文件变化, 自动刷新页面.

Open plh97 opened this issue 5 years ago • 0 comments

前言

修改文件后,不想f5刷新页面,

技术栈

  • fs.watch监听文件变更
  • ws这个库来实现与浏览器端 Websocket Api进行交互
  • 嗯嗯,js代码直接注入到html文件中就好了..

源码

index.js 文件

const http = require('http');
const fs = require('fs');
const wsScript = require('./client');
const srv = http.createServer((req, res) => {
  res.writeHead(200, { 'Content-Type': 'text/html' });
  // 同步阻塞代码
  let html = fs.readFileSync('./dist/index.html','utf-8')
  html+=wsScript.script;
  res.end(html);
});
srv.listen(8080,()=>{
  console.log('success listen port 8080');
})
let isWatch = true;
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8888 });
wss.on('connection', function connection(ws) {
  console.log('连接');
  if(isWatch){
    isWatch = false;
    fs.watch('./dist/', function (event, filename) {
      console.log(filename , '被修改');
      wss.clients.forEach(client=>{
        console.log("wss",client.readyState);
        if(client.readyState===1){
          client.send('reload')
        }
      })
    });
  }
  ws.on('message', function incoming(msg) {
    console.log('received: %s', msg);
  });
  ws.on('close', function () {
    console.log('关闭');
    ws.close()
  });
  ws.on('error', function error(event) {
    console.log('错误');
    // console.log(event.err + '  state: ' + ws.readyState);
  });
});

client.js文件

module.exports = {
  script: `
    <script>
      function createWS() {
        const log = function(msg) {
          document.body.innerHTML = "<br/>" + document.body.innerHTML;
          document.body.innerHTML = msg + document.body.innerHTML;
        }
        const ws = new WebSocket("ws://localhost:8888");
        ws.onopen = function(){
          console.log('打开');
        }
        ws.onmessage = function(msg){
          switch (msg.data){
            case 'reload':
              console.log('now to reload');
              // ws.send('close');
              window.location.reload();
          }
        }
        ws.onclose = function(){
          // ws.close(); //关闭TCP连接
          console.log('断开连接');
        };
      };
      window.onload = createWS;
    </script>
  `
}

仓库地址

http2 Server Push 实现热更

假如说你连页面刷新都不想,只想热替换js代码呢,

plh97 avatar Dec 16 '18 21:12 plh97