Node.js check if file exists

前端 未结 17 875
生来不讨喜
生来不讨喜 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.

    0 讨论(0)
  • 2020-12-07 10:42

    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

    0 讨论(0)
  • 2020-12-07 10:42

    After a bit of experimentation, I found the following example using fs.stat to be a good way to asynchronously check whether a file exists. It also checks that your "file" is "really-is-a-file" (and not a directory).

    This method uses Promises, assuming that you are working with an asynchronous codebase:

    const fileExists = path => {
      return new Promise((resolve, reject) => {
        try {
          fs.stat(path, (error, file) => {
            if (!error && file.isFile()) {
              return resolve(true);
            }
    
            if (error && error.code === 'ENOENT') {
              return resolve(false);
            }
          });
        } catch (err) {
          reject(err);
        }
      });
    };
    

    If the file does not exist, the promise still resolves, albeit false. If the file does exist, and it is a directory, then is resolves true. Any errors attempting to read the file will reject the promise the error itself.

    0 讨论(0)
  • 2020-12-07 10:50

    fs.exists has been deprecated since 1.0.0. You can use fs.stat instead of that.

    var fs = require('fs');
    fs.stat(path, (err, stats) => {
    if ( !stats.isFile(filename) ) { // do this 
    }  
    else { // do this 
    }});
    

    Here is the link for the documentation fs.stats

    0 讨论(0)
  • 2020-12-07 10:50

    in old days before sit down I always check if chair is there then I sit else I have an alternative plan like sit on a coach. Now node.js site suggest just go (no needs to check) and the answer looks like this:

        fs.readFile( '/foo.txt', function( err, data )
        {
          if(err) 
          {
            if( err.code === 'ENOENT' )
            {
                console.log( 'File Doesn\'t Exist' );
                return;
            }
            if( err.code === 'EACCES' )
            {
                console.log( 'No Permission' );
                return;
            }       
            console.log( 'Unknown Error' );
            return;
          }
          console.log( data );
        } );
    

    code taken from http://fredkschott.com/post/2014/03/understanding-error-first-callbacks-in-node-js/ from March 2014, and slightly modified to fit computer. It checks for permission as well - remove permission for to test chmod a-r foo.txt

    0 讨论(0)
提交回复
热议问题