如何检查文件是否存在?


当前回答

你可以用fs。Stat检查目标是否为文件或目录,您可以使用fs。访问,检查是否可以写入/读取/执行文件。(记得使用path。决心获得目标的完整路径)

文档:

path.resolve fs.stat fs.access

完整示例(TypeScript)

import * as fs from 'fs';
import * as path from 'path';

const targetPath = path.resolve(process.argv[2]);

function statExists(checkPath): Promise<fs.Stats> {
  return new Promise((resolve) => {
    fs.stat(checkPath, (err, result) => {
      if (err) {
        return resolve(undefined);
      }

      return resolve(result);
    });
  });
}

function checkAccess(checkPath: string, mode: number = fs.constants.F_OK): Promise<boolean> {
  return new Promise((resolve) => {
    fs.access(checkPath, mode, (err) => {
      resolve(!err);
    });
  });
}

(async function () {
  const result = await statExists(targetPath);
  const accessResult = await checkAccess(targetPath, fs.constants.F_OK);
  const readResult = await checkAccess(targetPath, fs.constants.R_OK);
  const writeResult = await checkAccess(targetPath, fs.constants.W_OK);
  const executeResult = await checkAccess(targetPath, fs.constants.X_OK);
  const allAccessResult = await checkAccess(targetPath, fs.constants.F_OK | fs.constants.R_OK | fs.constants.W_OK | fs.constants.X_OK);

  if (result) {
    console.group('stat');
    console.log('isFile: ', result.isFile());
    console.log('isDir: ', result.isDirectory());
    console.groupEnd();
  }
  else {
    console.log('file/dir does not exist');
  }

  console.group('access');
  console.log('access:', accessResult);
  console.log('read access:', readResult);
  console.log('write access:', writeResult);
  console.log('execute access:', executeResult);
  console.log('all (combined) access:', allAccessResult);
  console.groupEnd();

  process.exit(0);
}());

其他回答

考虑直接打开或读取文件,以避免竞争条件:

const fs = require('fs');

fs.open('foo.txt', 'r', (err, fd) => {
  // ...
});
fs.readFile('foo.txt', (err, data) => {
  if (!err && data) {
    // ...
  }
})

使用fs.existsSync:

if (fs.existsSync('foo.txt')) {
  // ...
}

使用fs.stat:

fs.stat('foo.txt', function(err, stat) {
  if (err == null) {
    console.log('File exists');
  } else if (err.code === 'ENOENT') {
    // file does not exist
    fs.writeFile('log.txt', 'Some log\n');
  } else {
    console.log('Some other error: ', err.code);
  }
});

弃用:

fs。Exists已弃用。

使用path.exists:

const path = require('path');

path.exists('foo.txt', function(exists) { 
  if (exists) { 
    // ...
  } 
});

使用path.existsSync:

if (path.existsSync('foo.txt')) { 
  // ...
}

@狐狸:回答得好! 这里有一个扩展,有更多的选项。这是我最近一直在使用的解决方案:

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.'
  );


}

另外,如果你还没有用过fs-extra,那就试试吧——它真的很贴心。 https://github.com/jprichardson/node-fs-extra)

fs。exists(path, callback)和fs.existsSync(path)现在已弃用,请参阅https://nodejs.org/api/fs.html#fs_fs_exists_path_callback和https://nodejs.org/api/fs.html#fs_fs_existssync_path。

要同步测试一个文件是否存在,可以使用ie。fs.statSync(路径)。fs。如果文件存在,Stats对象将返回,请参阅https://nodejs.org/api/fs.html#fs_class_fs_stats,否则将抛出一个错误,该错误将由try / catch语句捕获。

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.");
}

以前,在坐下之前,我总是检查一下椅子是否在那里,然后再坐下,否则我有一个替代计划,比如坐在教练上。现在node.js站点建议直接go(不需要检查),答案是这样的:

    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 );
    } );

代码从http://fredkschott.com/post/2014/03/understanding-error-first-callbacks-in-node-js/从2014年3月,并略有修改,以适应计算机。它也会检查权限—删除测试chmod a-r foo.txt的权限

异步版本!还有承诺版本!这里有干净简单的方法!

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

我的代码中的一个更实用的片段来更好地说明:


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
            }
        }; 
   }
}

上面的例子只是为了演示!我可以使用读流的错误事件!捕捉任何错误!跳过这两个电话!