Node.js check if file exists

303,836

Solution 1

Consider opening the file directly, to avoid race conditions:

const fs = require('fs');

fs.open('foo.txt', 'a', function (err, fd) {
  // ...
});

Using fs.existsSync:

if (fs.existsSync('foo.txt')) {
  // ...
}

Using 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);
  }
});

Deprecated:

fs.exists is deprecated.

Using path.exists:

const path = require('path');

path.exists('foo.txt', function(exists) { 
  if (exists) { 
    // ...
  } 
});

Using path.existsSync:

if (path.existsSync('foo.txt')) { 
  // ...
}

Solution 2

Edit: Since node v10.0.0we could use fs.promises.access(...)

Example async code that checks if file exists:

function checkFileExists(file) {
  return fs.promises.access(file, fs.constants.F_OK)
           .then(() => true)
           .catch(() => false)
}

An alternative for stat might be using the new fs.access(...):

minified short promise function for checking:

s => new Promise(r=>fs.access(s, fs.constants.F_OK, e => r(!e)))

Sample usage:

let checkFileExists = s => new Promise(r=>fs.access(s, fs.constants.F_OK, e => r(!e)))
checkFileExists("Some File Location")
  .then(bool => console.log(´file exists: ${bool}´))

expanded Promise way:

// returns a promise which resolves true if file exists:
function checkFileExists(filepath){
  return new Promise((resolve, reject) => {
    fs.access(filepath, fs.constants.F_OK, error => {
      resolve(!error);
    });
  });
}

or if you wanna do it synchronously:

function checkFileExistsSync(filepath){
  let flag = true;
  try{
    fs.accessSync(filepath, fs.constants.F_OK);
  }catch(e){
    flag = false;
  }
  return flag;
}

Solution 3

A easier way to do this synchronously.

if (fs.existsSync('/etc/file')) {
    console.log('Found file');
}

The API doc says how existsSync work:
Test whether or not the given path exists by checking with the file system.

Solution 4

Modern async/await way ( Node 12.8.x )

const fileExists = async path => !!(await fs.promises.stat(path).catch(e => false));

const main = async () => {
    console.log(await fileExists('/path/myfile.txt'));
}

main();

We need to use fs.stat() or fs.access() because fs.exists(path, callback) now is deprecated

Another good way is fs-extra

Solution 5

fs.exists(path, callback) and fs.existsSync(path) are deprecated now, see https://nodejs.org/api/fs.html#fs_fs_exists_path_callback and https://nodejs.org/api/fs.html#fs_fs_existssync_path.

To test the existence of a file synchronously one can use ie. fs.statSync(path). An fs.Stats object will be returned if the file exists, see https://nodejs.org/api/fs.html#fs_class_fs_stats, otherwise an error is thrown which will be catched by the try / catch statement.

var fs = require('fs'),
  path = '/path/to/my/file',
  stats;

try {
  stats = fs.statSync(path);
  console.log("File exists.");
}
catch (e) {
  console.log("File does not exist.");
}
Share:
303,836

Related videos on Youtube

RomanGor
Author by

RomanGor

Updated on February 17, 2022

