Node.js check if file exists

前端 未结 17 924
生来不讨喜
生来不讨喜 2020-12-07 10:02

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, cal

17条回答
  •  鱼传尺愫
    2020-12-07 10:41

    vannilla Nodejs callback

    function fileExists(path, cb){
      return fs.access(path, fs.constants.F_OK,(er, result)=> cb(!err && result)) //F_OK checks if file is visible, is default does no need to be specified.
    }
    

    the docs say you should use access() as a replacement for deprecated exists()

    Nodejs with build in promise (node 7+)

    function fileExists(path, cb){
      return new Promise((accept,deny) => 
        fs.access(path, fs.constants.F_OK,(er, result)=> cb(!err && result))
      );
    }
    

    Popular javascript framework

    fs-extra

    var fs = require('fs-extra')
    await fs.pathExists(filepath)
    

    As you see much simpler. And the advantage over promisify is that you have complete typings with this package (complete intellisense/typescript)! Most of the cases you will have already included this library because (+-10.000) other libraries depend on it.

提交回复
热议问题