jhan.com.au/build.js

62 lines
1.9 KiB
JavaScript

const fs = require('fs');
const readline = require('readline');
const src_dir = 'src';
const build_dir = 'build';
const files = ["src/index.html",
"src/about.html",
"src/projects/2016-XXXX.html",
"src/projects/2023-Pepperstone.html"]; // this list should be generated.
files.forEach( file => {
var file_buffer = "";
const rl = readline.createInterface({
input: fs.createReadStream(file),
output: process.stdout,
terminal: false
});
const re_include = new RegExp('{% include \'*(.*)\' %}');
const re_picture = new RegExp('{% picture.*%}');
rl.on('line', line => {
const match_include = line.match(re_include);
const match_picture = line.match(re_picture);
if (match_include) {
line = line.replace(re_include, fs.readFileSync(match_include[1], 'utf8'));
}
if (match_picture) {
const re_src = new RegExp("src=[\'\"](.*?)[\'\"]");
const picture_src = match_picture[0].match(re_src)[1].split('/').slice(1).join('/');
const re_alt = new RegExp("alt=[\'\"](.*?)[\'\"]");
const alt = match_picture[0].match(re_alt)[1];
ensureDirectoryExists(build_dir + '/' + picture_src);
fs.cp(src_dir + '/' + picture_src, build_dir + '/' + picture_src, { recursive: false }, (err) => {
if (err) throw err;
});
line = line.replace(re_picture, "<img src=\'/" + picture_src + "\' alt=\'" + alt + "\' \>");
}
file_buffer += line;
});
rl.on('close', () => {
ensureDirectoryExists(build_dir + '/' + file.split('/').slice(1).join('/'));
fs.writeFileSync(build_dir + '/' + file.split('/').slice(1).join('/'), file_buffer, 'utf8');
});
});
fs.cp('./src/styles','./build/styles', { recursive: true }, (err) => {
if (err) throw err;
});
function ensureDirectoryExists(filePath) {
var dirname = filePath.split('/').slice(0,-1).join('/');
if (fs.existsSync("./" + dirname)) {
return true;
}
ensureDirectoryExists(dirname);
fs.mkdirSync(dirname);
}