如何检查文件是否存在?


当前回答

现代异步/等待方式(Node 12.8. net)。x)

const fileExists = async path => !!(await fs.promises.stat(path).catch(e => false));

const main = async () => {
    console.log(await fileExists('/path/myfile.txt'));
}

main();

我们需要使用fs.stat()或fs.access(),因为fs。Exists (path, callback)现在已弃用

另一个好方法是fs-extra

其他回答

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

现代异步/等待方式(Node 12.8. net)。x)

const fileExists = async path => !!(await fs.promises.stat(path).catch(e => false));

const main = async () => {
    console.log(await fileExists('/path/myfile.txt'));
}

main();

我们需要使用fs.stat()或fs.access(),因为fs。Exists (path, callback)现在已弃用

另一个好方法是fs-extra

一种更简单的同步方法。

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

API文档说明了existsSync是如何工作的: 通过检查文件系统来测试给定路径是否存在。

编辑: 从节点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;
}

2021年8月

读完所有帖子后:

let filePath = "./directory1/file1.txt";

if (fs.existsSync(filePath)) {
    console.log("The file exists");
} else {
    console.log("The file does not exist");
}