snippetjavascriptMinor
Write log file in nodeJS with setInterval
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):
Is this the correct approach? I mean this is async right? Will
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
I would also add a function that adds to the log text:
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.