车栈

Hexo插件之Hexo-UUID

在我之前的博客搬迁纪录中,提到:

Hexo 每次 generate 后 post._id 会变化,导致和多说关联无效,评论无法显示

我的解决方法是给每篇文章手动增加了uuid属性,手动 不符合程序猿懒的个性,不如写个插件了。

有朋友也许会问为什么不用 permanent link 或者 创建时间戳 等作为关联媒介,我想这2个对于我来说都可能不是一直不变的,所以我更倾向于一个我不会去改变的属性,😄。

废话不多说,开始写代码,看完一遍 Hexo API 文档后,可以从 Hexo创建文章后的事件这里入手,Hexo创建文章后会触发new事件,同时携带文章的结构体作为参数:

{
    "path": "/the/path/your/post/will/stored/in",
    "content": "---\ntitle: some title\ndate: 2016-05-20 22:00\ntags:\n---\n"
}

解决方案就是修改此处post内容,并写入path指向的文件地址。

码代码开始,这里就只用ES2015语法写了:

index.js:

'use strict';

const HexoUuid = require('./lib/hexo-uuid');

hexo.on('new', HexoUuid);

lib/hexo-uuid.js:

'use strict';

const uuid = require('uuid');
const fs = require('fs');

module.exports = (post) => {

  let lines = post.content.split('\n');
  let index = lines.findIndex(item => item === 'uuid:');
  if (index > -1) {
    lines[index] += (' ' + uuid.v1());
  } else {
    lines.splice(1, 0, 'uuid: ' + uuid.v1());
  }

  post.content = lines.join('\n');
  if (post.path !== false) {
    fs.writeFile(post.path, post.content);
  }

};

最后,tests/index.js:

'use strict';

const should = require('chai').should();
const Hexo = require('hexo');
const HexoUuid = require('../lib/hexo-uuid');

const hexo = new Hexo(__dirname, {
  silent: true
});

hexo.on('new', HexoUuid);

describe('Post With User Pre-defined UUID Attribute', () => {

  let post = {
    path: false,
    content: `---
title: I love Hexo!
uuid:
date: "2016-05-20T16:20:00+08:00"
tags:
---
    `
  };

  hexo.emit('new', post);

  it('Post should have uuid', () => {
    let uuidPresence = /uuid: .{36}\n/.test(post.content);
    uuidPresence.should.equal(true);
  });

});

describe('Post Without User Pre-defined UUID Attribute', () => {

  let post = {
    path: './tmp/test.md',
    content: `---
title: I love Hexo!
date: "2016-05-20T16:20:00+08:00"
tags:
---
    `
  };

  hexo.emit('new', post);

  it('Post should have uuid', () => {
    let uuidPresence = /uuid: .{36}\n/.test(post.content);
    uuidPresence.should.equal(true);
  });

});

通过以上步骤,总体对Hexo的插件编写有了新的认知,毕竟我也是刚入门Hexo, 插件使用起来就更简单了:

npm install hexo-uuid --save

安装完成后,就和普通创建文章一样,hexo new whatever-your-fancy-title-is 就可以轻松拥有UUID属性了。

国际惯例 Github仓库在此

{% githubCard chekun hexo-uuid %}

Keep on hacking!