Node.js check if file exists

前端 未结 17 934
生来不讨喜
生来不讨喜 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:30

    Old Version before V6: here's the documentation

      const fs = require('fs');    
      fs.exists('/etc/passwd', (exists) => {
         console.log(exists ? 'it\'s there' : 'no passwd!');
      });
    // or Sync
    
      if (fs.existsSync('/etc/passwd')) {
        console.log('it\'s there');
      }
    

    UPDATE

    New versions from V6: documentation for fs.stat

    fs.stat('/etc/passwd', function(err, stat) {
        if(err == null) {
            //Exist
        } else if(err.code == 'ENOENT') {
            // NO exist
        } 
    });
    

提交回复
热议问题