fs.readdir()
reads the contents of a directory asynchronously and returns an array of file and folder names through a callback.
Want to learn more about
fs.readdir()
, check out our Answer: What is the stream fs.readdir() method in Node.js?
Key takeaways:
mkdir()
and mkdirSync()
create directories with key differences in behavior.
mkdir()
is asynchronous. It doesn’t block code execution and works well for non-blocking requests.
mkdirSync()
is synchronous. It blocks execution until completion, useful for ensuring immediate directory creation.
Use if–else
for handling mkdir()
cases and try–catch
for mkdirSync()
.
Syntax for mkdir()
:
fs.mkdir('./path/directoryName', callback)
Syntax for mkdirSync()
:
fs.mkdirSync('./path/directoryName')
Import the fs
module to access these methods: const fs = require('fs');
The fs
module is a built-in file system module in Node.js
that consists of several methods that can be used to access and manipulate files on the operating system. mkdir()
and mkdirSync()
are fs
methods used to create a new directory.
fs.mkdir
and fs.mkdirSync
The main difference between the two methods is that mkdir()
is an asynchronous method and mkdirSync()
is an asynchronous method.
Let’s look at their key differences and get a basic idea regarding when to use which method.
|
| |
Asynchronous vs. Synchronous | It is asynchronous that means when this function is called, it will execute and create a new directory while the other code continues to execute. | It is synchronous that means when this function is called, it will execute and create a new directory and send a callback. Till then the system will go in waiting and nothing else is executed. |
Syntax | Use if-else to handle cases. | Use try-catch to handle cases. |
When to Use | Used when there is a need to handle non-blocking requests. Hence, no immediate need to create the directory. | Used where there is a need for a blocking request to ensure immediate directory creation. |
Real Life Example | We can upload files asynchronously on a web server, allowing the server to simultaneously handle other requests. | We can create directories synchronously when handling nested files and directory scenarios to avoid any race conditions. |
Import the Node.js package fs
to access files:
const fs = require('fs')
The parameters for the fs.mkdir()
and fs.mkdirSync()
methods are the same, with a slight difference in syntax.
The syntax for fs.mkdir()
when handling its cases using if–else
conditions:
fs.mkdir('./path/directoryName', (err) => {if (err) {console.error(err);} else {console.log('Directory created successfully.');}});
The syntax for fs.mkdirSync()
when handling its cases using try–catch
block:
try {fs.mkdirSync('./path/directoryName');console.log('Directory created successfully.');} catch (err) {console.error(err);}
path
: The destination of the directory that is to be created. For example, if we want to create it inside a NewDir
directory, we will write NewDir
in place of the path. This helps in creating nested directories.
directoryName
: The name of the directory that we want to create.
err
: A callback function that is called once the method is executed and returns one of the two cases:
error
: The method fails to create the specified directory.
null
: The method successfully creates the specified directory.
This code creates a directory using both methods to practically communicate the difference between their implementation.
Let’s understand the output of the above example code and examine the difference in the behavior of a synchronous and asynchronous function.
Message 1
is printed because it is the first statement in the code.
Message 2
is printed, which is the very following statement after the mkdir()
method is called.
A new directory is created through the mkdirSync()
method, and its successful case statement is immediately printed because synchronous commands do not allow the code to proceed until its callback is received.
Message 3
is printed as it is the very following statement after the mkdirSync()
method is called.
A new SyncDirectory
directory is added to the public
directory, which was created through the mkdirSync()
method. Note that the synchronous method is executed before the asynchronous method.
A new AsyncDirectory
directory is added to the public
directory, which was created through the mkdir()
method.
The success case message for the directory created through the mkdir()
method is printed at the end once the whole code is executed because it is an asynchronous command.
A quick quiz to test your understanding.
try {
fs.mkdirSync('./Dir1');
console.log('Dir1 created successfully.');
try{
fs.mkdirSync('./Dir2');
console.log('Dir2 created successfully.');
}catch(err) {
console.log(err);
}} catch (err) {
console.error(err);}
What will be the console output for this code?
Dir1 created successfully.
Dir2 created successfully.
Dir2 created successfully.
Dir1 created successfully.
In conclusion, the fs
module in Node.js offers powerful methods for managing directories, with mkdir()
and mkdirSync()
serving as key options for creating directories. Understanding their asynchronous and synchronous nature is crucial for selecting the right method based on your application’s needs. Use mkdir()
for non-blocking operations where performance is prioritized, and mkdirSync()
for scenarios requiring immediate execution and strict sequence control. By using these methods effectively, you can handle file system operations with precision and efficiency in your Node.js applications.
Haven’t found what you were looking for? Contact Us
Free Resources