How to properly send message to html side


#1

I’d like to update my html view, when one of my text file is changed. So I downloaded package chokidar to monitor the file changed. I also wants to send the content of these file to the HTML for display.

in my main.js, I wrote

chokidar.watch('data/server1/fake_data.txt', {ignored: /[\/\\]\./}).on('all', (event, path) => {
  sendDataToWeb(mainWindow, path);
  console.log(event, path)
});

function sendDataToWeb(window, data_file_path)
{
  fs.readFile(data_file_path, 'utf8', function (err,data) {
    if (err) {
      return console.log(err);
    }

var array = data.toString().split("\n");
mainWindow.webContents.on('did-finish-load', () => {
  mainWindow.webContents.send('update-data-on-page1', array);
}); //end of mainWindow.webContents.send

}); //end of redFile

} //end of sendDataToWeb

and in my index.html

    require('electron').ipcRenderer.on('update-data-on-page1', (event, message) => {
       console.log("event received");

        //read last cached data
        $(document).ready(function(){

        console.log("event received in document ready");
        for(i in message)
        {
          if(message[i] !="")
          {
            var obj = JSON.parse(message[i]);
            $("<div/>", {
            "class": "Tag",
            "id": "Geo_" + obj.ID,
            "text": "AVG:" + obj.AvgTemp ,
            "style":" position:absolute;text-align:center;font-size: 20px; color: red; margin:0;padding: 0; background: blue; left:" + obj.X +"%;top:" + obj.Y +"%;"
            }).appendTo("#Container1");
         }
        }
    	}); //end of document ready
    });

I found that everytime my file changed, the sendDataToWeb get called, but the webContents.on only execute once. Can anyone help me with the correct usage ?

Thanks,