LoginSignup
38
28

More than 5 years have passed since last update.

fs.statSyncでファイルの存在判定

Posted at

node書いてたときのメモ。

ファイルが存在しているかを確認したい。

versions
node -v
> v4.2.3

fs.existsSync(path) はv1.0.0でDeprecatedになっていたので、fs.statSync(path)を使う。

sample.js
fs.statSync('hoge.txt');
// Uncaught Error: ENOENT: no such file or directory, stat 'hoge.txt'

hoge.txtが存在しないと、エラーになるので
try catchでくるんであげる。
ENOENT は、「No such file or directory」のエラーコード。)

sample.js
function isExistFile(file) {
  try {
    fs.statSync(file);
    return true
  } catch(err) {
    if(err.code === 'ENOENT') return false
  }
}

isExistFile('./hoge.txt');
// false

もちろん存在する時はtrueになる。

38
28
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
38
28