Safely creating new directories using the Node.js File System API

A usual way to create a directory in Node.js is:

const fs = require('fs')

fs.mkdir('/path/to/new/directory', (err) => {
  // Callback code
})

If the /path/to/new/directory directory already exists, this will fail with the following error:

Error: EEXIST: file already exists, mkdir '/path/to/new/directory'

If the /path/to/new directory (the parent of the directory that we are trying to create) does not exist, this will also fail:

Error: ENOENT: no such file or directory, mkdir '/path/to/new/directory'

In Node.js 10.12.0 and above, it is possible to have these two cases handled automatically by passing the { recursive: true } option to mkdir:

const fs = require('fs')

fs.mkdir('/path/to/new/directory', { recursive: true }, (err) => {
  // Callback code
})

This code will create the /path/to/new/directory directory at the desired destination regardless of whether /path/to/new, /path/to, and /path exist. If the parent directory (or directories) doesn't exist, it will recursively create them. It also won't return an error if /path/to/new/directory already exists.

Importantly, the { recursive: true } option makes the mkdir calls idempotent, meaning that if you execute the same code over again, nothing will change and you won't get errors such as "file already exists".

Note that mkdir can still fail for a number of other reasons such as insufficient permissions, full disk, and so on.

The { recursive: true } option for mkdir was introduced in Node.js 10.12.0 and is not supported in earlier versions. Various third-party libraries can be used in place of native mkdir that offer the same functionality. These include mkdirp, fs-extra, make-dir, and others.

See also

How to list all files recursively within a directory tree in Node.js?

How to receive email in Node.js?

All prices listed are in United States Dollars (USD). Visual representations of products are intended for illustrative purposes. Actual products may exhibit variations in color, texture, or other characteristics inherent to the manufacturing process.