How to use the hexo-front-matter.parse function in hexo-front-matter

To help you get started, we’ve selected a few hexo-front-matter examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github LouisBarranqueiro / hexo-algoliasearch / lib / initPost.js View on Github external
function initPost(post) {
  var cuid = require('cuid');
  var chalk = require('chalk');
  var green = chalk.green;
  var magenta = chalk.magenta;
  var red = chalk.red;
  var fs = require('fs');
  var frontMatter = require('hexo-front-matter');
  var id = cuid();
  /* eslint-disable camelcase */
  var filepath = post.full_source || post.path;
  /* eslint-enable camelcase */
  var file = fs.readFileSync(filepath, 'utf-8');
  var data = frontMatter.parse(file);
  
  /* eslint-disable camelcase */
  data.algolia_object_id = id;
  post.algolia_object_id = id;
  /* eslint-enable camelcase */

  try {
    fs.writeFileSync(filepath, frontMatter.stringify(data), 'utf-8');
    console.log(green('INFO  ') + 'Initialized: ' + magenta(post.path));
    return post;
  }
  catch (err) {
    console.log(red('ERROR  ') + 'Can\'t initialize ' + post.path + ' - ' + err);
  }
}
github jaredly / hexo-admin / update.js View on Github external
module.exports = function (model, id, update, callback, hexo) {
  function removeExtname(str) {
    return str.substring(0, str.length - path.extname(str).length);
  }
  var post = hexo.model(model).get(id)
  if (!post) {
    return callback('Post not found');
  }
  var config = hexo.config,
    slug = post.slug = hfm.escape(post.slug || post.title, config.filename_case),
    layout = post.layout = (post.layout || config.default_layout).toLowerCase(),
    date = post.date = post.date ? moment(post.date) : moment();

  var split = hfm.split(post.raw),
    frontMatter = split.data
    compiled = hfm.parse([frontMatter, '---', split.content].join('\n'));

  var preservedKeys = ['title', 'date', 'tags', 'categories', '_content', 'author'];
  Object.keys(hexo.config.metadata || {}).forEach(function (key) {
    preservedKeys.push(key);
  });
  var prev_full = post.full_source,
    full_source = prev_full;
  if (update.source && update.source !== post.source) {
    // post.full_source only readable ~ see: /hexo/lib/models/post.js
    full_source = hexo.source_dir + update.source
  }

  preservedKeys.forEach(function (attr) {
    if (attr in update) {
      compiled[attr] = update[attr]
    }
github 52cik / hexo-admin-cn / update.js View on Github external
module.exports = function (model, id, update, callback, hexo) {
  var post = hexo.model(model).get(id)
  if (!post) {
    return callback('Post not found');
  }
  var config = hexo.config,
    slug = post.slug = hfm.escape(post.slug || post.title, config.filename_case),
    layout = post.layout = (post.layout || config.default_layout).toLowerCase(),
    date = post.date = post.date ? moment(post.date) : moment();

  var split = hfm.split(post.raw),
    frontMatter = split.data
    compiled = hfm.parse([frontMatter, '---', split.content].join('\n'));

  var preservedKeys = ['title', 'date', 'tags', 'categories', '_content', 'keywords', 'description'];
  var prev_full = post.full_source,
    full_source = prev_full;
  if (update.source && update.source !== post.source) {
    // post.full_source only readable ~ see: /hexo/lib/models/post.js
    full_source = hexo.source_dir + update.source
  }

  preservedKeys.forEach(function (attr) {
    if (attr in update) {
      compiled[attr] = update[attr]
    }
  });
  compiled.date = moment(compiled.date).toDate()
github LouisBarranqueiro / hexo-algoliasearch / lib / initPosts.js View on Github external
async.forEach(filenames, function(filename, cb) {
      try {
        file = fs.readFileSync(filename, 'utf-8');
        data = frontMatter.parse(file);
        if (data.algolia_object_id) {
          cb();
        }
        else {
          /* eslint-disable camelcase */
          data.algolia_object_id = cuid();
          /* eslint-enable camelcase */
          fs.writeFileSync(filename, frontMatter.stringify(data));
          console.log(chalk.green('Initialized: ') + chalk.magenta(path.basename(filename)));
          modifiedFilesCount++;
          cb();
        }
      }
      catch (err) {
        console.log(chalk.red('Can\'t process ' + filename + ' file : ' + err));
      }
github xu-song / hexo-auto-category / lib / logic.js View on Github external
let logic = function(data) {
    var log = this.log;

    if (data.layout != 'post')
        return data;
    if (!this.config.render_drafts && data.source.startsWith("_drafts/"))
        return data;


    var overwrite = true;
    if (this.config.auto_category.enable && overwrite) {
        let postStr;
        // 1. parse front matter
        var tmpPost = front.parse(data.raw);
        // 2. read old categories
        //
        // 3. generate categories from directory
        // var categories = data.slug.split('/');
        var categories = data.source.split('/');
        // 3.1 handle depth
        var depth = this.config.auto_category.depth || categories.length-2;
        if (depth==0) { // Uncategorized
            //tmpPost.categories = ["Uncategorized"];
            return data;
        }
        var newCategories = categories.slice(1, 1+Math.min(depth, categories.length-2));
        // 3.2 prevents duplicate file changes
        if (Array.isArray(tmpPost.categories) && (tmpPost.categories.join("_") == newCategories.join("_"))) return data;
        tmpPost.categories = newCategories
github redbrick / static-site / lib / emailNewPosts.js View on Github external
.map((post, index) => ({
              // cut out front matter and surrounding whitespace
              contents: post.replace(/---[\w\W]*---/, '').trim(),

              frontMatter: parseFrontMatter(post),

              // get filename without parent directory and without '.md'
              slug: postFilenames[index].split('/').slice(-1)[0].slice(0, -3),
            }))
            .filter(({ frontMatter }) => {
github poacher2k / hexo-featured-image / index.js View on Github external
hexo.extend.filter.register('before_post_render', function(data) {
	var front = fm.parse(data.raw);
	var featured_image = front.featured_image;
	if (featured_image) {
		var thumbnail = front.thumbnail;
		var imagePrefix = imagesPath;
		// Use post asset folder
		if (post_asset_folder) {
			imagePrefix = data.permalink;
			if (useAbsolutePathReference) {
				imagePrefix = absolute_path_reference_url(imagePrefix);
			}
		}
		// Check if the featured image path is an absolute URI
		if (
			featured_image.indexOf('http') === 0 ||
			featured_image.indexOf('/') === 0
		) {
github rozbo / hexo-abbrlink / lib / logic.js View on Github external
abbrlink = org_get_abbrlink(data).abbrlink
        }
        if (!abbrlink) {
			var opt_alg = ((this.config.abbrlink && this.config.abbrlink.alg) ? this.config.abbrlink.alg : 'crc16');
			var opt_rep = ((this.config.abbrlink && this.config.abbrlink.rep) ? this.config.abbrlink.rep : 'dec')
			
			let res = (opt_alg == 'crc32' ? crc32.str(data.title) >>> 0 : crc16(data.title) >>> 0);
			//check this abbrlink is already exist then get a different one
			abbrlink = model.check(res);
			//set abbrlink to hex or dec
			abbrlink = opt_rep == 'hex' ? abbrlink.toString(16) : abbrlink;
            data.abbrlink = abbrlink;
            let postStr;
            if (!/.*\.org/.test(data.source)){
            //re parse front matter
            var tmpPost = front.parse(data.raw);
            //add new generated link
            tmpPost.abbrlink = abbrlink;
            //process post
                postStr = front.stringify(tmpPost);
            postStr = '---\n' + postStr;
            fs.writeFileSync(data.full_source, postStr, 'utf-8');
            }
            else
            {
                postStr = data.raw.split("\n")
                postStr.splice(2,0,'#+ABBRLINK: ' + abbrlink)
                fs.writeFileSync(data.full_source, postStr.join('\n'), 'utf-8');
            }
            if(data.title.length==0)
                log.i("No title found for post [%s]", data.slug);
            log.i("Generate link %s for post [%s]", abbrlink, data.title);
github thesadabc / hexo-myadmin / lib / service / post.js View on Github external
create({ meta, content }) {
        let compiled = hfm.parse(['---', meta, '---'].join('\n'));
        delete compiled._content;

        if (!compiled.title) return Promise.reject("title cant be null");

        compiled.updated = compiled.updated || new Date();
        compiled.content = content;
        compiled.author = this.hexo.config.author;
        compiled.layout = this.type.toLowerCase();

        if (this.type === "Post") {
            compiled.categories = compiled.categories || [this.hexo.config.default_category]
        }
        return this.hexo.post.create(compiled)
            .then((file) =>
                this.updateDB().then(() => this.getSource(file.path))
            );
github thesadabc / hexo-myadmin / lib / service / post.js View on Github external
update(id, { meta, content }) {
        let post = this.detail(id);

        let compiled = hfm.parse(['---', meta, '---', content].join('\n'));
        compiled.updated = compiled.updated || new Date();
        compiled.date = compiled.date || new Date(post.date.valueOf());
        compiled.author = compiled.author || post.author || this.hexo.config.author;
        if (this.type === "Post") {
            compiled.categories = compiled.categories || [this.hexo.config.default_category]
        }

        return fs.writeFile(post.full_source, hfm.stringify(compiled))
            .then(() => this.updateDB())
            .then(() => this.getSource(post.full_source));

    }

hexo-front-matter

Front-matter parser.

MIT
Latest version published 1 year ago

Package Health Score

62 / 100
Full package analysis