How to not overwrite file in node.js

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-21 17:18:26

问题


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

Something like:

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

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?


回答1:


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();


来源:https://stackoverflow.com/questions/34187284/how-to-not-overwrite-file-in-node-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!