← coderrocketfuel.com

Create a New Directory in Node.js

How do you create a new directory in Node.js?

Node.js has an Fs core module that provides an fs.mkdir() function that makes creating a new directory or folder super easy.

And since this is included with Node.js as a core module, you won't need to install any NPM packages and can simply import it into your code without any configuration.

To get the code in this article to work, make sure you have Node.js installed on your local machine.

If you need one, we created a guide on installing Node.js.

Let's get started!

Table of Contents

Basic Example

First, we'll go over a basic example of how to use fs.mkdir() in your code.

Here's what it looks like:

const fs = require("fs")

fs.mkdir("./new-directory-name", function(err) {
  if (err) {
    console.log(err)
  } else {
    console.log("New directory successfully created.")
  }
})

Let's break down what's going on in the code.

We require() the fs module and then pass the path of the new directory as an argument to the fs.mkdir() function.

A callback function is also passed as an argument to function. If no error occurs, the directory is successfully created.

When you run the code, either a success or error message will be logged.

Create Parent Directories

What if you want to recursively create multiple levels of directories that don't exist yet?

The fs.mkdir() function has an optional recursive boolean value you can pass as a parameter.

You must have Node v10.12 or greater for this functionality to work. And it's NOT supported on Windows platforms.

Here's a code sample:

const fs = require("fs")

fs.mkdir("./files/a/new-directory-name", { recursive: true }, function(err) {
  if (err) {
    console.log(err)
  } else {
    console.log("New directory successfully created.")
  }
})

That code will create a new directory at a path of /files/a/new-directory-name whether or not the /files or files/a directories exist already. If they don't exist, fs.mkdir() will create them along with the /new-directory-name directory.

Other than that, the code works the same as the basic example from the previous section.

Remember, the recursive functionality is not supported on Windows and an error will be returned if it's used on that platform.