如何检查文件是否存在?


当前回答

fs。Exists自1.0.0以来已弃用。你可以用fs。用统计代替。

var fs = require('fs');
fs.stat(path, (err, stats) => {
if ( !stats.isFile(filename) ) { // do this 
}  
else { // do this 
}});

这里是文档的链接 fs.stats

其他回答

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

异步等待风格的简洁解决方案:

import { stat } from 'fs/promises';

const exists = await stat('foo.txt')
   .then(() => true)
   .catch(() => false);

vannilla Nodejs 回调

function fileExists(path, cb){
  return fs.access(path, fs.constants.F_OK,(er, result)=> cb(!err && result)) //F_OK checks if file is visible, is default does no need to be specified.
}

文档说你应该使用access()来代替已弃用的exists()

带有内置承诺的Nodejs (node 7+)

function fileExists(path, cb){
  return new Promise((accept,deny) => 
    fs.access(path, fs.constants.F_OK,(er, result)=> cb(!err && result))
  );
}

流行的javascript框架

fs-extra

var fs = require('fs-extra')
await fs.pathExists(filepath)

如你所见,简单多了。与promisify相比,它的优势在于你可以使用这个包实现完整的类型(完整的智能感知/typescript)!大多数情况下,您已经包含了这个库,因为(+-10.000)其他库都依赖于它。

编辑: 从节点v10.0.0开始,我们可以使用fs.promises.access(…)

检查文件是否存在的异步代码示例:

function checkFileExists(file) {
  return fs.promises.access(file, fs.constants.F_OK)
           .then(() => true)
           .catch(() => false)
}

stat的替代方法可能是使用新的fs.access(…):

简化的短承诺函数检查:

s => new Promise(r=>fs.access(s, fs.constants.F_OK, e => r(!e)))

示例用法:

let checkFileExists = s => new Promise(r=>fs.access(s, fs.constants.F_OK, e => r(!e)))
checkFileExists("Some File Location")
  .then(bool => console.log(´file exists: ${bool}´))

扩大承诺方式:

// returns a promise which resolves true if file exists:
function checkFileExists(filepath){
  return new Promise((resolve, reject) => {
    fs.access(filepath, fs.constants.F_OK, error => {
      resolve(!error);
    });
  });
}

或者如果你想同步操作:

function checkFileExistsSync(filepath){
  let flag = true;
  try{
    fs.accessSync(filepath, fs.constants.F_OK);
  }catch(e){
    flag = false;
  }
  return flag;
}

V6之前的旧版本: 下面是文档

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

更新

V6的新版本:fs.stat的文档

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