Skip to content

Instantly share code, notes, and snippets.

@der-On
Created January 29, 2016 21:58
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save der-On/1d97500a38aab5f8ebd3 to your computer and use it in GitHub Desktop.
Save der-On/1d97500a38aab5f8ebd3 to your computer and use it in GitHub Desktop.
Express middleware to create a dynamic HTML page using metalsmith.
'use strict';
var metalsmith = require('metalsmith');
var layouts = require('metalsmith-layouts');
var fs = require('fs');
var lorem = fs.readFileSync('./lorem.txt', 'utf8');
var n = 0;
// generates a single page
function generate(files, metalsmith, callback) {
n++;
files['index.html'] = {
title: 'Item ' + n,
path: 'index.html',
contents: new Buffer('<h1>Item ' + n + '</h1><pre>' + lorem + '</pre>')
};
callback();
}
module.exports = function () {
// prepare a metalsmith instance
var ms = metalsmith(__dirname)
.source('./src')
.destination('./build')
.use(generate)
.use(layouts({
directory: './layouts',
default: 'page.html',
engine: 'ejs'
}));
return function (req, res, next) {
ms.run({}, function (err, files) {
if (err) {
next(err);
return;
}
res
.type('html')
.end(files['index.html'].contents.toString(), 'utf8');
});
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment