Node.js 'fs' - a more efficient way to create a file + clear the file

I am currently using fs.createWriteStream(filePath) to do two things:

  • Create a file if it does not exist
  • Delete / delete file contents

However, I never write to the stream, so I do not use it. I wonder how this is kosher, and if I should use a more efficient or more explicit way to create a file, if it does not exist, and clean up the file. Any ideas?

+5
source share
3 answers

At your request, by sending your comment as an answer ...

fs.open(filePath, 'w+') using the flags 'w' or 'w+' will also create / truncate the file.

I don’t think that this will really give you a different result than your fs.createWriteStream(filePath) , and the difference in code execution is likely to be insignificant, especially considering that the input / output disk is involved. But this may seem a little cleaner since it does not create a thread that you are not going to use.

+5
source

You can directly use

 fs.writeFile('file path',<data to write>,'encoding',callback) //in your case data is empty 

It will create a file if it does not exist, and if it exists, then the fist will clear the contents and add new contents to it

+3
source

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.

+1
source

All Articles