如何检查文件是否存在?


当前回答

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

其他回答

一种更简单的同步方法。

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

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

你可以用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);
}());

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

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)其他库都依赖于它。