Skip to content

Instantly share code, notes, and snippets.

@beardedtim
Created January 1, 2019 20:11
Show Gist options
  • Save beardedtim/4c40c1cb035defb95c8755b69cdc001b to your computer and use it in GitHub Desktop.
Save beardedtim/4c40c1cb035defb95c8755b69cdc001b to your computer and use it in GitHub Desktop.
Create Markdown Posts for All markdown files in directory
const fs = require('fs')
const path = require('path')
const cheerio = require('cheerio')
const markdown = require('markdown-it')
const highlightjs = require('highlight.js')
const metaMD = require('markdown-it-meta')
const parser = markdown({
highlight: function (str, lang) {
if (lang && highlightjs.getLanguage(lang)) {
try {
return '<pre class="hljs"><code>' +
highlightjs.highlight(lang, str, true).value +
'</code></pre>';
} catch (__) { }
}
return '<pre class="hljs"><code>' + parser.utils.escapeHtml(str) + '</code></pre>';
},
html: true,
typographer: true
})
parser.use(metaMD)
fs.readdir(path.resolve(__dirname, 'blog'), (err, files) => {
const templatePath = files.find(f => f.indexOf('html') > -1)
const markdownPosts = files.filter(f => f.indexOf('md') > -1)
fs.readFile(path.resolve(__dirname, 'blog', templatePath), 'utf8', (err, template) => {
markdownPosts.forEach(filePath => {
fs.readFile(path.resolve(__dirname, 'blog', filePath), 'utf8', (err, post) => {
const postHTML = parser.render(post)
const $ = cheerio.load(template)
const $postBody = $('#markdown-content')
$postBody.html(postHTML)
if (parser.meta) {
if ("title" in parser.meta) {
$("head").append(`<title>${parser.meta.title} | beardedtim | i rant about stuff</title>`)
} else {
$("head").append(`<title>Another Non-Titled Post | beardedtim | i rant about stuff</title>`)
}
if ("description" in parser.meta) {
$("head").append(`<meta name="description" content="${parser.meta.description}" />`)
}
if ("keywords" in parser.meta) {
$("head").append(`<meta name="keywords" content="${parser.meta.keywords}" />`)
}
if ("author" in parser.meta) {
$("head").append(`<meta name="author" content="${parser.meta.author}" />`)
}
}
fs.writeFile(path.resolve(__dirname, 'public', 'blog', filePath.replace('.md', '.html')), $.html(), (err) => {
if (!err) {
console.log('Did it', path.resolve(__dirname, 'public', 'blog', filePath))
} else {
console.log(err)
process.exit(1)
}
})
})
})
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment