fs.write only registering after closing server

148 Views Asked by At

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') });
    })
})
2

There are 2 best solutions below

2
On BEST ANSWER

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.

4
On

For performance reasons, modern operating systems buffer disk writes in memory and flush to disk once in a while, preferring to make a few writes of many bytes instead of many writes of a few bytes.

Use fs.fsync or its synchronous counterpart, the humorously-named fs.fsyncSync, to force the operating system to synchronize the in-memory and on-disk contents.