基本原理:通过node.js的文件系统监听本地文件的变化,通过socket向前端推送信息,前端接收到信息后自动刷新页面。
开发环境
Node.js 6.10.0
express 4.15.2
socket.io 1.7.3
首先生成package.json配置文件
npm init
安装相关依赖包 express, socket.io
npm install --save express --save socket.io
配置服务器文件 app.js
var http = require('http');
var express = require('express');
var app = express();
var server = http.createServer(app);
var path = require('path');
var root = path.join(__dirname, './public');
var fs = require('fs');
var url = require('url');
var io = require('socket.io')(server);
app.use(function (req, res, next) {
var file = url.parse(req.url).pathname;
var mode = 'reload';
createWatcher(file, mode);
next();
});
app.use(express.static(root));
var watchers = {};
function createWatcher(file, event) {
var absolute = path.join(root, file);
console.log(event);
console.log(watchers);
if (watchers[absolute]) {
return;
}else {
fs.watchFile(absolute, function (curr, prev) {
if (curr.mtime !== prev.mtime) {
console.log(`文件被修改`);
io.sockets.emit(event, file);
}
});
watchers[absolute] = true;
}
}
server.listen(8080, function () {
console.log(`The server is running on port 8080.`);
});
进入项目根目录启动服务
node app.js
浏览器打开 http://localhost:8080/index.html 修改index.html文件并保存后页面自动刷新,public目录下其他文件都可实现自动刷新。
GitHub地址:https://github.com/Godgoodstudy/hot-update
结构