Javascript fs.watch events and websockets,catching";“不变”;情况
我观看一个带有以下内容的文件:Javascript fs.watch events and websockets,catching";“不变”;情况,javascript,node.js,websocket,fs,Javascript,Node.js,Websocket,Fs,我观看一个带有以下内容的文件: fs.watch('./data/object.json', (eventType, filename) => {}) if (`${eventType}` === 'change'){ // I call my emission function. emission(/* passing the contents of the file here */); }) 这就是发射函数的含义: // Just a
fs.watch('./data/object.json', (eventType, filename) => {})
if (`${eventType}` === 'change'){
// I call my emission function.
emission(/* passing the contents of the file here */);
})
这就是发射函数的含义:
// Just a dummy place-holder function.
// We later replace that with the real function inside the websocket
// block.
var emitter = function() {};
// Define a hook for the emission point.¬
// 'input' is the bit that receives the contents of the file.
var emission = function(input) {
emitter(input);
};
我这样做是因为我稍后会在websocket调用中注入函数:
wss.on('connection', function(ws) {
emitter = function(input){
// This receives the contents of the file through the input.
// Do some more stuff, convert 'input' into 'data'...
// ... and send to the client.
wss.clients.forEach(function(client) {
client.send(data);
}
}
});
因此,我在websocket连接块中用一个实函数交换了虚拟发射器函数
虽然有点复杂,但到目前为止,这是可行的。随着文件内容的更改,我会向客户端获取一个实时的恒定流
我的问题是:我无法捕获文件内容不再更改的事件。我需要能够捕捉到这一点,并让客户知道该文件不再更改
解决此问题的最佳方法是什么?在
fs.watch
回调中,只需创建一个计时器,定期检查文件是否正在更改
var changing = false;
var timer = null;
function checkChanging() {
if (!changing) {
clearInterval(timer);
timer = null;
notifyNoChange();
}
changing = false;
}
fs.watch('./data/object.json', (eventType, filename) => {})
if (`${eventType}` === 'change'){
if (!timer ) {
timer = setInterval(checkChanging, 1000);
}
changing = true;
// I call my emission function.
emission(/* passing the contents of the file here */);
})
计时器在文件第一次开始更改时设置。如果您想处理文件根本没有改变的情况,可能需要重构此代码。
checkChanging
函数将检查在最后一秒钟内是否有文件更改,并调用notifyNoChange
函数(您需要实现)。不是`${eventType}`==='change'
只是一种非常精细的编写eventType=='change'
的方法吗?另外,fs.watch
如何知道文件不再更改?如果在X时间之后,文件没有更改,您可能必须自己发出这样的事件。这一点很好。我的代码基于以下示例:如何将watch函数包装到另一个可以发出自定义事件的函数中?就我而言,noChange
?谢谢。我将测试你的解决方案。用闭包将两个函数封装在一个函数中是一个好主意吗?我想避免使用全局变量?是的,按照您认为合适的方式重新组织代码,我只是介绍了总体思路