Programing

파일이 존재하는지 Node.js 확인

crosscheck 2020. 7. 8. 07:52
반응형

파일이 존재하는지 Node.js 확인


파일이 있는지 어떻게 확인 합니까?

모듈의 문서 fs에는 메소드에 대한 설명이 fs.exists(path, callback)있습니다. 그러나 내가 이해하는 것처럼 디렉토리 만 존재하는지 확인합니다. 그리고 파일 을 확인해야 합니다 !

이것을 어떻게 할 수 있습니까?


왜 파일을 열어 보지 않겠습니까? fs.open('YourFile', 'a', function (err, fd) { ... })어쨌든 1 분 검색 후 이것을 시도하십시오 :

var path = require('path'); 

path.exists('foo.txt', function(exists) { 
  if (exists) { 
    // do something 
  } 
}); 

// or 

if (path.existsSync('foo.txt')) { 
  // do something 
} 

Node.js v0.12.x 이상

모두 path.existsfs.exists사용되지 않습니다

*편집하다:

변경 : else if(err.code == 'ENOENT')

에: else if(err.code === 'ENOENT')

Linter는 double equals가 triple equals가 아니라고 불평합니다.

fs.stat 사용 :

fs.stat('foo.txt', function(err, stat) {
    if(err == null) {
        console.log('File exists');
    } else if(err.code === 'ENOENT') {
        // file does not exist
        fs.writeFile('log.txt', 'Some log\n');
    } else {
        console.log('Some other error: ', err.code);
    }
});

이 작업을 동 기적으로 수행하는 가장 쉬운 방법입니다.

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

API 문서는 existsSync작동 방식을 말합니다
. 파일 시스템을 확인하여 주어진 경로가 존재하는지 여부를 테스트하십시오.


stat의 대안은 new fs.access(...):

점검을위한 단축 약속 기능 :

s => new Promise(r=>fs.access(s, fs.F_OK, e => r(!e)))

샘플 사용법 :

let checkFileExists = s => new Promise(r=>fs.access(s, fs.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.F_OK, error => {
      resolve(!error);
    });
  });
}

또는 동 기적으로 수행하려는 경우 :

function checkFileExistsSync(filepath){
  let flag = true;
  try{
    fs.accessSync(filepath, fs.F_OK);
  }catch(e){
    flag = false;
  }
  return flag;
}

fs.exists(path, callback)그리고 fs.existsSync(path), 지금은 사용되지 않는 볼 수 있습니다 https://nodejs.org/api/fs.html#fs_fs_exists_path_callbackhttps://nodejs.org/api/fs.html#fs_fs_existssync_path을 .

파일의 존재를 동 기적으로 테스트하기 위해 ie를 사용할 수 있습니다. fs.statSync(path). fs.Stats파일이 존재하는 경우 객체 참조 반환됩니다 https://nodejs.org/api/fs.html#fs_class_fs_stats를 , 그렇지 않으면 오류가 시도 / catch 문에 의해 사로 잡았 될 슬로우됩니다.

var fs = require('fs'),
  path = '/path/to/my/file',
  stats;

try {
  stats = fs.statSync(path);
  console.log("File exists.");
}
catch (e) {
  console.log("File does not exist.");
}

V6 이전의 이전 버전 : 여기에 설명서가 있습니다

  const fs = require('fs');    
  fs.exists('/etc/passwd', (exists) => {
     console.log(exists ? 'it\'s there' : 'no passwd!');
  });
// or Sync

  if (fs.existsSync('/etc/passwd')) {
    console.log('it\'s there');
  }

최신 정보

V6의 새 버전 : 대한 설명서fs.stat

fs.stat('/etc/passwd', function(err, stat) {
    if(err == null) {
        //Exist
    } else if(err.code == 'ENOENT') {
        // NO exist
    } 
});

fs.exists1.0.0부터 사용되지 않습니다. fs.stat대신 사용할 수 있습니다 .

var fs = require('fs');
fs.stat(path, (err, stats) => {
if ( !stats.isFile(filename) ) { // do this 
}  
else { // do this 
}});

