JavaScript: HTML Generate Refactoring
10/17/15
My
htmlGenerate.js
script has gotten the same treatment as my
publish.js
script.
'use strict';
/*jslint node: true */
// Required modules
var fs = require('fs'),
path = require('path');
// Private functions
var saveFile = function (filename, data) {
fs.writeFile(filename, data, 'utf-8', function (err) {
if (err) {
throw err;
}
});
};
// Module functions
var htmlGenerate = exports;
htmlGenerate.populate = function (template, data) {
var cheerio = require('cheerio'),
{{post}}#xA0;= cheerio.load(data),
post;
post = (template
.replace(/\{\{content\}\}/g, $('#content,#temp').attr('id'))
.replace(/\{\{title\}\}/g, $('.title').text().trim())
.replace(/\{\{date\}\}/g, $('.date').text().trim())
.replace(/\{\{post\}\}/g, $('.blogpost').html().trim())
);
return post;
};
htmlGenerate.translateFile = function (filename, htmlname) {
fs.readFile('templates/post.html', 'utf-8', function (err, template) {
if (err) {
console.log(err);
return;
}
fs.readFile(filename, 'utf-8', function (err, data) {
var translatedData;
if (err) {
console.log(filename);
console.log(err);
return;
}
// Grab title, date, and blogpost
translatedData = htmlGenerate.populate(template, data);
saveFile(htmlname, translatedData);
});
});
};
htmlGenerate.translateDirectory = function (area, htmlArea) {
fs.readdir(area, function (err, files) {
if (err) {
console.log('%s\n%s', area, err);
return;
}
files.forEach(function (file) {
var relpath,
htmlpath;
relpath = path.join(area, file);
htmlpath = path.join(htmlArea, file);
htmlGenerate.translateFile(relpath, htmlpath);
});
});
};
htmlGenerate.main = function () {
// Get all the files in views/blog area
htmlGenerate.translateDirectory('views/blog', 'test/blog');
};
if (require.main === module) {
htmlGenerate.main();
}
It is now something I can properly
require
in the
publish.js
script. Which means soon I should be able to point
publish.js
at a view draft I want to publish, and it'll generate the proper html
file for me and put both the written file and the generated file in
their published-post areas (the
views
directory and the
public
directory, respectively).
After I get that working, I'll give
indexGenerate.js
the same treatment, and then generate the index file from
publish.js,
as well.
After that, I'd like to improve the draft system I have in place, such that the date, and some repeats of the title of the post, are done programmatically and not by hand.
Finally, I'll want to clean everything up. Good documentation, better naming convention, etc.
I guess I might also want to learn how to go about testing these scripts.
We'll see. I'll take it one step at a time.