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

Time:09-01

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.

CodePudding user response:

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);
   });
});

CodePudding user response:

According to send() the documentation:

res.send([body])

Sends the HTTP response.
The body parameter can be a Buffer object, a String, an object, Boolean, or an Array.

You are probably looking for sendFile().

res.sendFile(path [, options] [, fn])

Transfers the file at the given path. Sets the Content-Type response HTTP header field based on the filename’s extension. Unless the root option is set in the options object, path must be an absolute path to the file.

CodePudding user response:

var data =fs.readFileSync('./public/modules/datacollectors/output.pdf');
res.contentType("application/pdf");
res.send(data);

I think you can find your answare in this thread: How to send a pdf file Node/Express?

CodePudding user response:

use marked npm package Link

If you want to return a file content then we have to read the file and then we use marked package

 app.get('/' (req,res)=>{
     let filePath = __dirname   '/test.md';
     let file = fs.readFileSync(filePath, 'utf8');
     res.send(marked(file.toString()));
 })

CodePudding user response:

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!

  • Related