Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a file if it doesn't already exist

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?

like image 364
Cory Klein Avatar asked Jul 02 '15 22:07

Cory Klein


People also ask

Which mode create a new file if file does not exist?

If a file does not exist, append mode creates the file.

How do you create a file if it does not exist Python?

To create a file if not exist in Python, use the open() function. The open() is a built-in Python function that opens the file and returns it as a file object. The open() takes the file path and the mode as input and returns the file object as output.

Which command create and import a file if file does not exist?

In Linux, we can create an empty file using the "touch" command.

Which mode is used to create a new file if the file already exists?

FileMode. Create is equivalent to requesting that if the file does not exist, use CreateNew; otherwise, use Truncate. If the file already exists but is a hidden file, an UnauthorizedAccessException exception is thrown. Specifies that the operating system should create a new file.


1 Answers

fs.closeSync(fs.openSync('/var/log/my.log', 'a'))
like image 156
cstuncsik Avatar answered Nov 15 '22 14:11

cstuncsik