Node.js create folder or use existing

后端 未结 14 1434
暖寄归人
暖寄归人 2020-12-04 06:43

I already have read the documentation of Node.js and, unless if I missed something, it does not tell what the parameters contain in certain operations, in particular fs.mkdi

14条回答
  •  时光取名叫无心
    2020-12-04 07:36

    Edit: Because this answer is very popular, I have updated it to reflect up-to-date practices.

    Node >=10

    The new { recursive: true } option of Node's fs now allows this natively. This option mimics the behaviour of UNIX's mkdir -p. It will recursively make sure every part of the path exist, and will not throw an error if any of them do.

    (Note: it might still throw errors such as EPERM or EACCESS, so better still wrap it in a try {} catch (e) {} if your implementation is susceptible to it.)

    Synchronous version.

    fs.mkdirSync(dirpath, { recursive: true })
    

    Async version

    await fs.promises.mkdir(dirpath, { recursive: true })
    

    Older Node versions

    Using a try {} catch (err) {}, you can achieve this very gracefully without encountering a race condition.

    In order to prevent dead time between checking for existence and creating the directory, we simply try to create it straight up, and disregard the error if it is EEXIST (directory already exists).

    If the error is not EEXIST, however, we ought to throw an error, because we could be dealing with something like an EPERM or EACCES

    function ensureDirSync (dirpath) {
      try {
        return fs.mkdirSync(dirpath)
      } catch (err) {
        if (err.code !== 'EEXIST') throw err
      }
    }
    

    For mkdir -p-like recursive behaviour, e.g. ./a/b/c, you'd have to call it on every part of the dirpath, e.g. ./a, ./a/b, .a/b/c

提交回复
热议问题