HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptMinor

Write log file in nodeJS with setInterval

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
filelogwithwritesetintervalnodejs

Problem

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) => {
        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?

Solution

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) => {
            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)
}

Code Snippets

var fs = require('fs');
var logText = '';
function writelog(){
    if (logText) {
        fs.appendFile('c:/log.txt', logText, (err) => {
            if (err) throw err;
            logText = '';
        });
    }
}
setInterval(writelog, 5000);
function log(text){
    logtext += ("Log prefix stuff here" + text)
}

Context

StackExchange Code Review Q#141329, answer score: 4

Revisions (0)

No revisions yet.