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?
If a file does not exist, append mode creates the file.
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.
In Linux, we can create an empty file using the "touch" command.
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.
fs.closeSync(fs.openSync('/var/log/my.log', 'a'))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With