Existing file check asynchronously

1

My code receives write a file, however, it needs to check if the file already exists and, if it exists, rename it. Is it possible to do this without using fs.existsSync ?

My current code:

fs.readFile(file.path, function (err, data) {

    for (i=2; !fs.existsSync(file.path); i++){
        file.name =file.name + i.toString();
        file.path = "./public/files/" + file.name;
    };
}

fs.writeFile(file.path, data, function (err) {
  if (err) {
    return console.warn(err);
  }
  console.log("The file: " + file.name + " was saved as " + file.path);
});
    
asked by anonymous 09.01.2018 / 02:45

1 answer

3

Can this help you? Documentation

var fs = require("fs");
var Promise = require("bluebird");

function existsAsync(path) {
  return new Promise(function(resolve, reject){
    fs.exists(path, function(exists){
      resolve(exists);
    })
  })
}

Or else:

var path = require('path'); 

path.exists('foo.txt', function(exists) { 
  if (exists) { 
    // faça alguma coisa
  } 
}); 

// ou

if (path.existsSync('foo.txt')) { 
  // faça algo
} 
  

For versions above Node.js v0.12.x

path.exists and fs.exists are deprecated use fs.stat :

fs.stat('foo.txt', function(err, stat) {
    if(err == null) {
        console.log('File exists');
    } else if(err.code == 'ENOENT') {
        // file does not exist
        fs.writeFile('log.txt', 'Some log\n');
    } else {
        console.log('Some other error: ', err.code);
    }
});

I hope I have been able to help you!

    
09.01.2018 / 10:51