39
28

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

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になる。

39
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
39
28

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?