Itβs better not to open the file if you are not really going to write it. You can write some shell functions for opening and writing to delay opening a file until you need to write.
var fd; function open() { if (fd) { return; } fd = fs.open(filePath, 'w'); } function write(buffer) { if (!fd) { open(); fs.writeFile(fd, buffer); } else { fs.write(fd, buffer); } } write('open file and write'); write('write to already opened file');
When opening, use fs.open with the 'w' flag, which means the file is created (if it does not exist) or truncated (if it exists).
Another way for the write () function is to call fs.writeFile when writing to a file for the first time, this will overwrite the existing contents of the file and call fs.write for subsequent entries to add.
Under real conditions, the difference between using writeFile () and write () is small, but it avoids checking for a file, deleting it if that happens, and creating a new file.
I assume that you have only one process that accesses this file at a time.
source share