Node.js check if file exists

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

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

    fs.exists(path, callback) and fs.existsSync(path) are deprecated now, see https://nodejs.org/api/fs.html#fs_fs_exists_path_callback and https://nodejs.org/api/fs.html#fs_fs_existssync_path.

    To test the existence of a file synchronously one can use ie. fs.statSync(path). An fs.Stats object will be returned if the file exists, see https://nodejs.org/api/fs.html#fs_class_fs_stats, otherwise an error is thrown which will be catched by the try / catch statement.

    var fs = require('fs'),
      path = '/path/to/my/file',
      stats;
    
    try {
      stats = fs.statSync(path);
      console.log("File exists.");
    }
    catch (e) {
      console.log("File does not exist.");
    }
    
    0 讨论(0)
  • 2020-12-07 10:38

    Well I did it this way, as seen on https://nodejs.org/api/fs.html#fs_fs_access_path_mode_callback

    fs.access('./settings', fs.constants.F_OK | fs.constants.R_OK | fs.constants.W_OK, function(err){
      console.log(err ? 'no access or dir doesnt exist' : 'R/W ok');
    
      if(err && err.code === 'ENOENT'){
        fs.mkdir('settings');
      }
    });
    

    Is there any problem with this?

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

    A easier way to do this synchronously.

    if (fs.existsSync('/etc/file')) {
        console.log('Found file');
    }
    

    The API doc says how existsSync work:
    Test whether or not the given path exists by checking with the file system.

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

    For asynchronous version! And with the promise version! Here the clean simple way!

    try {
        await fsPromise.stat(filePath);
        /**
         * File exists!
         */
        // do something
    } catch (err) {
        if (err.code = 'ENOENT') {
            /**
            * File not found
            */
        } else {
            // Another error!
        }
    }
    

    A more practical snippet from my code to illustrate better:

    
    try {
        const filePath = path.join(FILES_DIR, fileName);
        await fsPromise.stat(filePath);
        /**
         * File exists!
         */
        const readStream = fs.createReadStream(
            filePath,
            {
                autoClose: true,
                start: 0
            }
        );
    
        return {
            success: true,
            readStream
        };
    } catch (err) {
        /**
         * Mapped file doesn't exists
         */
        if (err.code = 'ENOENT') {
            return {
                err: {
                    msg: 'Mapped file doesn\'t exists',
                    code: EErrorCode.MappedFileNotFound
                }
            };
        } else {
            return {
                err: {
                    msg: 'Mapped file failed to load! File system error',
                    code: EErrorCode.MappedFileFileSystemError
                }
            }; 
       }
    }
    

    The example above is just for demonstration! I could have used the error event of the read stream! To catch any errors! And skip the two calls!

    0 讨论(0)
  • 2020-12-07 10:41
      fs.statSync(path, function(err, stat){
          if(err == null) {
              console.log('File exists');
              //code when all ok
          }else if (err.code == "ENOENT") {
            //file doesn't exist
            console.log('not file');
    
          }
          else {
            console.log('Some other error: ', err.code);
          }
        });
    
    0 讨论(0)
提交回复
热议问题