- You may need to move,
rename or remove a file.
The file system module has methods for that as well.
Let's go into our start folder and create a new file
called "rename.js."
The first thing I'm going to do is require the fs module
and the rename method has both a
synchronous and an asynchronous
version so "fs.renameSync" is the synchronous version
and I'll use that to rename a file.
I'm going to go ahead and rename the colors.json file
within my assets folder,
so the first argument is the path to the colors.json file.
That's the file that I want to rename and the second
argument is going to be the new name.
We'll call it colorData.
There's also an asynchronous version to the rename function,
and you can also use the rename function to move files.
So I'm going ahead and select the "./assets/notes.md"
and I can move that file simply by renaming the path,
so "./storage-files/notes.md."
As always,
with the asynchronous function,
the last argument is going to be the call back.
So if there are any errors,
return to this callback function,
I'm just going to go ahead and throw them.
Great, so running this code will rename one file
and move another file.
I'm also going to add a setTimeout in the first argument.
setTimeout is the function that I
want to invoke after four seconds.
So the second argument is four thousand milliseconds,
which is four seconds.
So what I want to do is wait four seconds
and then after four seconds I'm going to remove
a file by calling "fs.unlink."
Unlink has a synchronous version and
an asynchronous version,
we'll go ahead and use the synchronous version.
And all we need to do is send the file
that we would like to remove.
So the file that I'm going to go ahead and remove
is going to be "./assets/alex.jpg."
Great, so now when we save this
we're preforming three file operations.
One, we're renaming the colors.json to colorData.
Two, we're moving the notes.md into
the storage files folder.
And three, we're going to wait four seconds and...
Delete Alex with an "x".jpg.
So let's go ahead and open up our terminal.
So now I can go ahead and run this,
I'll call "node rename."
And the first thing you notice is the color file
is now called colorData.
We also have a process that ran for four seconds,
and you can see that "Alex.jpg" disappeared
from our assets folder after about four seconds.
And the third thing we did was move the
notes file out to the storage files.
So we can see that our "notes.md" from earlier
in this chapter has been moved from the assets folder
to the storage folder.
So the fs module really contains every method that
you will need to work competently with your file system.