Skip to content

Instantly share code, notes, and snippets.

@jdmichaud
Created April 19, 2018 13:24
Show Gist options
  • Save jdmichaud/fb3d639ce935585f55e56d8c0b242675 to your computer and use it in GitHub Desktop.
Save jdmichaud/fb3d639ce935585f55e56d8c0b242675 to your computer and use it in GitHub Desktop.
A tiny markdown web renderer
// npm install express highlight.js marked morgan mustache
const fs = require('fs');
const express = require('express');
const morgan = require('morgan');
const marked = require('marked');
const highlight = require('highlight.js');
const Mustache = require('mustache');
const config = {
host: '127.0.0.1',
port: 9500,
};
const template = `
<!DOCTYPE html>
<html>
<head>
<title>{{ metadata.title }}</title>
<link rel="stylesheet" href="/pixyll-like.css">
<!-- highlighter -->
<link rel="stylesheet"
href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/styles/default.min.css">
<!-- Fonts -->
<link href="//fonts.googleapis.com/css?family=Merriweather:900,900italic,300,300italic" rel="stylesheet" type="text/css">
<link href="//fonts.googleapis.com/css?family=Lato:900,300" rel="stylesheet" type="text/css">
</head>
<body>
{{{ content }}}
</body>
</html>
`;
marked.setOptions({
renderer: new marked.Renderer(),
highlight: (code, lang) => {
if (lang) {
return highlight.highlight(lang, code).value;
}
return highlight.highlightAuto(code).value;
},
// highlight: code => highlight.highlightAuto(code).value,
pedantic: false,
gfm: true,
tables: true,
breaks: false,
sanitize: false,
smartLists: true,
smartypants: false,
xhtml: false,
});
const app = express();
app.disable('x-powered-by');
app.use(morgan('combined'));
// Error management
app.use((err, req, res, next) => {
console.error('Error:', err.stack);
next(err);
});
app.use((err, req, res, next) => { // eslint-disable-line
res.status(500).send({ error: 'Server Error' });
});
// Routes
app.get('/*', (req, res, next) => {
const filename = req.url.match('/?(.*)')[1];
console.log(`requesting ${filename}`);
const file = fs.readFileSync(filename).toString('utf-8');
res.send(Mustache.render(template, {
content: marked(file),
}));
res.sendStatus(200);
});
app.listen(config.port, config.host, () => {
console.log(`server listening on http://${config.host}:${config.port}/`);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment