Welcome back.
In this video, let's see how we can read content from a file for FS two.
We can write the code in synchronous way, meaning a code that blocks other code from running, or we
can read it in asynchronous way.
So let me show you how we can write this one synchronously.
So fs dots read.
File sync as a function and all.
What I need is to pass in the file that I want to read, so I'll pass in the about as dot pdf.
So with this one, let's assign the result coming back after this function as result now equal to that.
So now let's console.log the results and see if we are going to see the content in the console.
Let's run it where I have some error.
It means that this file has been already been declared.
Yes.
So let me comment this one.
Now, let me run the application, save it and now let's run again.
Let me play my console here and let's run it.
And now you can see that it has given me a buffer, so I need to convert it to a string.
Right?
So to string, you're going to give me the actual contents on the file, so save it and now have a look.
And indeed we have the content say that this is my first PDF file created and that is what is on the
file.
So how can we write this one using callback?
The difference here is the method or the function is no more read file saying, but instead read file.
So let me comment this one out and likewise this one out.
And come down here, I'm going to be f s dot read file and then as usual you pass in the file you want
to read.
That is about as dot pdf and the next segment is going to be the callback function.
So here is my callback function.
It can be error function or normal function and this function we have access to error and the actual
data and here we go.
So I'm going to check if there are some error, then we can go ahead and then console that, log the
error.
Otherwise down here we can console.log the actual data.
So let's run the application, click the console and now run it.
And indeed it's also gives us a buffer, meaning that the contents are being read bit by bit.
So let's convert the buffer into the actual string by using dot to string.
Is that so now?
Save it, clear the console.
And run again.
And indeed we have.
This is my first five created.