Write log file in nodeJS with setInterval I wrote this code to write the log file every 5 seconds to avoid excessive disk I/O (which can cause HDD temperature to increase or SSD to wear off):

var fs = require('fs');
var logText = '';
function log(){
    fs.appendFile('c:/log.txt', logText, (err) =&gt; {
        if (err) throw err;
        logText = '';
    }); 
}
setInterval(log, 5000);


Is this the correct approach? I mean this is async right? Will setInterval interfere with the performance?
I'm assuming that you are changing the logText variable to control what's being logged. If you want to keep this same interface, the only optimization that I can see is to make log() check if logText is not empty before it writes it:

var fs = require('fs');
var logText = '';
function writelog(){
    if (logText) {
        fs.appendFile('c:/log.txt', logText, (err) =&gt; {
            if (err) throw err;
            logText = '';
        });
    }
}
setInterval(writelog, 5000);


I would also add a function that adds to the log text:

function log(text){
    logtext += ("Log prefix stuff here" + text)
}