Create a file if it doesn't already exist

Cory Klein picture Cory Klein · Jul 3, 2015 · Viewed 17.3k times · Source

I would like to create a file foobar. However, if the user already has a file named foobar then I don't want to overwrite theirs. So I only want to create foobar if it doesn't exist already.

At first, I thought that I should do this:

fs.exists(filename, function(exists) {
  if(exists) {
    // Create file
  }
  else {
    console.log("Refusing to overwrite existing", filename);
  }
});

However, looking at the official documentation for fs.exists, it reads:

fs.exists() is an anachronism and exists only for historical reasons. There should almost never be a reason to use it in your own code.

In particular, checking if a file exists before opening it is an anti-pattern that leaves you vulnerable to race conditions: another process may remove the file between the calls to fs.exists() and fs.open(). Just open the file and handle the error when it's not there.

fs.exists() will be deprecated.

Clearly the node developers think my method is a bad idea. Also, I don't want to use a function that will be deprecated.

How can I create a file without writing over an existing one?

Answer

Davide Ungari picture Davide Ungari · Jul 3, 2015

I think the answer is:

Just open the file and handle the error when it's not there.

Try something like:

function createFile(filename) {
  fs.open(filename,'r',function(err, fd){
    if (err) {
      fs.writeFile(filename, '', function(err) {
          if(err) {
              console.log(err);
          }
          console.log("The file was saved!");
      });
    } else {
      console.log("The file exists!");
    }
  });
}