Node.js: Append to file without closing handle

I have blog, written in Node.js, without Express... I want to implement access logs.

I want to store the logs in JSON. There are 2 problems: first, I don't want to open file handle to access log file, write to it, and then close it. I would like to just open it on server startup, and write to it and close it when I shut the server. Is it possible? Is it actually effective?

Second problem: I want to append new log instead of writing whole file. Logs are in form of an array. Is there any way rewrite closing bracket of the array (]) with, add log object behind it and add ] to end?

Open file once, write multiple times

first, I don't want to open file handle to access log file, write to it, and then close it. I would like to just open it on server startup, and write to it and close it when I shut the server. Is it possible? Is it actually effective?

Yes, it's possible and effective. The best solution for you is to open WriteStream once and then write all your data using its .write() method:

var log = fs.createWriteStream('./my.log', {
  flags: 'a' // Open file for appending. The file is created if it does not exist.
})

log.write('Application started');

It's much safer than handling file descriptor by yourself, because, as said in fs.write documentation:

Note that it is unsafe to use fs.write multiple times on the same file without waiting for the callback. For this scenario, fs.createWriteStream is strongly recommended.


Appending file instead of rewriting it

I want to append new log instead of writing whole file

Just use append flag a instead of default write flag w. For more info see fs.open docs.


Append JSON array

Logs are in form of an array. Is there any way rewrite closing bracket of the array (]) with, add log object behind it and add ] to end?

It is a very bad idea to store your logs in such format.

The whole idea of logging is to be able to quickly spit your logs into some log file. You'll need to write quite complicated logic to properly remove and then recreate closing bracket ].

Of course, it's possible. But not doing so is a much better solution.