Fs.write is only registered after the server is closed

I am programming a chat server and I am trying to make chat logs. I am using fs.write to write a message to a file called logs.txt.

The problem is the messages don't appear immediately in the log file as I want, they only appear after the server is closed. How can I fix this?

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

      

+3


source to share


2 answers


You can use the sync version fs.write

β†’ fs.writeSync()


In fact, keeping the log as a string, I think append message to a file longer looks fine for me, you can look fs.appendFileSync

here .



+2


source


For performance reasons, modern operating systems write the spooled disk into memory and flush it to disk from time to time, preferring to make multiple writes from many bytes rather than many writes from several bytes.



Use fs.fsync

or its humorous sync counterpart fs.fsyncSync

to force the operating system to synchronize memory and content on disk.

+1


source







All Articles