l0bsterssg

node.js static responsive blog post generator
Log | Files | Refs | README

index.js (1614B)


      1 
      2 
      3 const path = require('path');
      4 const mkdirp = require('mkdirp');
      5 const marked = require('marked');
      6 const matter = require('gray-matter');
      7 const glob = require('glob');
      8 const fs = require('fs');
      9 
     10 
     11 const readFile = (filename) => {
     12 	const rawFile = fs.readFileSync(filename, 'utf8')
     13 	const parsed = matter(rawFile)
     14 	const html = marked(parsed.content)
     15 
     16 	return { ...parsed, html }
     17 }
     18 
     19 const templatize = (template, { date, title, content }) =>
     20 	template
     21 		.replace(/<!-- PUBLISH_DATE -->/g, date)
     22 		.replace(/<!-- TITLE -->/g, title)
     23 		.replace(/<!-- CONTENT -->/g, content)
     24 
     25 const saveFile = (filename, contents) => {
     26 	const dir = path.dirname(filename)
     27 	mkdirp.sync(dir)
     28 	fs.writeFileSync(filename, contents)
     29 }
     30 
     31 const getOutputFilename = (filename, outPath) => {
     32 	const basename = path.basename(filename)
     33 	const newfilename = basename.substring(0, basename.length - 3) + '.html'
     34 	const outfile = path.join(outPath, newfilename)
     35 	return outfile
     36 }
     37 
     38 const processFile = (filename, template, outPath) => {
     39 	const file = readFile(filename)
     40 	const outfilename = getOutputFilename(filename, outPath)
     41 
     42 	const templatized = templatize(template, {
     43 		date: file.data.date,
     44 		title: file.data.title,
     45 		content: file.html,
     46 	})
     47 
     48 	saveFile(outfilename, templatized)
     49 	console.log(`📝 ${outfilename}`)
     50 }
     51 
     52 const main = () => {
     53 	const srcPath = path.resolve('src')
     54 	const outPath = path.resolve('dist')
     55 	const template = fs.readFileSync(path.join(srcPath, 'template.html'), 'utf8')
     56 	const filenames = glob.sync(srcPath + '/pages/**/*.md')
     57 
     58 	filenames.forEach((filename) => {
     59 		processFile(filename, template, outPath)
     60 	})
     61 }
     62 
     63 main()