Reputation: 6904
I am currently learning my way around a nodeJS server. I do client side rendering with ReactJS.
One thing I am wondering about is, when I have new data I need the client to fetch, how do I let the Client know? And what is the best way to do that?
For instance for some sort of chat or similar things.
Upvotes: 0
Views: 232
Reputation: 203
Take a look at http://socket.io/
I can only offer an example.
server.js
io.sockets.on('connection', function(socket) {
console.log(__dirname);
// watching file
fs.watchFile(__dirname + '/example.txt', function(curr, prev) {
// on file change we can read the new file
fs.readFile(__dirname + '/example.txt', function(err, data) {
if (err) throw err;
// parsing the new txt and make it json just my preference
var json = parser.toJson(data);
// send the new data to the client
socket.volatile.emit('notification', json);
});
});
frontend.html
<script src="socket.io/socket.io.js"></script>
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script>
// creating a new websocket
var socket = io.connect('http://localhost:8000');
// on every message recived we print the new datas inside div
socket.on('notification', function (data) {
// json string into a valid javascript object
var _data = JSON.parse(data);
$('#container').html(_data.test.sample);
$('time').html('Last Update:' + new Date());
});
</script>
So basically when my file of data was updated on the server, I used a websocket to keep a connection active between my server and client. It would update the clientside with new data from the file each time it was changed.
Upvotes: 1
Reputation: 2574
HTTP is a request - response protocol that can only be initiated client-side. So you need to look into workarounds like comet or long-polling, or into alternative technologies such as websockets, which allow two way communication in the browser.
http://www.pubnub.com/blog/http-long-polling/
Upvotes: 1