9

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?

Viesturs Knopkens
  • 594
  • 1
  • 8
  • 16
  • 2
    Such functions are usually unnecessary as another process could easily create or delete the file between you checking for it existing and then trying to process it - seems this is the reason for it being deprecated in node. I'm not familiar with fs in node.js (hence this being a comment and not an answer), but usually there would be a version of a function such as `writeFile` that has options to specify its behaviour if the file already exists – James Thorpe Dec 09 '15 at 19:48

1 Answers1

22

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();
Fabian Schmitthenner
  • 1,696
  • 10
  • 22
  • The flags are documented in the fs.open section of the API. – Gary Dec 09 '15 at 20:41
  • Let me just add that "encoding", "mode", and "flag" are parts of "options" object. It would be one object param instead of additional param. It can be useful for mentioning image encoding. `fs.writeFile(path.join(part1, part2), img_data, { encoding: "base64", flag: "wx" }, function (err) { })` – Max Bender Feb 11 '19 at 17:23