我正在使用express-ws
https://www.npmjs.com/package/express-ws(API有助于为express和websocket客户端创建服务器).
app.ws('/',function(ws,req) { console.log("New connection") if (content.length > 0) { console.log(content) ws.send(content) } ws.on('message',function(msg,flags) { console.log("Received "+ msg); }); ws.on('data',flags) { var data = []; // List of Buffer objects res.on("data",function(chunk) { data.push(chunk); // Append Buffer object console.log(data) }) }) });
现在您可以看到上面的代码,无论何时创建连接,它都会检查内容的长度,并在超过0时向客户端发送conetent.
遵循路由器代码,在Web请求上更新文件.
如果在连接创建后的某个时间(如果此文件被修改),此连接不知道它,因此不会调用此函数,因此不会调用send函数.
我也试过fs.watch但是我无法让它工作.
router.post('/run_restart',function(req,res,next) { text = '{"to_do": "run_test","devices":"all","argv": { "test": "' + req.body.cmd + '","cycles": "' + req.body.cycles + '","awake_for": "' + req.body.wt + '" }}' path = process.env['HOME']+'/Desktop/automation/Stressem/StressemWeb/bin/task.txt' fs.writeFile(path,text) res.render('home.jade',{ title: 'Stressem' }); }); fs.watch(file,function (event) { fs.stat(file,function (err,stats) { if(stats.size>80){ console.log("Event: " + event); fs.readFile(file,'utf8',data) { if (err) throw err; content = data.toString(); }); } });
解决方法
由于您的服务器是更改文件的服务器,因此您无需使用fs.watch,因为您已经知道文件何时发生更改.剩下要做的就是遍历打开的连接列表并向它们发送新内容.
var connections = []; // Keeps track of all connections app.ws('/',req) { console.log("New connection") connections.push(ws); // Add the new connection to the list if (content.length > 0) { console.log(content) ws.send(content) } ws.on('message',function(chunk) { data.push(chunk); // Append Buffer object console.log(data) }) }) // TODO: Make sure you remove closed connections from `connections` // by listening for the ws `close` event. }); router.post('/run_restart',{ title: 'Stressem' }); connections.forEach(function(c){ c.send(text); // Send the new text to all open connections } });