Comments

  • RomanGor
    RomanGor over 2 years

    How do i check the existence of a file?

    In the documentation for the module fs there's a description of the method fs.exists(path, callback). But, as I understand, it checks for the existence of only directories. And I need to check the file!

    How can this be done?

    • mb21
      mb21 over 5 years
      As of 2018, use fs.access('file', err => err ? 'does not exist' : 'exists'), see fs.access
  • RomanGor
    RomanGor almost 11 years
    But, as it turned out, fs.exists works too. I have had problems with permissions to the file.
  • Arnaud Rinquin
    Arnaud Rinquin about 10 years
    path.exists actually is deprecated in favor of fs.exists
  • Antrikshy
    Antrikshy over 9 years
    Anyone reading this now (Node.js v0.12.x) keep in mind that fs.exists and fs.existsSync have also been deprecated. The best way to check file existence is fs.stat, as demoed above.
  • newprog
    newprog about 9 years
    From Node js documentation, seems like the best way to go if you plan on opening the file after checking its existence, is to actually open it and handle the errors if it doesn't exists. Because your file could be removed between your exists check and the open function...
  • Andy
    Andy almost 8 years
    Both fs.exists and fs.existsSync are deprecated according to the link you shared.
  • Wtower
    Wtower almost 8 years
    stats.isFile() does not need filename.
  • HaveF
    HaveF over 7 years
    @Imeurs but nodejs.org/api/fs.html#fs_fs_existssync_path say: Note that fs.exists() is deprecated, but fs.existsSync() is not.
  • shreddish
    shreddish about 7 years
    The link you provided for fs.existsync clearly stats that it is NOT deprecated "Note that fs.exists() is deprecated, but fs.existsSync() is not. (The callback parameter to fs.exists() accepts parameters that are inconsistent with other Node.js callbacks. fs.existsSync() does not use a callback.)"
  • Dmitry Koroliov
    Dmitry Koroliov about 7 years
    the first (from the top) answer, which mentioned where the fs variable comes from
  • RyanZim
    RyanZim over 6 years
    @Antrikshy fs.existsSync is no longer depricated, though fs.exists still is.
  • RyanZim
    RyanZim over 6 years
    fs.existsSync was deprecated, but it no longer is.
  • RyanZim
    RyanZim over 6 years
    At the time this answer was written, the info was correct; however, fs.existsSync() is no longer deprecated.
  • AKMorris
    AKMorris over 6 years
    Upvoted, this is definitely the most modern (2018) way to detect if a file exists in Node.js
  • Darpan
    Darpan about 6 years
    existsSync is not deprecated as per that doc, may be it was when you read it.
  • Justin
    Justin about 6 years
    Yes this is the official recommended method to simply check if the file exists and manipulation afterwards is not expected. Otherwise use open/write/read and handle the error. nodejs.org/api/fs.html#fs_fs_stat_path_callback
  • samson
    samson about 6 years
    In the documentation I find fs.constants.F_OK etc. Is it also possible to access them like fs.F_OK? Weird. Also terse, which is nice.
  • Philll_t
    Philll_t almost 6 years
    Is this a promise or something? Doesn't seem to be executed asynchronously.
  • vipatron
    vipatron over 4 years
    As @newprog said, the Nodejs documentation for fsPromises(fsp) indeed says that they are correct: Calling fsp.access() then calling fsp.open() can "introduce a race condition" in which "other processes may change the file's state between the two calls". "Instead, [...] open/read/write the file directly and handle the error [if] not accessible" Last part of linked section in docs
  • oldboy
    oldboy over 4 years
    @Antrikshy the nodejs fs documentation only says fs.exists is deprecated, but that fs.existsSync is fine ???
  • Jeremy Trpka
    Jeremy Trpka about 4 years
    Could try doing it with fs.promises.access(path, fs.constants.F_OK); to simply make it a Promise instead of creating a Promise.
  • antitoxic
    antitoxic almost 4 years
    I have been using an even shorter version of this: does not exist: !(await fs.stat(path).catch(() => false)) exists: !!(await fs.stat(path).catch(() => false))
  • Szczepan Hołyszewski
    Szczepan Hołyszewski over 3 years
    Why not just try opening the file? Because that requires catching the error and distinguishing the error thrown as a result of file's nonexistence from any other possible error, while an exists() kind of API answers the question directly and can be used directly in a condition.
  • Systems Rebooter
    Systems Rebooter about 3 years
    thank you! the first example is such an elegant way.
  • TOPKAT
    TOPKAT about 3 years
    This code is so ugly compared to the simple fs.exists one...really wonder why they force us to use such alternatives :'-(
  • ggorlen
    ggorlen almost 3 years
    Synchronous is "easier", but it's also categorically worse because you block the whole process waiting for I/O and other tasks can't make progress. Embrace promises and asynchrony, which the app probably has to use anyway if it's nontrivial.
  • ggorlen
    ggorlen almost 3 years
    A couple characters shorter and maybe easier to read: const fileExists = path => fs.promises.stat(path).then(() => true, () => false);
  • Faither
    Faither almost 3 years
    I'm sorry, but what does say that "existsSync" is deprecated exactly?
  • Marius
    Marius over 2 years
    pls remove the 1st part of the answer, which works only for node < 0.12 (way too old)
  • Alexandre Andrade
    Alexandre Andrade over 2 years
    According to the documentation: "fs.exists() is deprecated, but fs.existsSync() is not. The callback parameter to fs.exists() accepts parameters that are inconsistent with other Node.js callbacks. fs.existsSync() does not use a callback."
  • Константин Ван
    Константин Ван about 2 years
    fs.constants.F_OK, the flag indicating that the file is visible to the calling process, is not needed. It is the default. Just trycatch await fs.access(path).