- [Male Instructor] So the file system module
can also be used to create new files
and write data to files.
In this lesson, we're going to look at the write file method
that's provided with the file system module.
I'm going to come over here to my start folder
and create a new file called "writefile.js".
And within the writefile.js,
the first thing we're going to do is require the file system.
So we're going to require our fs module.
And then the next thing we're going to need is some text.
We will write some text to a file,
so I'll just go ahead and create some markdown text,
using a template string so that we honor the white space.
And we'll say, "this is a new file."
So we can write text to a file with fs writefile.
So, so far we have learned fs.readdir, fs.readfile,
and now we're going to learn fs.writefile.
So I'll just jot these down as notes within our markdown.
So let's say I wanted to write this to a new file.
I'll just use fs.writefile
and we can do this asynchronously.
There is a writefile sync function that you can use
if you wanted to write this file synchronously.
And then we need to supply the file path.
So we are going to write to assets/notes.md.
The second argument of writefile
is the text that we want to use.
So I'll just take our markdown, and I will trim it,
just to get rid of those leading and trailing spaces.
The third argument is a callback function,
which will be invoked
once the notes md file has been created,
and the contents have been written to that file.
Now this function will only take in an error
as an argument because there's no data to pass back
to this callback.
So again, if any errors occur,
I'll handle this a little more simply this time,
by throwing the errors.
And that will cause new js to stop processing
and we will see that error in the terminal if it occurs.
I'm going to go ahead and console log file saved.
Great, so let's go ahead and save this,
and then open up our terminal and give it a run.
Node write file, and when we do this,
we see that it says file saved.
If I go and look within the assets directory,
we should see a new file.
There's a file called notes md
and when I open it up, we can see the contents
that we have written to that file.