Search code examples
node.jsdynamic-data

Current approach to reflect dynamic data from json in nodejs using setInterval


I am trying to develop a MERN stack application, and I have done numerous attempts at this. So, what I am trying to achieve is have some data I am pulling from an api and dump it to a database, then query from the database to create a JSON file every 5 minutes(using jenkins and python, the best approach I can think of). Below is a method I am implementing and it does not work. If I remove the setInterval() function and un-comment the callback function, the code works but does not update the data.

const express = require('express');
const fs = require('fs');
const app = express();

// Read JSON File
function readJSON(callback) {
    fs.readFile('./name.json', "utf8", function(err, result) {
        if (err) callback (err);
        callback(JSON.parse(result));
    });
}

// Process JSON File during callback
// readJSON(function(res) {
//     app.get('/api/customers', (request, response) => {
//         response.json(res);
//     });
// });

// Attempt to run every 5 minutes
setInterval(readJSON(function(res) {
    app.get('/api/customers', (request, response) => {
        response.json(res);
})}, 60000 * 5); // 5 Minutes

const port = 5000

app.listen(port, () => `Server running on port ${port}`);

I thought of using sockets, but I don't want it to be real-time, only live data on an interval. Restful API's I don't believe are a good fit here either, I don't want a 2-way communication to modify/update the data. If my approach is bad, please let me know why you'd pick another approach. I am just trying to establish a foundation in full-stack web dev. Thanks!


Solution

  • A logical code would be:

    On server side:

    function readJSON(callback) {
        fs.readFile('./name.json', "utf8", function(err, result) {
            if (err) callback(err);
            callback(null, JSON.parse(result));
        });
    }
    
    app.get('/api/customers', (request, response) => {
        readJSON((err, nameContent) => {
            if(err) {
                response.status(500).send(err);
            }
            response.send(nameContent);
        })
    });
    

    And in the client side ask for the data every 5 minutes:

    someAjaxMethod('/api/customers', (err, nameContent) => console.log(err, nameContent));