InsightsTopicsContact
Eckher
Your guide to what's next.
Home › Eckher Insights › Safely creating new directories using the Node.js File System API
Aug 21, 2020

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

How to safely create directories using the native file system module in Node.js?

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.

Cover
See also
Amazon EC2 Mac instances: Provisioning macOS compute environments in the AWS cloud
Powered by Apple Mac minis, EC2 Mac instances allow developers to provision macOS-based environments in the cloud and benefit from the pay-as-you-go pricing model.
Here's the full list of AWS services
A complete list of services offered by Amazon Web Services, with the latest additions.
Receiving email with Node.js
How to receive email in Node.js?
Eckher
Your guide to what's next.
Copyright © 2021 Eckher. Various trademarks held by their respective owners.