Now that we know
how "getStaticProps" works,
let's go back to our original plan,
that was to load the post data
from this Markdown file.
To take one step at a time,
in this video we'll focus
only on how to read a file,
and leave parsing the Markdown for later.
So for now let's assume
we want to load the data from a JSON file
called "first-post.json".
This will contain a JSON object
with our post details,
that is the title,
and the body,
that for now can be some simple text
but let's write that this is
"in a JSON file",
so we'll see something different
when we load this data.
Ok. Starting with a JSON file
simplifies our task a little bit,
in that now we just need to figure out
how to read a file from this code.
Now, if this code was meant
to run inside the browser
it wouldn't really be possible
to read a local file
that's inside our project.
But remember that the "getStaticProps" function
runs on the server,
which really means in Node.js,
so in our function we can use
any the APIs provided by Node.js.
And Node.js provides a module
call "File system, or "fs" for short,
which includes a function
called "readFile",
that does exactly what the name says.
So let's see how to use
this function in our code.
First we want to import that function
from the 'fs' module,
and I'll use the "promises" variant
that's more convenient.
So that module should contain
a function named "readFile".
Now we can call "readFile" here
and we want to pass it
the path to the file,
which is under the "content"
and then "posts" folders
inside our project.
so the path is "content/posts"
"/first-post.json".
And this is relative to the project folder
because that's where the server runs.
We also need to pass a second argument
with the character encoding,
in this case "utf8".
Now, this function returns
the data inside that file,
but it's asynchronous
so we need to "await" the result.
Let's quickly log the data,
so we can see exactly
what that function returns.
Let me show the server logs,
and if we reload this page
you can see that the "data"
is in fact the content of the JSON file,
as we expected.
Ok. So at this point we can
get the "post" details
simply by parsing that JSON data.
and that "post" object is what
we want to return in our props,
instead of these hard-coded values.
Let's see if this works.
I'll show the server logs as well.
And if we reload the page now,
we can see that it displays
"My first post, in a JSON file",
so it's clearly reading the data from the file.
Of course the server logs
printed the same data.
Let's stop here for this video.
This is how we can read data from a local file.
But, perhaps more importantly,
we've also seen that
in our "getStaticProps" function
we can use any of the functionality
provided by Node.js.
Because this code only runs on the server.