socket.io/angular/node를 처음 사용하며 라이센스 수를 표시 할 페이지를 만들려고합니다. 기본적으로 매시간마다 실행되고 파일을 업데이트하는 내 서버에 cron이 있습니다. 내 앱을 초기화하고, 파일을 읽고, 막대 차트로 그 결과를 그래프로 나타내기를 원한다. 또한 파일을 변경할 때마다 파일을 다시 읽길 원합니다. 나는, 그래서 여기에 몇 가지 물건 주위에 놀겠 된 것은 내가 지금까지 무엇을 가지고 :Socket.io 사용 주기적으로 파일을 읽고 차트를 업데이트하려면
내가 같은 간단한 시도
[{
"DEV": 7,
"TEST: 50,
"PROD": 100
}]
서버 파일
const path = require('path');
const express = require('express');
const webpack = require('webpack');
const webpackMiddleware = require('webpack-dev-middleware');
const webpackHotMiddleware = require('webpack-hot-middleware');
const config = require('./config/webpack.prod.js');
const port = process.env.PORT || 8080;
const app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.use(express.static(__dirname + '/dist'));
app.get('*', function response(req, res) {
res.sendFile(path.join(__dirname, 'dist/index.html'));
});
io.on('connection', function(socket){
console.log('==> ' + socket.handshake.address + ' User Connected');
});
io.on('disconnect', function (socket) {
console.log('<== ' + socket.handshake.address + ' User Disconnected');
socket.removeAllListeners('send message');
socket.removeAllListeners('disconnect');
io.removeAllListeners('connection');
});
const fs = require('fs');
fs.watch(__dirname + "/public/agent_count/agent_count_apm", function(event, filename) {
console.log("Event:", event);
if (event == "change") {
fs.readFile(__dirname + "/public/agent_count/agent_count_apm","UTF-8", function(err, data) {
readFile(false);
});
}
});
http.listen(port, '0.0.0.0', function onStart(err) {
if (err) {
console.log(err);
}
console.info('==> Listening on port %s. Open up http://0.0.0.0:%s/ in your browser.', port, port);
readFile(true);
});
function readFile(init) {
fs.readFile(__dirname + "/public/agent_count/agent_count_apm","UTF-8", function(err, data) {
if (err) throw err;
io.emit("agent_count_apm", data);
console.log("agent_count_apm %s", init? "initialized" : "reread");
});
}
컨텐츠 파일
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title><%= webpackConfig.metadata.title %></title>
<meta name="description" content="<%= webpackConfig.metadata.description %>">
<% if (webpackConfig.htmlElements.headTags) { %>
<!-- Configured Head Tags -->
<%= webpackConfig.htmlElements.headTags %>
<% } %>
<script src="https://cdn.socket.io/socket.io-1.4.5.js"></script>
<script>
var socket = io();
socket.on('agent_count_apm', function(msg){
console.log(msg);
document.getElementById("agent_count_apm").value = msg;
});
</script>
<!-- base url -->
<base href="<%= webpackConfig.metadata.baseUrl %>">
</head>
<body>
<app>
</app>
<input id="agent_count_apm" value="" />
</body>
</html>
하지만 파일을 업데이트 한 후에 '입력'만 업데이트되는 것처럼 보입니다. 페이지를 새로 고치면 입력 값이 다시 비워집니다.