Solved: Node.js create directory if doesn't exist [Examples]

Quick cheat sheet

The fs module enables you to Node.js create directory if doesn't exist.

// Check if the directory exists
if (fs.existsSync([directory])) {

// asynchronously create a directory
fs.mkdir([directory name], [callback function])

// synchronously create a directory
fs.mkdirSync([directory name])

}

The directory can be a single or a nested tree.

Advertisement

This tutorial explains how to Node.js create directory if it doesn't exist by clarifying the ins and outs of the key fs module's methods. After that, it walks you through practical examples, enabling you to apply the knowledge comfortably.

Let's get started.

 

Introduction to fs module

The fs module handles file writing and reading tasks.

You can check all its methods by entering the Node.js REPL, then typing fs followed by a dot and double-tapping the tab key.

# Enter the REPL mode 
node

# check the native fs module's methods 
> fs. 

# exit the REPL mode 
> process.exit()

Solved: Node.js create directory if doesn't exist [Examples]

Some of the methods are

  • fs.writeFile(): Creates a file and writes content into it.
  • fs.appendFile(): Add more content to an existing file.
  • fs.readFile(): reads the contents of a file asynchronously.
  • fs.mkdir(): makes a directory.
  • fs.rename(): renames a file

The above methods are asynchronous. That means their code portions can run alongside others without blocking the running tasks. An asynchronous task receives a callback function with the error and (sometimes) the data parameters.

Advertisement

However, sometimes you want to halt other running processes until the file reading or writing action is complete.  The tasks that block others are called synchronous. For example, you may not want a file creation process to proceed while checking for the existence of the target directory.

For that reason, you can use synchronous methods (ending with Sync) to check for a directory's existence before Node.js create directory if it doesn't exist.

if (fs.existsSync([directory])) {
    // do something
}

Now that you understand the methods we are about to use, let's Node.js create directory if doesn't exist. We start by creating a file structure.

 

Setup Lab Environment

Open the terminal and create a directory. Inside the directory, create the script file.

$ mkdir main_directory
$ cd main_directory
$ touch script.js

You can open the script file with any code editor, in readiness for examples of Node.js create directory if doesn't exist. Although I am using Vim, you can install and use a preferred code editor like Visual Studio Code.

Solved: Node.js create directory if doesn't exist [Examples]

 

Example-1: Synchronously create directory if doesn’t exist

Step-1: Import the fs module

const fs = require('fs');

 

Step-2: Store the target directory name

const target_directory = './target_directory';

 

Step-3: Check if the directory already exists or create it.

if (!fs.existsSync(target_directory)) {
fs.mkdirSync(target_directory);
}

Node.js create directory if doesn't exist

 

Advertisement

Step-4: Check the output

Save the file, return to the terminal and run the file with the node command.

node script.js

You should get no message if the directory gets created. You can verify the directory creation by checking the contents of the main main_directory directory.

ls

Solved: Node.js create directory if doesn't exist [Examples]

 

Example-2: Asynchronously create directory if doesn’t exist

Assume we want to Node.js create directory if doesn't exist, then print a success message. We can do that by replacing the fs.mkdirSync() with fs.mkdir().

Open the script file and replace the fs.mkdirSync() method with the fs.mkdir() method and a callback function.

const fs = require('fs')
const target_directory = './target_directory';

if (!fs.existsSync(target_directory)) {
    fs.mkdir(target_directory, error => error ? console.log(error) : console.log('You have created the target_directory') ) ;
}

The callback function catches errors that may arise when creating the target directory. We then print the error or a success message.

Next, delete the target target_directory directory we created in example-1 and rerun the script file.

Advertisement
rm -rf target_directory
node script.js

You should get the success message.

user@hostname:~/main_directory$ node script.js
You have created the target_directory

We can confirm the directory's creation by listing the contents of the main directory.

user@hostname:~/main_directory$ ls
script.js target_directory # the expected output

Solved: Node.js create directory if doesn't exist [Examples]

 

Example-3: Recursive create directory if doesn’t exist

Assume we want to create a nested directory inside the main directory. We can do that by introducing the recursive object as an option to the fs.mkdir() method.

Input:

const fs = require('fs')

const nested_directory = './target_directory/another_directory/inside/another';

if (!fs.existsSync(nested_directory)) {

fs.mkdir(nested_directory, { recursive: true }, error => error ? console.log(error) : console.log('You have created the nested_directory') ) ;

}

We start by modifying the directory path from the single target_directory directory to the nested nested_directory directory consisting of three subdirectories: another_directory/inside/another.

Save the script file, then rerun it with the node command.

Advertisement
node script.js

Output:

user@hostname:~/main_directory$ node script.js
You have created the nested_directory

Finally, we can verify each of the subdirectories' creation.

user@hostname:~/main_directory$ ls
script.js target_directory
user@hostname:~/main_directory$ ls target_directory/
another_directory
user@hostname:~/main_directory$ ls target_directory/another_directory/
inside
user@hostname:~/main_directory$ ls target_directory/another_directory/inside/
another

Solved: Node.js create directory if doesn't exist [Examples]

 

Conclusion

You learned how to Node.js create directory if doesn't exist asynchronously, synchronously or recursive using the fs module's existsSync(), mkdir(), and mkdirSync() methods. It is your turn to apply the knowledge to your projects.

 

Related Keywords: nodejs create folder, javascript make directory if not exists, create a node js application create a directory and the contents of the directory, nodejs create file if not exists, nodejs create directory recursively if not exists, node check if directory exists, javascript create directory, create file in current directory nodejs

 

Didn't find what you were looking for? Perform a quick search across GoLinuxCloud

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can either use the comments section or contact me form.

Thank You for your support!!

Leave a Comment

X