node.js fs.exists() will be deprecated, what to use instead?

后端 未结 4 800
我在风中等你
我在风中等你 2021-02-18 13:05

According to the documentation node.js fs.exists() will be deprecated. Their reasoning:

fs.exists() is an anachronism and exists only for historical reasons.

相关标签:
4条回答
  • 2021-02-18 13:44

    Use fs.existsSync().

    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-02-18 13:52

    The io.js docs mention the use of fs.stat() or fs.access() in place of fs.exists().

    0 讨论(0)
  • 2021-02-18 13:57

    Here is an example using fs.stat, but handling errors correctly as well:

    async function fileExists(filename) {
        try {
            await fs.promises.stat(filename);
            return true;
        } catch (err) {
            if (err.code === 'ENOENT') {
                return false;
            } else {
                throw err;
            }
        }
    }
    
    0 讨论(0)
  • 2021-02-18 14:08

    Here is example by using fs.stat:-

    fs.stat('mycustomfile.csv', function (err, stats) {
       console.log(stats);//here we got all information of file in stats variable
       if (err) {
           return console.error(err);
       }
         fs.unlink('mycustomfile.csv',function(err){
            if(err) return console.log(err);
            console.log('file deleted successfully');
       });  
    });
    
    0 讨论(0)
提交回复
热议问题