0

Can anyone guide me in the right direction?

I have a NodeJS app that is displaying an image. The image (saved in a local directory) gets updated after a certain time by an OpenCV script. However, when the image is updated, the update does not show on my app until I refresh the page. Does anyone know how I can have my image update automatically?

Here is how I serve the image from a directory as a static file:

var express = require('express');
var app = express();    
var publicDir = require('path').join(__dirname,'/public');
app.use(express.static(publicDir));

With the code above, I can access my image using this directory: http://localhost/images/myImage.jpg

Does anyone have an idea of how I can have my image be updated automatically? Or recommend something different for my use case? I don't know if my approach to the problem is the right one.

Mauricio
  • 109
  • 1
  • 11
  • 1
    [This post might be useful to you](https://stackoverflow.com/questions/11077857/what-are-long-polling-websockets-server-sent-events-sse-and-comet). Basically, to automatically get the updated version you will probably have to occasionally ping your backend to see if there's an updated version or use a websocket to notify the front end that a new version is available. You might also need to use some sort of cachebusting measure to make sure you pull a fresh version. This is off the top of my head-- someone may yet answer with a better solution. – Alexander Nied Mar 07 '19 at 03:43
  • Indeed you are looking at this problem the wrong way. There's nothing simple you can do on the server side to solve this problem. – Robert Moskal Mar 07 '19 at 03:46

2 Answers2

1

You can use reload to refresh the page automatically from the server side. This might be helpful for you. How to reload manually is explained in the documentation.

reloadServer = reload(app);
watch.watchTree(__dirname + "/public", function (f, curr, prev) {
// Fire server-side reload event
reloadServer.reload();
});
1

Take a look at Socket.IO http://socket.io/#how-to-use

when the server decides to broadcast a change use:

io.sockets.emit('update-msg', { data: 'this is the data'});

on the client first connect socket.io and then wait for the "update-msg" event and update your dom:

var socket = io.connect('http://localhost');
socket.on('update-msg', function (msg) {
    console.log(msg);
    $('#mydiv').html(msg.data)
});
Shivam
  • 3,514
  • 2
  • 13
  • 27