Skip to content
Advertisement

Read all .md files, convert them to html and send them

I use fs to read the file which is in .md format and I want to transform it into html file.

This is my code so far:

JavaScript

the file is situated in that folder and has that name.

This function puts in console the content of the .md file.

For converting it to html I added this:

JavaScript

It puts the file as html in the log which is fine.

My problem is how to do this if there are multiple files in /posts/ folder, how to read and send those files?

I would like to send them to front-end using a POST method.

Is it possible to read all the files from the folder, transform them and send them?

Advertisement

Answer

It seems from the comment thread below the question that you want something that does the following:

  • Converts all markdown files from a given directory to HTML
  • Sends them all in a single request
  • Is usable in a single-page app

Here’s an approach that fulfils all of these requirements. The HTML of each post is inserted into a template element, the content of which can be cloned and manipulated within the SPA script.

server.js

JavaScript

public/spa.js

JavaScript

glitch.me demo

Source | Live

Limitations

  • The conversion is done on-the-fly. If you have heavy traffic, you’ll want to implement some caching, or perhaps simply save the HTML versions separately, and trigger updates to them whenever the corresponding Markdown is edited.
  • The current code is probably not XSS safe — this assumes that either the content/filenames of posts are trusted, or that you carry out proper sanitation where required.
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement