如何检查文件是否存在?


当前回答

在node14中使用typescript和fs/promises

import * as fsp from 'fs/promises';
try{
const = await fsp.readFile(fullFileName)
...
} catch(e) { ...}

最好使用fsp。readFile than fsp。定子fsp。访问有两个原因:

最不重要的原因是少了一个机会。 有可能fsp。statand fsp。readFile会给出不同的答案。要么是因为他们所问问题的细微差异,要么是因为文件状态在两次调用之间发生了变化。因此编码器必须为两个而不是一个条件分支编码,用户可能会看到更多的行为。

其他回答

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

import { stat } from 'fs/promises';

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

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

在node14中使用typescript和fs/promises

import * as fsp from 'fs/promises';
try{
const = await fsp.readFile(fullFileName)
...
} catch(e) { ...}

最好使用fsp。readFile than fsp。定子fsp。访问有两个原因:

最不重要的原因是少了一个机会。 有可能fsp。statand fsp。readFile会给出不同的答案。要么是因为他们所问问题的细微差异,要么是因为文件状态在两次调用之间发生了变化。因此编码器必须为两个而不是一个条件分支编码,用户可能会看到更多的行为。

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

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

这有什么问题吗?