다음은 설명서 fs.stats에 대한 링크입니다.


@ 폭스 : 좋은 대답! 더 많은 옵션이있는 약간의 확장 기능이 있습니다. 최근에 이동 솔루션으로 사용하고 있습니다.

var fs = require('fs');

fs.lstat( targetPath, function (err, inodeStatus) {
  if (err) {

    // file does not exist-
    if (err.code === 'ENOENT' ) {
      console.log('No file or directory at',targetPath);
      return;
    }

    // miscellaneous error (e.g. permissions)
    console.error(err);
    return;
  }


  // Check if this is a file or directory
  var isDirectory = inodeStatus.isDirectory();


  // Get file size
  //
  // NOTE: this won't work recursively for directories-- see:
  // http://stackoverflow.com/a/7550430/486547
  //
  var sizeInBytes = inodeStatus.size;

  console.log(
    (isDirectory ? 'Folder' : 'File'),
    'at',targetPath,
    'is',sizeInBytes,'bytes.'
  );


}

PS 아직 사용하지 않는 경우 fs-extra를 확인하십시오. 달콤합니다. https://github.com/jprichardson/node-fs-extra )


fs.existsSync()더 이상 사용되지 않는 것에 대한 부정확 한 의견이 많이 있습니다 . 그렇지 않습니다.

https://nodejs.org/api/fs.html#fs_fs_existssync_path

fs.exists ()는 더 이상 사용되지 않지만 fs.existsSync ()는 사용되지 않습니다.


async/awaitutil.promisify노드 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);
    }
  });
});

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

약간의 실험을 한 후 다음 예제를 사용하여 fs.stat파일이 존재하는지 비동기 적으로 확인하는 것이 좋습니다. 또한 "파일"이 "실제로 파일"(디렉토리가 아님)인지 확인합니다.

이 방법은 비동기 코드베이스로 작업한다고 가정하고 약속을 사용합니다.

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

파일이 존재하지 않더라도 약속은 여전히 ​​해결 false됩니다. 파일이 존재하고 디렉토리 인 경우 resolve true입니다. 파일을 읽으려고 시도하는 모든 오류 reject는 오류 자체를 약속합니다.


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

이것에 문제가 있습니까?


최신 비동기 / 대기 방법 (노드 12.8.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() or fs.access()있기 때문에 fs.exists(path, callback)지금은 사용되지 않습니다

Another good way is fs-extra


in old days before sit down I always check if chair is there then I sit else I have an alternative plan like sit on a coach. Now node.js site suggest just go (no needs to check) and the answer looks like this:

    fs.readFile( '/foo.txt', function( err, data )
    {
      if(err) 
      {
        if( err.code === 'ENOENT' )
        {
            console.log( 'File Doesn\'t Exist' );
            return;
        }
        if( err.code === 'EACCES' )
        {
            console.log( 'No Permission' );
            return;
        }       
        console.log( 'Unknown Error' );
        return;
      }
      console.log( data );
    } );

code taken from http://fredkschott.com/post/2014/03/understanding-error-first-callbacks-in-node-js/ from March 2014, and slightly modified to fit computer. It checks for permission as well - remove permission for to test chmod a-r foo.txt


vannilla Nodejs callback

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.
}

the docs say you should use access() as a replacement for deprecated exists()

Nodejs with build in promise (node 7+)

function fileExists(path, cb){
  return new Promise((accept,deny) => 
    fs.access(path, fs.constants.F_OK,(er, result)=> cb(!err && result))
  );
}

Popular javascript framework

fs-extra

var fs = require('fs-extra')
await fs.pathExists(filepath)

As you see much simpler. And the advantage over promisify is that you have complete typings with this package (complete intellisense/typescript)! Most of the cases you will have already included this library because (+-10.000) other libraries depend on it.


You can use fs.stat to check if target is a file or directory and you can use fs.access to check if you can write/read/execute the file. (remember to use path.resolve to get full path for the target)

Documentation:

Full example (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);
}());

참고URL : https://stackoverflow.com/questions/17699599/node-js-check-if-file-exists

반응형