#web development
#programming
#nodejs

How to Create a Markdown Files in Node.js?

Anonymous

AnonymousOct 06, 2023

How to Create a Markdown Files in Node.js?

Here's a basic Node.js script that generates single Markdown file:

Source Code

import fs from 'fs'
const mdFileName = `example.md`
const frontMatters = `---
title: My Markdown Document
date: 2023-10-07
author: John Doe
permalink: page-1
---
`
fs.writeFileSync("./pages/" + mdFileName, frontMatters)

Ouput:

pages/example.md

---
title: My Markdown Document
date: 2023-10-07
author: John Doe
permalink: page-1
---

If you want to generate multiple Markdown files in a Node.js script, you can use a loop to create. Here's an example of how you can modify the script to generate multiple Markdown files:

Source Code

import fs from 'fs'
let noOfpages = [1, 2, 3, 4, 5]
for (let i = 0; i < noOfpages.length; i++) {
  const num = noOfpages[i];
  const mdFileName = `page-${num}.md`
  const frontMatters = `---
title: My Markdown Document
date: 2023-10-07
author: John Doe
permalink: page-${num}
---
`
fs.writeFileSync("./pages/" + mdFileName, frontMatters)
}

In this example, we're using the built-in fs module in Node.js to create a Markdown files.

Next, In this example, Each file has a name that includes a page number, such as "page-1.md," "page-2.md," and so on. these files are stored in a folder called "pages" . you can change the file name and folder name as needed.

You can also update markdown content.

Finally, we use the fs.writeFile() method to write the Markdown content to the file.

To run this script, save it to a file with a .js extension (e.g., generateMarkdown.js), and execute it using Node.js:

node generateMarkdown.js

Ouput:

example-screenshot

Happy Coding! ❤️