- [Eve] We can also create directories
with the file system module's mkdir function.
So let's create a new file and create some directories.
I've created this new file here called directory.js,
which is going to start
with our require statement.
And then we're going to use the asynchronous mkdir method
and make a directory called your-files-here.
So if we wanted to do this synchronously,
of course we would use mkdirSync,
but we want to use mkdir.
The first argument we'll send here is your-files-here.
Then we'll add this function with an error,
and we'll say if the error occurs,
then we want to console.log an error
in a little template string here.
Otherwise, we will message our user to let 'em know
that the directory was created.
So here we'll say directory created.
Now we want to run this with node directory,
and it looks like, if I type ls,
we've created a directory called your-files-here.
And if I type open. or explorer. on a PC,
we'll see that the Finder opens up,
and yep, here's my directory.
So let's go ahead and try to run this again.
So we'll run node directory,
but this time we're getting an error.
It's letting us know that the file already exists
when I try to make this directory.
We want to make sure that this is not created.
So we'll say fs.existsSync
your-files-here.
Does this already exist?
If so, console.log already there!
Otherwise, we can create it if the directory doesn't exist.
So let's just cut and paste this into the else condition.
And now if we try to run this again,
it'll say already there!
But if we were to delete this directory
and try to run it again,
it'll say directory created, and we see it here.
So everything seems to be working appropriately.
We've used a combination of mkdir and existsSync
to validate that the folder doesn't exist.
And if it doesn't exist, then we'll create it.