Skip to content

Instantly share code, notes, and snippets.

@joepie91
Last active October 5, 2023 21:24
Show Gist options
  • Save joepie91/bbf495e044da043de2ba to your computer and use it in GitHub Desktop.
Save joepie91/bbf495e044da043de2ba to your computer and use it in GitHub Desktop.
Asynchronous fs.exists

Important warning

You should almost never actually use this. The same applies to fs.stat (when used for checking existence).

Checking whether a file exists before doing something with it, can lead to race conditions in your application. Race conditions are extremely hard to debug and, depending on where they occur, they can lead to data loss or security holes. Using the synchronous versions will not fix this.

Generally, just do what you want to do, and handle the error if it doesn't work. This is much safer.

  • If you want to check whether a file exists, before reading it: just try to open the file, and handle the ENOENT error when it doesn't exist.
  • If you want to make sure a file doesn't exist, before writing to it: open the file using an exclusive mode, eg. wx or ax, and handle the error when the file already exists.
  • If you want to create a directory: just try to create it, and handle the error if it already exists.
  • If you want to remove a file or directory: just try to unlink the path, and handle the error if it doesn't exist.

If you're really, really sure that you need to use fs.exists or fs.stat, then you can use the example code below. If you just want to know how to promisify an asynchronous callback that doesn't follow the nodeback convention, then you can look at the example below as well.

var fs = require("fs");
var Promise = require("bluebird");
function existsAsync(path) {
return new Promise(function(resolve, reject){
fs.exists(path, function(exists){
resolve(exists);
})
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment