How to use a Javascript file to refresh/reload a div from an HTML file?

Viewed 105

I am using Node JS and have a JS file, which opens a connection to an API, works with the receving API data and then saves the changed data into a JSON file. Next I have an HTML file, which takes the data from the JSON file and puts it into a table. At the end I open the HTML file in my browser to look at the visualized table and its data.

What I would like to happen is, that the table (or more specific a DIV with an ID inside the table) from the HTML file refreshes itself, when the JSON data gets updated from the JS file. Kinda like a "live table/website", that I can watch change over time without the need to presh F5.

Instead of just opening the HTML locally, I have tried it by using the JS file and creating a connection with the file like this:

const http = require('http');
const path = require('path');

const browser = http.createServer(function (request, response) {

    var filePath = '.' + request.url;
    if (filePath == './') {
        filePath = './Table.html';
    }

    var extname = String(path.extname(filePath)).toLowerCase();
    var mimeTypes = {
        '.html': 'text/html',
        '.css': 'text/css',
        '.png': 'image/png',
        '.js': 'text/javascript',
        '.json': 'application/json'
    };

    var contentType = mimeTypes[extname] || 'application/octet-stream';

    fs.readFile(filePath, function(error, content) {
        response.writeHead(200, { 'Content-Type': contentType });
        response.end(content, 'utf-8');
    });
}).listen(3000);

This creates a working connection and I am able to see it in the browser, but sadly it doesn't update itself like I wish. I thought about some kind of function, which gets called right after the JSON file got saved and tells the div to reload itself. I also read about something like window.onload, location.load() or getElementById(), but I am not able to figure out the right way.

What can I do? Thank you.

1 Answers

Websockets!

Though they might sound scary, it's very easy to get started with websockets in NodeJS, especially if you use Socket.io.

You will need two dependencies in your node application:

 "socket.io": "^4.1.3",
 "socketio-wildcard": "^2.0.0"

your HTML File:

  <script type="module" src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.0.0/socket.io.js"></script>

Your CLIENT SIDE JavaScript file:

var socket = io();

socket.on("update", function (data) { //update can be any sort of string, treat it like an event name
  console.log(data);
  // the rest of the code to update the html
})

your NODE JS file:

import { Server } from "socket.io";

// other code...

let io = new Server(server);
let activeConnections = {};

io.sockets.on("connection", function (socket) { 
  // 'connection' is a "magic" key
  
  // track the active connections
  activeConnections[socket.id] = socket;

  socket.on("disconnect", function () { 
    /* Not required, but you can add special handling here to prevent errors */ 
    delete activeConnections[socket.id];
  })

  socket.on("update", (data) => {  
    // Update is any sort of key
    console.log(data) 
  })
})


// Example with Express 
app.get('/some/api/call', function (req, res) {

 var data = // your API Processing here

 Object.keys(activeConnections).forEach((conn) => {
   conn.emit('update', data)
 }
 res.send(data); 
})

Finally, shameful self promotion, here's one of my "dead" side projects using websockets, because I'm sure I forgot some small detail, and this might help. https://github.com/Nhawdge/robert-quest

Related