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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31195391/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 13:25:47  来源:igfitidea点击:

Create a file if it doesn't already exist

javascriptnode.jsfs

提问by Cory Klein

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

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

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 documentationfor fs.exists, it reads:

然而,看着官方文档fs.exists,它读取:

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.

fs.exists() 是一个时代错误,仅因历史原因而存在。几乎没有理由在您自己的代码中使用它。

特别是,在打开文件之前检查文件是否存在是一种反模式,它会使您容易受到竞争条件的影响:另一个进程可能会在调用 fs.exists() 和 fs.open() 之间删除文件。只需打开文件并在它不存在时处理错误。

fs.exists() 将被弃用。

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?

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

回答by Davide Ungari

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

回答by cstuncsik

fs.closeSync(fs.openSync('/var/log/my.log', 'a'))

回答by Remek Ambroziak

If you would like to write data to this file later, you can use fs.appendFile('message.txt', 'data to append', 'utf8', callback);.

如果您想稍后将数据写入此文件,您可以使用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.

节点文件系统文档