Creating Markdown files from a template is a straightforward process with Node.js and Mustache. You can define a template, load it into your script, then push whatever data you have into your template, then write the files back out. Node.js built-in filesystem tools allow you to read and write the files while Mustache helps you to push the data into the template.
Instructor: [00:00] npm install mustache. Then we can grab render off of Mustache. I can define a template like name is age years old, and an object, so person name john, and age 37, and use render from Mustache to render the template from the person data.
[00:33] The output of this will be John is 37 years old, because it grabs the data off of the person, the name, the age, and drops them wherever it finds those double curly braces.
[00:46] To write that to a file, we'll bring in the file system tools, require('fs'), and then define this as our output, and then fs.writeFileSync, the name of the file, which we'll just call person.md, and the data to write to the file, which is output.
[01:06] I'll go ahead and run this with Node index.js. You can see we have our person.md here with the text that we wanted.
[01:16] If I grab a lot more data -- I'll grab this array of people -- and paste that into my JavaScript file, I'm going to fold this so it doesn't take up my entire view here. Instead of one person, I can take the people and forEach on them. I'll get a person from there.
[01:37] With this person, I'm going to drop that into my template, and I'm going to make my template a bit more Markdown-y. We'll say that can be a header and as eye color eyes, because eye color is one of the variables on my people here.
[01:58] To write the file, I'll bring in my writeFileSync. I'm going to replace this with a path to a people folder, and then the name of the file, which comes from the person.name. The extension can still be .md. Let's go ahead and create that people folder.
[02:17] Now when I run Node index and check my people folder, you'll see I have Markdown files for each person from that array.
[02:28] Finally, we can also extract this template into its own file. Let's create a template.md. I'll say this is the name as eye color eyes and hair color hair. I can read in my template with readFileSync, and I'll just read in template.md. Then I need to invoke toString on it.
[03:02] Now when I run Node index and check my people folder, I have all the files with the names, and eye color, and hair colors. We're reading in this template, looping through all the people, and populating it with the data from that person, and then writing it back out to a new file.