How can I have an express endpoint return a README.md file?

Issue

I have an express server and I am trying to render my readme at the ‘/’ endpoint. I am looking to simply display the file contents (like github does). I cannot find a straightforward method, i guess to render this as html? Express doesn’t seem to support md files.

Currently, I am having issues using the following:

const readme = require('../README.md');

app.get('/', function(req, res) {
  res.send(readme)
});

With the error:

README.md:1
# Express API
^
SyntaxError: Invalid or unexpected token

Which is pointing at the first line of the file.

Solution

Thanks to TD3V for pointing in the right direction!

Check out this question stackoverflow.com/questions/27971806/…

While this wasn’t a complete solution (As It isn’t mentioned but I forgot to install Marked and require it, doh), it is one of them.

const fs = require('fs'); 
const { marked } = require('marked');

app.get('/', function(req, res) {
  var readme = '../README.md';
  var output = fs.readFileSync(readme, 'utf8');
  res.send(marked(output.toString()));
});

The other solution pointed out by bill.gates:

require() does not work like this. You can read the file and send the content:

const fs = require("fs");

app.get('/', function(req, res) {
   fs.readFile("../README.md", "utf-8", (err, result) => {
      res.send(result);
   });
});

And while this also works, it is a bit janky with formatting. Thanks guys!

Answered By – swamptiger24

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published