使用nodejs的markdown和marked模块解析markdown


#Node#


2014-10-19

markdown-jsmarked这两个模块都支持将mardown解析为html。

安装:

$ npm install markdown
$ npm install marked

markdown模块

测试1:

# !/usr/bin/env node

var text = "##hello\n"+
    "---\n" +
    "[baidu](http://www.baidu.com)\n" +
    "Hello *World*!";
var markdown = require( "markdown" ).markdown;
console.log( markdown.toHTML( text ) );

运行结果如下:

<h2>hello</h2>

<hr/>

<p><a href="http://www.baidu.com">baidu</a>
Hello <em>World</em>!</p>

测试2:

现在,当前目录下有文件test.md,内容如下:

# Hello
---

01 | 02 |  03
---|------|-----
11 |  12 | 13
23| 34|  43


	print 'hello'

使用下面的代码处理下test.md的内容:

# !/usr/bin/env node

fs = require('fs');
markdown = require( "markdown" ).markdown;

fs.readFile('test.md', function (err, data) {
  if (err) throw err;
  var markdownContent = data.toString();
  var htmlContent = markdown.toHTML( markdownContent );
  console.log( htmlContent );
});

输出如下:

<h2>Hello</h2>

<hr/>

<p>01 | 02 |  03
---|------|-----
11 |  12 | 13
23| 34|  43</p>


<pre><code>print &#39;hello&#39;</code></pre>

test.md使用了markdown扩展的表格定义,node的markdown模块并没有提供转换表格的功能。

marked模块

使用marked模块解析test.md

# !/usr/bin/env node

fs = require('fs');
markdown = require('marked');

fs.readFile('test.md', function (err, data) {
  if (err) throw err;
  var markdownContent = data.toString();
  var htmlContent = markdown( markdownContent );
  console.log( htmlContent );
});

解析结果:

<h2 id="hello">Hello</h2>
<hr>
<table>
<thead>
<tr>
<th>01</th>
<th>02</th>
<th>03</th>
</tr>
</thead>
<tbody>
<tr>
<td>11</td>
<td>12</td>
<td>13</td>
</tr>
<tr>
<td>23</td>
<td>34</td>
<td>43</td>
</tr>
</tbody>
</table>
<pre><code>print &#39;hello&#39;
</code></pre>

由此可见,marked模块提供的功能更多一些。


( 本文完 )