How can I have an express endpoint return a file?


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('../');

app.get('/', function(req, res) {

With the error:
# Express API
SyntaxError: Invalid or unexpected token

Which is pointing at the first line of the file.


Thanks to TD3V for pointing in the right direction!

Check out this question…

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 = '../';
  var output = fs.readFileSync(readme, 'utf8');

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("../", "utf-8", (err, 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