2012-01-19 03:01:17 +11:00
|
|
|
var FS = require('fs');
|
|
|
|
var Path = require('path');
|
|
|
|
var Markdown = require('markdown').markdown;
|
|
|
|
|
|
|
|
// This function is used to map wiki page names to files
|
|
|
|
// on the real filesystem.
|
|
|
|
function pathFromName(name) {
|
|
|
|
return Path.join(__dirname, "pages", name + ".markdown");
|
|
|
|
}
|
|
|
|
|
2012-01-19 04:42:29 +11:00
|
|
|
// Load a file, parse the title and generate the HTML
|
2012-01-19 03:01:17 +11:00
|
|
|
exports.loadPage = function (name, callback) {
|
|
|
|
var path = pathFromName(name);
|
2012-01-19 04:42:29 +11:00
|
|
|
|
2012-01-19 03:01:17 +11:00
|
|
|
FS.readFile(path, 'utf8', function (err, markdown) {
|
2012-01-19 04:42:29 +11:00
|
|
|
|
2012-01-19 03:01:17 +11:00
|
|
|
var exists = true;
|
|
|
|
if (err) {
|
|
|
|
if (err.code === "ENOENT") {
|
2012-01-19 04:42:29 +11:00
|
|
|
// Generate a placeholder body.
|
|
|
|
markdown = "# " + name.replace(/_/g, " ") +
|
|
|
|
"\n\n" + "This page does not exist yet.";
|
2012-01-19 03:01:17 +11:00
|
|
|
exists = false;
|
|
|
|
} else {
|
2012-01-19 04:42:29 +11:00
|
|
|
// Forward on all other errors.
|
2012-01-19 03:01:17 +11:00
|
|
|
return callback(err);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2012-01-19 04:42:29 +11:00
|
|
|
// Parse and render the markdown.
|
2012-01-19 03:01:17 +11:00
|
|
|
var tree = Markdown.parse(markdown);
|
|
|
|
var title = name;
|
|
|
|
for (var i = 1, l = tree.length; i < l; i++) {
|
|
|
|
if (tree[i] && tree[i][0] === "header") {
|
|
|
|
title = tree[i][2];
|
|
|
|
tree.splice(i, 1);
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
var html = Markdown.toHTML(tree);
|
|
|
|
|
|
|
|
callback(null, {
|
|
|
|
name: name,
|
|
|
|
title: title,
|
|
|
|
exists: exists,
|
|
|
|
markdown: markdown,
|
|
|
|
html: html,
|
|
|
|
});
|
2012-01-19 04:42:29 +11:00
|
|
|
|
2012-01-19 03:01:17 +11:00
|
|
|
});
|
|
|
|
};
|
|
|
|
|
|
|
|
// Saving is simple. Just put the markdown in the file
|
|
|
|
exports.savePage = function (name, value, callback) {
|
|
|
|
var path = pathFromName(name);
|
|
|
|
FS.writeFile(path, value, callback);
|
|
|
|
};
|