- [Instructor] The fs module can also be used
to write or append data to a file.
In this lesson, we'll take a closer look.
Let's create a new file here called writeFile
and we're going to import the file system module,
as you might expect.
And then we're going to create some Markdown.
So we're going to create a little template here.
We'll say let md equal,
we'll use a couple back ticks.
And then within this, we'll say this is a New File.
We'll underline this with equal signs for our header,
and we'll say ES6 Template Strings are cool.
They honor whitespace.
And then we'll add some bullets here.
So we'll say Template Strings,
Node File System,
and Readline CLIs.
Cool.
So now that I've created that,
I can create a new file,
and write the Markdown contents to this file.
So we'll do this here on line 14 with fs.writeFile.
Now, what writeFile is going to take in?
It needs to take in the name of the new file.
So we'll say javascript.md.
We will, for the second argument,
say what do we want to write to this file?
So we'll say md.trim
to trim off any extra white spaces from this string.
Then we're going to create a function.
And this callback function is going to log
that the Markdown was created.
Excellent.
So now if I try to run this with node writeFile,
we should see that the Markdown was created
but the Markdown has actually been created.
How cool is that?
We've added all of this text to our file.
Now let's use the appendFile method.
So we're going to use appendFileSync
to synchronously append to the file.
So add to the file.
Remember that all of our file system methods
have a synchronous version and an asynchronous version.
So in this particular version,
we'll use this inside of our callback function.
So let's do this first.
We'll say function error,
if there's an error,
we're going to throw that error.
Otherwise, we want to append something to our file.
So we'll say appendFileSync.
The file that we want to append to is right here.
Javascript.md.
And this time, we'll pass in a string
that we want to append.
We'll say n for new line, new line,
and then we'll say Node.js Everyone!
All right, cool.
So now let's try to write the file again.
We'll hit our up arrow.
We will open our javascript.md file and check it out,
we've added this little heading here.
A couple things to note.
The Markdown created message was added
to the terminal as well.
We wrote the file
and then we appended that content to our file.
So in this lesson, we created an appended text files
but know that you can also create
an append binary file as well.