gpt4 book ai didi

node.js - 如何在浏览器上显示不断更新的文件?

转载 作者:太空宇宙 更新时间:2023-11-04 01:15:38 26 4
gpt4 key购买 nike

我的目标是用一些文件更新网页。当我编辑并保存文件时,其内容会立即更新到页面。

我正在使用 socket.io 来处理此问题。但。我需要对我的代码进行一些修改才能接近它。

::我的服务器端代码:

var PORT = 8001;
var io = require("socket.io").listen(PORT);
var fs = require("fs");

io.sockets.on('connection', function(socket) {
console.log("Connected!");
socket.emit('connected', { accept: true});

console.log("Trying to send a content file to client...");
fs.readFile("file.txt","UTF-8", function(err, data) {
if (err) throw err;
socket.emit("requestFile", data );
console.log("Conteúdo:", data);
})
});

console.log("Application has started! Port: " + PORT);

::我的页面

<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript" src="http://localhost:8001/socket.io/socket.io.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<style>
.arquivo {
font-family: Arial, Helvetica, sans-serif;
font-size: 14px;
width: 900px;
border: 2px solid black;
-moz-border-radius: 3px;
}
</style>
<script type="text/javascript">
console.log("Try to logon...");
var socket = io.connect("localhost", {"port" : "8001"});

socket.on("connected", function(data) {
console.log("Connected User?", data.accept);
});

//recebe o arquivo indefinidamente
var requestFile = socket.on("requestFile", function(data) {
$("#arquivoSaida").html(data + "<br/>");
console.log(data);
});

setInterval(requestFile, 200);
</script>
</head>
<body>
<h3 style="font: Arial, Verdana; font-size: 14px; font-weight: bold;">
File updated:
</h3>
<div id="arquivoSaida">

</div>
</body>
</html>

我使用 setInterval 以 200 毫秒触发,向服务器请求文件。任何提示都会非常受欢迎。

提前致谢!

-- 更新了解决方案:

::我对原始代码做了一些修改。该解决方案由 PuerkitoBio 提供。谢谢,伙计!

更新的代码:

var PORT = 8001;
var io = require("socket.io").listen(PORT);
var fs = require("fs");

io.sockets.on('connection', function(socket) {
console.log("Connected!");
socket.emit('connected', { accept: true});

console.log("Trying to send the content to a client...");
console.log("dir", __dirname);

fs.watch(__dirname + "/arquivo.txt", function(event, filename) {
console.log("Event:", event);

if (event == "change") {
fs.readFile("arquivo.txt","UTF-8", function(err, data) {
if (err) throw err;
socket.emit("receiveFile", data );
console.log("Content:", data);
})
}

});

});

console.log("Application has started! Port: " + PORT);

最佳答案

您可以使用fs.watchFile()并将curr.mtime与prev.mtime进行比较来检测文件是否已被修改。然后使用 readFile 将内容发送到连接的客户端。 From the docs

使用套接字,您不会从客户端轮询数据,而是在需要时从服务器推送数据(在您的情况下,当您的文件更改时)。因此,您不需要客户端的 setInterval (您将使用 fs.watchFile 监视服务器端的更改,并将内容推送到客户端,因此客户端上的“requestFile”处理程序将被自动调用(应该是重命名为 receiveFile 或其他更准确的名称!)。

关于node.js - 如何在浏览器上显示不断更新的文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9548223/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com