Is node.js rmdir recursive ? Will it work on non empty directories?

后端 未结 22 1417
清歌不尽
清歌不尽 2021-01-31 13:41

The documentation for fs.rmdir is very short and doesn\'t explain the behavior of rmdir when the directory is not empty.

Q: What happens if I try to use

22条回答
  •  猫巷女王i
    2021-01-31 13:58

    Node.js v12.10.0 introduced recursive option into fs.rmdir. As fs.mkdir supports the same option since v10.12.0, both making and removing directory can be executed recursively.

    $ node --experimental-repl-await
    
    # without recursive option -> error
    > await fs.promises.mkdir('foo/bar')
    Thrown:
    [Error: ENOENT: no such file or directory, mkdir 'foo/bar'] {
      errno: -2,
      code: 'ENOENT',
      syscall: 'mkdir',
      path: 'foo/bar'
    }
    
    # with recursive option -> success
    > await fs.promises.mkdir('foo/bar', { recursive: true })
    undefined
    
    # without recursive option -> error
    > await fs.promises.rmdir('foo')
    Thrown:
    [Error: ENOTEMPTY: directory not empty, rmdir 'foo'] {
      errno: -66,
      code: 'ENOTEMPTY',
      syscall: 'rmdir',
      path: 'foo'
    }
    
    # with recursive option -> success
    > await fs.promises.rmdir('foo', { recursive: true })
    undefined
    

提交回复
热议问题