Check synchronously if file/directory exists in Node.js

前端 未结 15 2265
梦如初夏
梦如初夏 2020-11-22 12:26

How can I synchronously check, using node.js, if a file or directory exists?

15条回答
  •  耶瑟儿~
    2020-11-22 13:01

    Another Update

    Needing an answer to this question myself I looked up the node docs, seems you should not be using fs.exists, instead use fs.open and use outputted error to detect if a file does not exist:

    from the docs:

    fs.exists() is an anachronism and exists only for historical reasons. There should almost never be a reason to use it in your own code.

    In particular, checking if a file exists before opening it is an anti-pattern that leaves you vulnerable to race conditions: another process may remove the file between the calls to fs.exists() and fs.open(). Just open the file and handle the error when it's not there.

    http://nodejs.org/api/fs.html#fs_fs_exists_path_callback

提交回复
热议问题