Skip to content

Instantly share code, notes, and snippets.

@teramako
Created November 1, 2012 14:12
Show Gist options
  • Save teramako/3993843 to your computer and use it in GitHub Desktop.
Save teramako/3993843 to your computer and use it in GitHub Desktop.
Markdown ファイルを HTML 出力するやつ
/**
* Markdown generator
* @example
* node markdown.js <file.md> [ file.md ... ]
*/
const fs = require("fs"),
libxml = require("libxmljs"),
pagedown = require("pagedown");
const markdown = new pagedown.Converter;
process.argv.slice(2).forEach(function(aFile) {
initFile(aFile);
});
function initFile (aFile) {
fs.readFile(aFile, "utf-8", function(aError, aData) {
if (aError)
throw aError;
var html = convert(aData, domConverter);
output(aFile, html);
});
}
const XML_HEADER = '<html><head></head><body>',
XML_FOOTER = '</body></html>';
function convert (aData, aConverter) {
var html = XML_HEADER + markdown.makeHtml(aData) + XML_FOOTER;
// console.log(html);
var doc = libxml.parseHtmlString(html);
return aConverter(doc);
}
function domConverter (aDocument) {
var root = aDocument.root(),
body = root.child(1);
var title, isHeading = false;
var sections = [];
body.childNodes().forEach(function(aElement) {
switch (aElement.name()) {
case "h1":
if (!title)
title = aElement.text();
isHeading = true;
case "h2":
case "h3":
sections.push({title: aElement.toString(), body: "", isHeading: isHeading});
isHeading = false;
break;
case "hr":
sections.push({title: "", body: ""});
break;
default:
sections[sections.length - 1].body += aElement.toString() + "\n";
}
});
var html = [
'<!DOCTYPE html>',
'<html xmlns="http://www.w3.org/1999/xhtml">',
'<head>',
' <meta charset="utf-8"/>',
' <title>' + title + '</title>',
'</head>',
'<body>'
].concat(
sections.map(function(aSection, i) {
return '<section id="' + (i+1) + '" class="page' + (aSection.isHeading ? " title": "") + '">\n' +
aSection.title + "\n" +
' <div class="sectionBody">\n' +
aSection.body.trim() + "\n" +
' </div>\n' +
'</section>';
}),
['</body>', '</html>']
).join("\n");
return html;
}
function output (aFile, aHTML) {
var file = aFile.replace(/\.md$/, ".xhtml");
fs.writeFile(file, aHTML, function (aError) {
if (aError)
throw aError;
console.log("%s -> %s: success !!", aFile, file);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment