- [Instructor] In the last lesson,
we used the fs modules rename method
to rename and move files.
You can use that same method
to rename and move directories, too.
Let's go ahead and create a new file
within our start folder called directories.js.
And the first thing we'll do is require the fs module.
And using the fs.renameSync,
I'm going to go ahead and rename the ./storage-files
to simply ./storage.
I can open up my terminal and run this fob
by typing directories,
and we can see that our storage directory
is now simply called storage.
Let's go ahead and remove the directory.
Now to remove a directory,
we need to use fs.rmdir,
and we're going to use the asynchronous version
of this function so the directory that we wish to remove
is going to be ./storage,
and once the removal is complete any errors
will be passed to this call back function.
So like always, I'm just going to check the error,
and if there is an error, we're going to throw it.
Otherwise, I'll go ahead and put a console.log
storage directory removed.
So let's go ahead and go into our terminal
and run this file again
so we will node directories,
and notice this time we see an error.
We're getting a not empty error
so we can't remove the storage directory
because we have some files in there.
So before we remove the directory,
we need to delete all of the files within that directory.
Fs.readdirSync is going to be the synchronous version
of the function that will read a directory.
So the readdirSync function is going to give us an array
of every filename within the directory.
I can simply chain a forEach
to loop through each item of that array,
and each item of that array is going
to be a string filename so we can go ahead
and throw in a little call back function
to handle each filename.
Now using fs.unlinkSync,
I can go ahead and unlink our ./storage/$(filename),
and this will synchronously unlink or remove
every file from the storage directory
before we hit line seven where we make the call
to remove the directory.
Let's go ahead and open up our terminal
and run this code, node directories.
So this time we notice that there is no error,
and we see that the storage directory
and all of the files within the storage directory
have been removed.
So before we can remove a directory with fs.rmdir,
we need to make sure that all the files
within that directory have been moved or removed.
In this case, we read all of the files
within the storage directory,
and we used the unlinkSync function to remove them all
before deleting that directory.