I'm programming a chat server, and I'm trying to make chat logs. I'm using fs.write to write the message to a file called logs.txt.
The problem is that the messages don't show up instantly in the log file like I want them to, they only appear after I shut down the server. How can I fix that?
Here's the code I used:
fs.open('./logs.txt', 'a', 0666, function(err, fd) {
if (err) {
console.log('file could not be opened');
}
fs.write(fd, data, 0, data.length, null, function(err, written, buffer) {
if (err) {
console.log('log could not be written');
}
fs.close(fd, function() { console.log('log written') });
})
})
You can use sync version
fs.write
->fs.writeSync()
Actually, saving log like string, I think append message to file is more look ok for me, you can look
fs.appendFileSync
here.