Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
190
rated 0 times [  192] [ 2]  / answers: 1 / hits: 27570  / 9 Years ago, thu, july 2, 2015, 12:00:00

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?


More From » node.js

 Answers
58

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!);
}
});
}

[#65950] Tuesday, June 30, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
minab

Total Points: 701
Total Questions: 104
Total Answers: 91

Location: Saint Pierre and Miquelon
Member since Fri, Jan 28, 2022
2 Years ago
;