- [Instructor] Node.js also ships with a module
that allows us to interact with the file system.
The Fs module can be used to list files and directories,
create files and directories, stream files,
change file permissions, and really just about anything
you'd need to work with files and directories.
To get started, we want to go over to this empty file
called list.js and we want to create an import.
So we'll say require fs.
From here we're going to create a variable called files.
That's going to help us read files into a variable.
So we'll say fs.readdirSync and we want to read
from the directory that we're currently in.
Now, if we console log these files
and we save and run node list,
this is going to give us an array
of all of the files that are listed here.
Notice that when I read the directory,
I used a function called read dir sync.
This means that I read the contents of this directory
synchronously with a blocking request.
Meaning that I'm blocking the rest of the process
until the file is read.
Now, when we use any methods of the file system module,
we are given the option to use them
synchronously or asynchronously.
So because we're blocking here,
a way that we could do this differently
is I could say read dir, we'll still read from the same spot
but this time we're going to pass in a callback function.
We'll say error files.
Now, if there's some sort of error,
we want to throw an error,
otherwise we'll simply log the files.
So check this out.
I'll give it a save.
I'll get rid of my other console message.
And I also want to get rid of the variable
that I created here.
So now what we can do run node list again
and our results will be exactly the same.
When our app is already running,
it's really nice to use these asynchronous requests
so that the process can do other things
while your file or directory is being read.
Now, we also want to, just to prove that this is working,
we'll console log reading files.
Node list.
Reading files will happen first
when we're ready reading the files,
we'll log the rest here to the console after.