如何不在node.js中覆盖文件 [英] How to not overwrite file in node.js

查看:108
本文介绍了如何不在node.js中覆盖文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果文件存在而不是覆盖它,我想让这段代码更改文件名。

I want to make this code to change filename if file exists instead of overwritng it.

var fileName = 'file';

fs.writeFile(fileName + '.txt', 'Random text', function (err) {
  if (err) throw err;
  console.log('It\'s saved!');
});

类似于:

var fileName = 'file',
    checkFileName = fileName,
    i = 0;

while(fileExists(checkFileName + '.txt')) {
  i++;
  checkFileName = fileName + '-' + i;
} // file-1, file-2, file-3...

fileName = checkFileName;

fs.writeFile(fileName + '.txt', 'Random text', function (err) {
  if (err) throw err;
  console.log('It\'s saved!');
});

考虑到 fs.exists,如何制作fileExists功能( )现已弃用, fs.statSync() fs.accessSync()抛出文件不存在时出错。也许有更好的方法来实现这个目标?

How can I make "fileExists" function, considering that fs.exists() is now deprecated and fs.statSync() or fs.accessSync() throws error if file doesn't exist. Maybe there is a better way to achieve this?

推荐答案

使用 writeFile 第三个参数设置为 {flag:wx} (参见 fs.open 获取标志概述)。这样,它在文件已经存在时失败,并且它还避免了在 exists writeFile call。

use writeFile with the third argument set to {flag: "wx"} (see fs.open for an overview of flags). That way, it fails when the file already exists and it also avoids the possible race condition that the file is created between the exists and writeFile call.

在已存在的情况下以不同名称写入文件的示例代码。

Example code to write file under a different name when it already exist.

fs = require('fs');


var filename = "test";

function writeFile() {
  fs.writeFile(filename, "some data", { flag: "wx" }, function(err) {
    if (err) {
      console.log("file " + filename + " already exists, testing next");
      filename = filename + "0";
      writeFile();
    }
    else {
      console.log("Succesfully written " + filename);
    }
  });

}
writeFile();

这篇关于如何不在node.js中覆盖文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