Asynchronously checking existing files

Asked

Viewed 485 times

1

My code gets writes a file, but needs to check if the file already exists and, if it exists, rename it. It is possible to do this without using the 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);
});

1 answer

3

I wonder if this might 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 andfs.exists are depreciated 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’ve been able to help you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.