如果文件不存在则创建一个文件

Create a file if it doesn't already exist

我想创建一个文件foobar。但是,如果用户已经有一个名为 foobar 的文件,那么我不想覆盖他们的文件。所以我只想创建 foobar 如果它还不存在。

起初,我认为我应该这样做:

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

然而,查看 fs.existsofficial documentation,它显示为:

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.

显然节点开发人员认为我的方法是个坏主意。另外,我不想使用将被弃用的功能。

如何在不覆盖现有文件的情况下创建文件?

我认为答案是:

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

试试这样的东西:

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

如果以后要向这个文件写入数据,可以使用fs.appendFile('message.txt', 'data to append', 'utf8', callback);

Asynchronously append data to a file, creating the file if it does not yet exist. Data can be a string or a buffer.

Node file system documentation.

fs.closeSync(fs.openSync('/var/log/my.log', 'a'))
import { promises as fs } from "fs";

fs.readFile(path).catch(() =>
    fs.writeFile(path, content);
);