Skip to content
陈广亮的技术博客
Go back

Node 中使用 Markdown 与 highlight.js

基础:使用 marked

var md = require("marked");
blogs.forEach(function (v, i) {
  v.content = md(v.content);
});

引入 highlight.js

参照 marked 官方示例引入 highlight.js:

marked.setOptions({
  highlight: function (code) {
    return require("highlight.js").highlightAuto(code).value;
  },
});

添加行号(参考 hexo 源码)

highlight: function (code) {
  var compiled = require('highlight.js').highlightAuto(code).value;
  var lines = compiled.split('\n'),
    numbers = '', content = '';

  lines.forEach(function(item, i){
    numbers += '<div class="line">' + (i + 1) + '</div>';
    content += '<div class="line">' + item + '</div>';
  });

  return '<figure class="highlight"><table><tr>' +
    '<td class="gutter"><pre>' + numbers + '</pre></td>' +
    '<td class="code"><pre>' + content + '</pre></td>' +
    '</tr></table></figure>';
}

Share this post on:

Previous Post
JS 解析 XML 兼容 IE 与其他浏览器
Next Post
文本复制换行问题