// app.js or where-ever 'app' and 'express' vars are assigned
const
fs = require('fs-extra'),
path = require('path'),
marked = require('marked');
// Web site is in ./www from this js file
const commonSiteDir = __dirname +'/www';
// Given a valid path to .md file - converts it to HTML and sends to requester
var markdown = function (req, res, next) {
// look in the web site /docs sub directory
var mdfile = commonSiteDir + '/docs' + req.url;
var ext = path.extname(req.url);
// Only interested in files with no or .md extension
if (!(ext === '' || ext === '.md')) return next();
// If .md and found - sweet!
// If found by adding .md extension - sweet!
// If found the default .md file - sweet!
// Otherwize - we are outta here - call next express route
if (ext === '.md' && fs.existsSync(mdfile)) () => {}; // noop
else if (fs.existsSync(mdfile + '.md')) mdfile += '.md';
else if (fs.existsSync(mdfile + '/index.md')) mdfile += '/index.md';
else return next();
// Sweet! Markup the file
fs.readFile(mdfile, 'utf8', (err, data) => {
if (err) return next(err);
var markedup = marked(data);
var page =
'<!doctype html><html lang="en"><head><meta charset="utf-8">' + // <title>The HTML5 Herald</title>
'<link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Tangerine">' +
'<link rel="stylesheet" type="text/css" href="/docs/css/markdown.css?v=1.0">' +
'</head><body>' +
markedup +
'</body></html>';
res.send(page);
});
};
// Tell express to give markdown a try first on requests to https://domain.com/docs/blahblah
app.use('/docs', markdown);
// Got here if not a markdown file so let express.static try to find the file
// for example the css sheet in /docs/css/markdown.css - see the marked up page above
app.use('/docs', express.static(commonSiteDir + '/docs'));
----------------------------
In '/docs/markdown.css'
----------------------------
body {
background-color: aliceblue;
font-family: 'Tangerine', serif;
font-size: 24px;
}
----------------------------
Last active
October 9, 2018 08:04
-
-
Save PotOfCoffee2Go/667f599fe03599a8d145dda5bbd6f67e to your computer and use it in GitHub Desktop.
Quick express server middleware to convert .md files to .html page
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment