kulfon
Version:
Kulfon is a modern static site generator written in JavaScript.
51 lines (45 loc) • 1.47 kB
JavaScript
const Promise = require('bluebird');
const path = require('path');
const fs = Promise.promisifyAll(require("fs-extra"));
const yaml = require('js-yaml');
const dataPath = path.join(__dirname, 'data');
function isObject(item) {
return (item && typeof item === 'object' && !Array.isArray(item) && item !== null);
}
function mergeDeep(target, source) {
if (isObject(target) && isObject(source)) {
for (let key in source) {
if (isObject(source[key])) {
if (!target[key]) Object.assign(target, { [key]: {} });
mergeDeep(target[key], source[key]);
} else {
Object.assign(target, { [key]: source[key] });
}
}
}
return target;
}
Promise.resolve().then(() => {
return fs.statAsync(dataPath)
.then(stats => stats.isDirectory())
.catch(err => false); // not directory, so parse `data.yml`
}).then(isDirectory => {
return isDirectory ?
{ content: fs.readdirAsync(dataPath), path: dataPath} :
{ content: ['data.yml'], path: __dirname };
}).then(directory => {
return {
files: directory.content.filter(f => fs.statSync(path.join(directory.path, f)).isFile()),
path: directory.path
}
}).then(yml => {
const content = yml.files.reduce((acc, x) => {
return [acc, fs.readFileSync(path.join(yml.path, x), 'utf8')].join('---\n');
}, '');
let data = {};
yaml.safeLoadAll(content, (doc) => {
data = mergeDeep(data, doc);
});
}).catch(err => {
console.log(err.message)
});