文件内容更改时自动重新加载浏览器,保存在 NodeJS 中



我一直在做node.js项目。 我的要求是我想在浏览器上加载.txt文件。 当我更改并保存此文件时,应更新内容。浏览器应该是自动刷新的。

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
index.js
app.get('/', function(req, res){
res.sendFile(__dirname + '/demo.txt');
});
io.on('connection', function(socket){
console.log('a user connected');
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
var io = require('socket.io')(80);
var fs = require('fs');
fs.watchFile('message.text', (curr, prev) => {
console.log(`the current mtime is: ${curr.mtime}`);
console.log(`the previous mtime was: ${prev.mtime}`);
// file changed push this info to client.
io.emit('fileChanged', 'yea file has been changed.');
});
index.html
<script>
var socket = io();
socket.on('fileChanged', function(msg){
alert(msg);
});

首先,您可以通过两个操作来执行此操作:

1. 在服务器端观察文件更改。并将信息推送到客户端

您可以使用 node.js 观看文件。

var app = require('express')();
var http = require('http').Server(app);
app.get('/', function(req, res){
res.sendFile(__dirname + '/cluster.json');
});
const io = require('socket.io')(http);
io.on('connection',function (client) {
console.log("Socket connection is ON!");
});
http.listen(80, function(){
console.log('listening on *:80');
});
var fs = require('fs');
fs.watchFile('cluster.json', function(curr, prev){
// file changed push this info to client.
console.log("file Changed");
io.emit('fileChanged', 'yea file has been changed.');
});

2.捕获"文件已更改"信息并刷新客户端的页面

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script type="text/javascript" src="node_modules/socket.io-client/dist/socket.io.js"></script>
<script>
var socket = io("http://localhost:80");
socket.on('fileChanged', function(msg){
alert(msg);
});
</script>
</body>
</html>

最好的方法是使用 WebSockets。一个非常好的包来使用 WebSockets 是Socket.io,您可以使用类似chokidar或本机函数fs.watch来观察文件更改,然后发出消息。

或者,如果您尝试仅出于开发目的执行此操作,则应检查具有内置函数的webpackgulp或其他任务运行程序来执行此操作。

使用 Ajax 轮询文件。您的服务器可能会以{changes: '{timestamp-of-file-modify}'}进行响应。现在检查您上次看到的更改时间是否与响应时间不同。

如果有更改:window.location.reload

最新更新