Node.js check if file exists

前端 未结 17 903
生来不讨喜
生来不讨喜 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条回答
  •  萌比男神i
    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

提交回复
热议问题