首页 > 解决方案 > 从 accessSync 返回 ENOENT 以外的值

问题描述

当它找不到文件/目录而不是时,false我将如何返回?accessSyncENOENT

单元测试

it.only('should be able to read a file stream only if a file exist', function() {
    let testfile = testpath+'/imageeee.png';
    let ok = FileService.existsAsync(testfile);

    ok = ok.then((result) => {
      console.log('exists: ', result);
      return FileService.createReadStream(testfile);
    });

    ok = ok.then((result) => {
      assert.isNotNull(result.path);
      assert.equal(result.path, testfile);
      assert.isTrue(result.readable, true);
    });
    return ok;
  });

功能

 existsAsync(path) {
    let ok = fs.accessAsync(path, fs.F_OK);
    ok = ok.then(function(error) {
      if (error) {
        return false;
      } else {
        return true;
      }
    });
    return ok;
  },

错误

 Error: ENOENT: no such file or directory, access '/home/j/Work/imageeee.png'

标签: node.jsasynchronous

解决方案


将此视为替代解决方案,通过使用带有 cat 的 'child_process' 而不是 'fs' 功能来了解文件是否存在(实际捕获错误异常不会干扰您的主要当前进程),从而避免 ENOENT 错误。

const { exec } = require('child_process');

function is_file(path){
  return new Promise(resolve => {
    try {
      exec(`cat ${path}`, (err, stdout, stderr) => { // cat required
        if (err) {
          resolve(false);
        } else {
          resolve(true);
        }
      });
    } catch ( e ) { resolve(false); }
  });
}

async function main(){
  let file = `foo.txt`;
  if ( (await is_file(file)) ) {
    console.log(`file exists: ${file}`);
  } else {
    console.log(`no such file: ${file}`);
  }
}

main();

推荐阅读