dynamic-content
Version:
dynamic content functionality for roots
101 lines (82 loc) • 2.33 kB
JavaScript
// Generated by CoffeeScript 1.9.1
(function() {
var BR, FRONTMATTER_REGEXP, LINEBREAK_REGEXP, W, _, detect, detect_file, fs, nodefn, path, read, readFile, readdir, yaml;
fs = require('fs');
path = require('path');
W = require('when');
nodefn = require('when/node');
yaml = require('js-yaml');
_ = require('lodash');
BR = "(?:\\\r\\\n|\\\n|\\\r)";
LINEBREAK_REGEXP = new RegExp(BR);
FRONTMATTER_REGEXP = new RegExp(RegExp("^---\\s*" + BR + "([\\s\\S]*?)" + BR + "?---\\s*" + BR + "?"));
/**
* Read the first three bytes of each file, if they are '---', assume
* that we're working with dynamic content.
*
* @private
*
* @param {File} file - vinyl-wrapped file instance
* @return {Boolean} promise returning true or false
*/
detect = function(str) {
if (str.split(LINEBREAK_REGEXP)[0] === '---') {
return true;
} else {
return false;
}
};
detect_file = function(path) {
var deferred, res;
deferred = W.defer();
res = false;
fs.createReadStream(path, {
encoding: 'utf-8',
start: 0,
end: 3
}).on('error', deferred.reject).on('end', function() {
return deferred.resolve(res);
}).on('data', function(data) {
if (detect(data)) {
return res = true;
}
});
return deferred.promise;
};
read = function(str) {
var data, front_matter_str;
if (!detect(str)) {
return false;
}
front_matter_str = str.match(FRONTMATTER_REGEXP);
data = yaml.safeLoad(front_matter_str[1]);
data.content = str.replace(front_matter_str[0], '');
return data;
};
readFile = function(path) {
return nodefn.call(fs.stat, path).then(function(res) {
if (res.isDirectory()) {
return false;
}
return detect_file(path).then(function(res) {
if (!res) {
return false;
}
return nodefn.call(fs.readFile, path, 'utf8').then(read);
});
});
};
readdir = function(dir) {
return nodefn.call(fs.readdir, dir).then(function(paths) {
return W.map(paths, function(p) {
return readFile(path.join(dir, p));
});
}).then(_.compact);
};
module.exports = {
read: read,
readFile: readFile,
readdir: readdir,
detect_file: detect_file
};
}).call(this);