3

I was using readdirsync() to get all the file names in a directory then send it to the front end and it works fine. The problem is if a new file is created in the directory after readdirsync run it the won't update the files name array to send to the back end. How can I listen if a new file exists and resend the data to the client-side without having to reload the server manually? Is this possible? Any help is appreciated. Thanks in advance.

const fs = require("fs");

var currentData = []
fs.readdirSync('./dirPATH').forEach(file => {
    currentData.push(file);
});

//what i tried but this won't work. still requires manual server restart:
function dataExchange() {
    app.post("/getData", (req, res) => {
        try {
            res.send(currentData);
        } catch (error) {
            console.log(error);
            res.status(400);
        }
    })
}

dataExchange()
setInterval(() => {
    dataExchange()
}, 2000)
seriously
  • 1,202
  • 5
  • 23

0 Answers0