Node.js check if file exists

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

    @Fox: great answer! Here's a bit of an extension with some more options. It's what I've been using lately as a go-to solution:

    var fs = require('fs');
    
    fs.lstat( targetPath, function (err, inodeStatus) {
      if (err) {
    
        // file does not exist-
        if (err.code === 'ENOENT' ) {
          console.log('No file or directory at',targetPath);
          return;
        }
    
        // miscellaneous error (e.g. permissions)
        console.error(err);
        return;
      }
    
    
      // Check if this is a file or directory
      var isDirectory = inodeStatus.isDirectory();
    
    
      // Get file size
      //
      // NOTE: this won't work recursively for directories-- see:
      // http://stackoverflow.com/a/7550430/486547
      //
      var sizeInBytes = inodeStatus.size;
    
      console.log(
        (isDirectory ? 'Folder' : 'File'),
        'at',targetPath,
        'is',sizeInBytes,'bytes.'
      );
    
    
    }
    

    P.S. check out fs-extra if you aren't already using it-- it's pretty sweet. https://github.com/jprichardson/node-fs-extra)

提交回复
热议问题