fs.exists, fs.existsSync - why are they deprecated?

前端 未结 7 512
遥遥无期
遥遥无期 2021-01-07 20:06

I noticed that the official node documentation says something startling about fs.exists:

\"fs.exists() is an anachronism and exists only

相关标签:
7条回答
  • 2021-01-07 20:10

    I was searching for a solution to this issue and found that fs.exists and fs.existsSync was deprecated. This seems to work well in my senario

    fs.readFile(filename, 'utf8', function(err,data){
        // the err variable substitutes for the fs.exists callback function variable
        if (!err){
            // do what you planned with the file
            console.log(data)
        }else{
            // handle the non-existence of the file
            console.log('File does not exist!');
        }
    });
    
    0 讨论(0)
  • 2021-01-07 20:15

    There is no need to use fs.stat(), because fs.existsSync() has not been deprecated.

    https://nodejs.org/api/fs.html#fs_fs_existssync_path

    fs.existsSync(path)

    Added in: v0.1.21 path | Synchronous version of fs.exists(). Returns true if the file exists, false otherwise.

    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.)

    0 讨论(0)
  • 2021-01-07 20:27

    You can use new install for this one and continue to use it:
    https://github.com/imyller/node-fs-exists-nodeback

    npm install fs-exists-nodeback
    
    0 讨论(0)
  • 2021-01-07 20:29

    Because of the second paragraph you quoted.

    There is no point in checking whether a file exists, because it could always be deleted right after the check.

    0 讨论(0)
  • 2021-01-07 20:29

    existsSync's implementation is like this (v0.10.25):

    function (path) {
      try {
        nullCheck(path);
        binding.stat(pathModule._makeLong(path));
        return true;
      } catch (e) {
        return false;
      }
    }
    

    so if you write program like if(fs.existsSync(thepath)){}, it is better to change it to if(fs.statSync(thepath)){}.

    0 讨论(0)
  • 2021-01-07 20:30

    I think it because it's redundant. You can check if a file exists by trying to open it. It will give you ENOENT if it doesn't exist:

    > fs.open('foo', 'r', function(err, fd) {
        ... console.log(err, fd);
        ... 
    })
    undefined
    > { [Error: ENOENT, open 'foo'] errno: 34, code: 'ENOENT', path: 'foo' } undefined
    
    0 讨论(0)
提交回复
热议问题