如何检查文件是否存在?


当前回答

经过一些实验,我找到了下面使用fs的示例。Stat是异步检查文件是否存在的好方法。它还检查您的“文件”是否“真的是一个文件”(而不是一个目录)。

这个方法使用Promises,假设你使用的是异步代码库:

const fileExists = path => {
  return new Promise((resolve, reject) => {
    try {
      fs.stat(path, (error, file) => {
        if (!error && file.isFile()) {
          return resolve(true);
        }

        if (error && error.code === 'ENOENT') {
          return resolve(false);
        }
      });
    } catch (err) {
      reject(err);
    }
  });
};

如果文件不存在,承诺仍然解析,尽管是错误的。如果文件确实存在,并且它是一个目录,则is解析为true。任何试图读取文件的错误都将拒绝错误本身的承诺。

其他回答

我是这样做的,详见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');
  }
});

这有什么问题吗?

使用util的异步/等待版本。从节点8开始承诺:

const fs = require('fs');
const { promisify } = require('util');
const stat = promisify(fs.stat);

describe('async stat', () => {
  it('should not throw if file does exist', async () => {
    try {
      const stats = await stat(path.join('path', 'to', 'existingfile.txt'));
      assert.notEqual(stats, null);
    } catch (err) {
      // shouldn't happen
    }
  });
});

describe('async stat', () => {
  it('should throw if file does not exist', async () => {
    try {
      const stats = await stat(path.join('path', 'to', 'not', 'existingfile.txt'));
    } catch (err) {
      assert.notEqual(err, null);
    }
  });
});

一种更简单的同步方法。

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

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

2021年8月

读完所有帖子后:

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

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

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