I have this function to fetch data from another server(it basically send a command to run a python program, which writes an output into a text file on the remote machine and then it returns the content of the txt file)
const getServerStatus = () => { // returns result of of screen -ls
const commandQuery = "python3 /home/user/scripts/getServerStatus.py && cat /home/user/scripts/status.txt";
return fetch('http://10.0.0.253:3005/fetch', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
command: commandQuery
})
})
.then(res => {
return res.json();
})
.then(data => {
return data.status;
})
.catch(err => { // it catches when fatch fails (server is off)
return 'OFF';
});
};
And the function gets executed when the user visits home page
app.get('/', checkAuthenticated, async (req, res) => {
const status = await getServerStatus()
.then(data => {
return data;
});
res.render('index.ejs', {
name: req.user.username,
title: 'home',
server_status: status
});
})
It runs no problem and it returns data and the home page gets rendered very quickly, but the problem is that if I don't refresh the webpage for a curtain amount of time (maybe like 2-3 minutes or so), it'll take around 8-10 seconds to fetch and render the homepage again. I just can't figure out what the problem is. I think there is something wrong with my async functions but I am not sure. Or maybe my node server goes like an idle mode when there's no oncomming connections?
my /fetch endpoint
app.post('/fetch', (req, res) => {
exec(req.body.command,
function (error, stdout, stderr) {
res.send(JSON.stringify({status :stdout.replace(/\s/g, '')}));
console.log('[+] SERVER STATUS SENT');
if (error !== null) {
console.log('exec error: ' + error);
}
});
});