<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Soul Of Free Loop &#187; node.js</title>
	<atom:link href="https://zohead.com/archives/tag/node-js/feed" rel="self" type="application/rss+xml" />
	<link>https://zohead.com</link>
	<description>Uranus Zhou&#039;s Blog</description>
	<lastBuildDate>Sat, 19 Jul 2025 15:42:46 +0000</lastBuildDate>
	<language>zh-CN</language>
		<sy:updatePeriod>hourly</sy:updatePeriod>
		<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.8</generator>
	<item>
		<title>使用lunr.js为Wiki系统增加全文搜索支持</title>
		<link>https://zohead.com/archives/wiki-lunr-js/</link>
		<comments>https://zohead.com/archives/wiki-lunr-js/#comments</comments>
		<pubDate>Mon, 09 Jan 2017 16:50:39 +0000</pubDate>
		<dc:creator><![CDATA[Uranus Zhou]]></dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[学习感悟]]></category>
		<category><![CDATA[Elasticlunr.js]]></category>
		<category><![CDATA[lunr.js]]></category>
		<category><![CDATA[MDwiki]]></category>
		<category><![CDATA[node.js]]></category>
		<category><![CDATA[Wiki]]></category>
		<category><![CDATA[Wikitten]]></category>
		<category><![CDATA[全文]]></category>
		<category><![CDATA[索引]]></category>

		<guid isPermaLink="false">https://zohead.com/?p=1338</guid>
		<description><![CDATA[搜索 Wiki 知识库的问题 今年早些时候我捣鼓了一个基于 Wikitten 和 MDwiki 的 个人知识库系统，我一般使用基于 PHP Wikitten 的 动态 Wiki 知识库，本地预览或者测试时可以用基于 MDwiki 的 静态 Wiki 知识库，两个配合使用并通过 BitTorrent Sync 与 VPS 进行数据同步，这样需要更新时也是很方便的。 我在实际使用中还是发现 Wikitten 的搜索功能比较薄弱，只支持通过文档或目录名称进行搜索（Wikitten 显示时是直接遍历 Wiki 文档的，出于效率考虑也不好直接进行目录遍历全文搜索）；MDwiki 则由于是纯静态实现，根本 [&#8230;]]]></description>
				<content:encoded><![CDATA[<h2 id="搜索-wiki-知识库的问题">搜索 Wiki 知识库的问题</h2>
<p>今年早些时候我捣鼓了一个基于 Wikitten 和 MDwiki 的 <a href="https://zohead.com/archives/wikitten-mdwiki/">个人知识库系统</a>，我一般使用基于 PHP Wikitten 的 <a href="https://wiki.zohead.com/" target="_blank">动态 Wiki 知识库</a>，本地预览或者测试时可以用基于 MDwiki 的 <a href="https://mdwiki.zohead.com/" target="_blank">静态 Wiki 知识库</a>，两个配合使用并通过 BitTorrent Sync 与 VPS 进行数据同步，这样需要更新时也是很方便的。</p>
<p>我在实际使用中还是发现 Wikitten 的搜索功能比较薄弱，只支持通过文档或目录名称进行搜索（Wikitten 显示时是直接遍历 Wiki 文档的，出于效率考虑也不好直接进行目录遍历全文搜索）；MDwiki 则由于是纯静态实现，根本没有搜索功能，通过我写的生成 Wiki 目录索引的脚本也只能一层层目录定位到 Wiki 文档，要想快速的搜索知识库内容暂时只能通过在本地运行 grep 等命令的方式。</p>
<h2 id="关于-lunrjs">关于 lunr.js</h2>
<p>最近我在看到 <a href="http://lunrjs.com/">lunr.js</a> 这个轻量级 JavaScript 全文搜索引擎之后，搜索 Wiki 知识库的问题也迎来了曙光。目前有一些基于 Hexo 之类静态博客框架的站点就是使用 lunr.js 实现了站内搜索功能。因为我考虑将 lunr.js 加入到 Wikitten 和 MDwiki 系统中以支持直接在线全文搜索。</p>
<p>lunr.js 的官方版本目前仍然不支持中文的分词器，其目前支持的语言列表在 <a href="https://github.com/MihaiValentin/lunr-languages">这里</a>。开始我考虑过使用 <a href="http://blog.csdn.net/watkinsong">wei song</a> 博主写的基于 lunr.js 的改进版 <a href="http://elasticlunr.com/">Elasticlunr.js</a>，作者介绍的 Elasticlunr.js 相比 lunr.js 可以实现更快的搜索速度和更小的索引文件，只是 Elasticlunr.js 同样也不支持中文搜索，还是暂且作罢。</p>
<p>最终我使用的是国内网友 <a href="http://blog.codepiano.com/">codepaino</a> 分享的支持中文的修改版 lunr.js，项目地址为：</p>
<p><a href="https://github.com/codepiano/lunr.js">https://github.com/codepiano/lunr.js</a></p>
<p>在 VPS 上安装修改版的 lunr.js 也还是比较简单的，首先 VPS 上需要有 node.js 环境（这里只介绍 Linux 版本的），下载修改版的 lunr.js：</p>
<pre class="brush: bash; title: ; notranslate">
root@zoserver:~# wget https://github.com/codepiano/lunr.js/raw/master/lunr.min.js
</pre>
<p>然后 npm 安装依赖的 nodejieba 库：</p>
<pre class="brush: bash; title: ; notranslate">
root@zoserver:~# npm install -g nodejieba
|
&gt; nodejieba@2.2.4 install /usr/lib/node_modules/nodejieba
&gt; node-gyp rebuild

gyp WARN EACCES user &quot;root&quot; does not have permission to access the dev dir &quot;/root/.node-gyp/4.6.1&quot;
gyp WARN EACCES attempting to reinstall using temporary dev dir &quot;/usr/lib/node_modules/nodejieba/.node-gyp&quot;
make: Entering directory `/usr/lib/node_modules/nodejieba/build'
  CXX(target) Release/obj.target/nodejieba/lib/index.o
  CXX(target) Release/obj.target/nodejieba/lib/nodejieba.o
  SOLINK_MODULE(target) Release/obj.target/nodejieba.node
  COPY Release/nodejieba.node
make: Leaving directory `/usr/lib/node_modules/nodejieba/build'
nodejieba@2.2.4 /usr/lib/node_modules/nodejieba
└── nan@2.3.5
</pre>
<h2 id="生成-wiki-搜索索引文件">生成 Wiki 搜索索引文件</h2>
<p>在线的 Wiki 系统在实际使用搜索功能时需要在浏览器前端加载 lunr.js 的搜索索引文件，为了方便生成整个 Wiki 知识库目录的所有 Markdown 文档的索引，我写了一个生成 Wiki 搜索索引文件的 node.js 程序。</p>
<p><strong>search.js</strong> 程序的功能非常简单，遍历 Wikitten 和 MDwiki 共用的 Wiki 文档目录（默认为 <code>library</code>），获取遍历到的 Wiki 文档的标题、关键字标签和文档内容（这三者搜索权重依次降低），然后使用 lunr.js 最终生成 JSON 格式的索引文件：</p>
<pre class="brush: jscript; title: search.js; notranslate">
var fs = require('fs'), removeMd = require('remove-markdown'), lunr = require('./static/js/lunr.min.js');

var md_index = lunr(function () {
	this.field('title');
	this.field('tags');
	this.field('body');
	this.ref('url');
});

function walk_dir(wdir, path, callback) {
	var dirList = fs.readdirSync(wdir + path);
	dirList.forEach(function(item) {
		if(fs.statSync(wdir + path + '/' + item).isDirectory())
			walk_dir(wdir, path + '/' + item, callback);
		else
			callback(wdir, path + '/' + item);
	});
}

function process_markdown(wdir, path) {
	var pos = path.lastIndexOf(&quot;.&quot;);
	if (pos &lt; 0) return;
	if (path.substr(pos) != &quot;.md&quot; &amp;&amp; path.substr(pos) != &quot;.markdown&quot;) return;
	var fpos = path.lastIndexOf(&quot;/&quot;);
	var title = (fpos &gt;= 0 ? path.substring(fpos + 1, pos) : path.substr(0, pos));

	// ignore navigation menu document
	if (path == &quot;/navigation.md&quot;) return;

	var has_front = false;
	var md_doc = {
		&quot;url&quot;: path,
		&quot;title&quot;: title,
		&quot;tags&quot;: &quot;&quot;
	};

	var data = fs.readFileSync(wdir + path, &quot;utf-8&quot;);
	// ignore auto generated index.md
	if (title == &quot;index&quot; &amp;&amp; data.indexOf(&quot;Auto-index of&quot;) &gt;= 0) return;

	// process front matter
	if (data.substr(0, 3) == &quot;```&quot;) {
		pos = data.substr(3).indexOf(&quot;```&quot;);
		if (pos &gt;= 0) {
			var front = JSON.parse(&quot;{&quot; + data.substr(3, pos) + &quot;}&quot;);
			has_front = true;
			if (&quot;title&quot; in front) md_doc.title = front.title;
			if (&quot;tags&quot; in front) md_doc.tags = front.tags.join(' ');
			md_doc.body = removeMd(data.substr(pos + 6));
		}
	}
	if (!has_front) md_doc.body = removeMd(data);
	md_index.add(md_doc);
}

if (process.argv.length &lt; 4) {
	console.log(&quot;Usage:\n&quot;);
	console.log(process.argv[0] + &quot; &quot; + process.argv[1] + &quot; Wiki-document-directory Search-index-file&quot;);
	console.log(process.argv[0] + &quot; &quot; + process.argv[1] + &quot; Search-index-file Keyword&quot;);
	process.exit(1);
} else if (!fs.existsSync(process.argv[2])) {
	console.log(&quot;Invalid Wiki-document-directory or Search-index-file: &quot; + process.argv[2]);
	process.exit(1);
}

if (fs.statSync(process.argv[2]).isDirectory()) {
	walk_dir(process.argv[2], &quot;&quot;, process_markdown);
	fs.writeFileSync(process.argv[3], JSON.stringify(md_index.toJSON()));
} else {
	md_index = lunr.Index.load(JSON.parse(fs.readFileSync(process.argv[2])));
	console.log(JSON.stringify(md_index.search(process.argv[3])));
}
</pre>
<blockquote>
<p><strong>提示</strong></p>
<p>为了方便 Wikitten 和 MDwiki 能同时使用 lunr.js，我把 <strong>search.js</strong> 程序引用的修改版 <code>lunr.min.js</code> 文件放到了 Wiki 程序主目录下的 <code>static/js</code> 文件夹，如需要的话可以自行修改。</p>
</blockquote>
<p>上面的程序在遍历 Markdown 文档时忽略了我之前写的自动生成子目录索引文档脚本 <code>generate-index.sh</code> 产生的 <code>index.md</code> 文档，另外也忽略了 MDwiki 专用的 <code>navigation.md</code> Wiki 系统菜单文档。</p>
<p><strong>search.js</strong> 程序使用了 <code>remove-markdown</code> 这个去掉 Markdown 格式的 npm 包，同样用 npm 安装即可：</p>
<pre class="brush: bash; title: ; notranslate">
root@zoserver:~# npm install -g remove-markdown
</pre>
<p>一般情况下直接在 Wiki 程序目录下运行 <strong>search.js</strong> 程序生成索引文件即可：</p>
<pre class="brush: bash; title: ; notranslate">
root@zoserver:/home/wiki# node search.js library search_index.json
</pre>
<p>最后上面的命令生成出来的 <code>search_index.json</code> 就是 lunr.js 格式的索引文件，我们可以直接放到 Wiki 程序主目录下。</p>
<p>经过实际测试目前我的 Wiki 目录一共包含 44 篇有效的 Markdown 文档，文件夹占用不到 500 KB，不过生成出来的 <code>search_index.json</code> 索引文件就已经接近 1.5 MB 了，浏览器访问索引文件时通过 gzip 压缩传输之后差不多 160 KB，还在我能接受的范围内。</p>
<p>另外你也可以使用 <strong>search.js</strong> 程序通过索引文件直接在本地进行关键字搜索：</p>
<pre class="brush: bash; title: ; notranslate">
root@zoserver:/home/wiki# node search.js search_index.json shell
[{&quot;ref&quot;:&quot;/技术/Android/Android Shell控制手机.md&quot;,&quot;score&quot;:0.21389728235059557},{&quot;ref&quot;:&quot;/技术/Linux/Shell/Shell进行TCP和UDP网络编程.md&quot;,&quot;score&quot;:0.2134705596450158},{&quot;ref&quot;:&quot;/技术/Linux/Shell/sed命令相关技巧.md&quot;,&quot;score&quot;:0.13650355812409723},{&quot;ref&quot;:&quot;/技术/Linux/Shell/vim操作技巧.md&quot;,&quot;score&quot;:0.1060635524797807},{&quot;ref&quot;:&quot;/技术/Windows/rundll32运行命令列表.md&quot;,&quot;score&quot;:0.035704080604386734},{&quot;ref&quot;:&quot;/技术/Windows/Windows注册表记录.md&quot;,&quot;score&quot;:0.0019103777768910307}]
</pre>
<h2 id="将-lunrjs-整合到-wiki-系统">将 lunr.js 整合到 Wiki 系统</h2>
<p>有了正确的搜索索引文件之后，我们就可以修改 Wikitten 和 MDwiki 程序将 lunr.js 搜索功能整合进来了。</p>
<p>下面 Wikitten 和 MDwiki 支持全文搜索的修改我已经提交到 <a href="https://github.com/zohead/wikitten-and-mdwiki">wikitten-and-mdwiki</a> 项目，提交记录可以参考 <a href="https://github.com/zohead/wikitten-and-mdwiki/commit/ea6d35aa038e6da064892c9091f767f323b7864b">这里</a>。</p>
<h3 id="wikitten-修改">Wikitten 修改</h3>
<p>由于 Wikitten 自带了按文档和目录名搜索的功能，我们只要给 Wikitten 增加 AJAX 加载 lunr.js 搜索索引文件并按关键字搜索的功能，最后使用 lunr.js 的搜索结果替换原来的即可。</p>
<p>Wikitten 默认只允许直接访问 <code>static</code> 子目录中的文件，我们需要修改对应的 Web 目录转发规则，这里只贴出 Nginx 服务器的配置（Apache 用户请自行修改 <code>.htaccess</code> 文件）：</p>
<pre class="brush: plain; title: ; notranslate">
server
{
	gzip on;
	gzip_min_length 1000;
	gzip_buffers 4 8k;
	gzip_types text/plain application/x-javascript text/css application/json application/xml text/javascript;

	location ~* ^/(robots.txt|search_index.json|static/(css|js|img|fonts)/.+.(jpg|jpeg|gif|css|png|js|ico|html|xml|txt|swf|pdf|txt|bmp|eot|svg|ttf|woff|woff2))$ {
		access_log off;
		expires max;
	}
}
</pre>
<p>location 规则指定对 Wiki 主目录下的 <code>robots.txt</code> 和 <code>search_index.json</code> 索引文件以及 <code>static</code> 子目录中的文件不经过 Wikitten 处理；另外为了提高索引文件的加载速度上面的配置中还开启了 gzip 压缩，MDwiki 也可以做同样的修改。</p>
<h3 id="mdwiki-修改">MDwiki 修改</h3>
<p>MDwiki 原本没有搜索功能，为了方便页面上使用，我在其专用的 <code>navigation.md</code> Wiki 系统菜单文档里增加了一个搜索菜单，这样所有 Wiki 文档页面就都能使用了：</p>
<hr size="1" />
<p>[&#x1f50d;]()<br />&nbsp;* # Search file name or content.<br />&nbsp;* [&lt;input id="search_input" type="text"/&gt;](#)</p>
<hr size="1" />
<p>搜索菜单显示效果如下：</p>
<p><img src="http://res.cloudinary.com/digwht2y0/image/upload/v1737442839/mdwiki-search-menu.png" alt="MDwiki 搜索菜单" title="MDwiki 搜索菜单"></p>
<p>然后在 MDwiki 对应的 <code>index.html</code> 中增加搜索处理代码：</p>
<pre class="brush: jscript; title: index.html; notranslate">
&lt;script type=&quot;text/javascript&quot; src=&quot;static/js/lunr.min.js&quot;&gt;&lt;/script&gt;
&lt;script type=&quot;text/javascript&quot;&gt;
var search_indexes = null;

function doSearch(query) {
	if (search_indexes == null) return;
	var s_res = search_indexes.search(query);
	var t_html = '&lt;ul&gt;';
	for (var i = 0; i &lt; s_res.length; i++) {
		var t_pos = s_res[i].ref.lastIndexOf('/');
		t_html += '&lt;li&gt;&lt;a href=&quot;#!' + s_res[i].ref + '&quot;&gt;' + (t_pos &gt;= 0 ? s_res[i].ref.substr(t_pos + 1) : s_res[i].ref) + '&lt;/a&gt;&lt;/li&gt;';
	}
	t_html += '&lt;/ul&gt;';
	$('#search-result-body').html(t_html);
	$('#search-result-label').html('Search result for: ' + query);
	$('#search-result').modal('show');
}

function search_content(query) {
	if (search_indexes == null) {
		$.getJSON(&quot;search_index.json&quot;, function(data){
			if (data != null) search_indexes = lunr.Index.load(data);
			doSearch(query);
		});
	} else
		doSearch(query);
}

$(document).bind('DOMNodeInserted', function(e) {
	if ($('#search_input').length &lt;= 0) return;
	$(document).unbind('DOMNodeInserted');

	$('#search_input').bind('click', function(event) {
		event.stopPropagation();
		return false;
	});
	$('#search_input').bind('keypress', function(event){
		if (event.keyCode == '13')
			search_content($(this).val());
	});
});
&lt;/script&gt;

&lt;div class=&quot;modal fade&quot; id=&quot;search-result&quot; tabindex=&quot;-1&quot; role=&quot;dialog&quot; aria-labelledby=&quot;search-result-label&quot; aria-hidden=&quot;true&quot;&gt;
&lt;div class=&quot;modal-dialog&quot;&gt;
&lt;div class=&quot;modal-content&quot;&gt;
&lt;div class=&quot;modal-header&quot;&gt;
&lt;button type=&quot;button&quot; class=&quot;close&quot; data-dismiss=&quot;modal&quot; aria-hidden=&quot;true&quot;&gt;&amp;#x274c;&lt;/button&gt;
&lt;h4 class=&quot;modal-title&quot; id=&quot;search-result-label&quot;&gt;&lt;/h4&gt;
&lt;/div&gt;
&lt;div class=&quot;modal-body&quot; id=&quot;search-result-body&quot;&gt;&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
</pre>
<p>上面对搜索输入框的点击事件增加了处理，防止点击时 Bootstrap 的搜索菜单项丢失，在输入框中输入关键字回车才加载索引文件并使用 lunr.js 进行搜索。</p>
<p>MDwiki 的搜索效果如下图所示：</p>
<p><img src="http://res.cloudinary.com/digwht2y0/image/upload/v1737442840/mdwiki-search-result.png" alt="MDwiki 搜索结果" title="MDwiki 搜索结果"></p>
<p>点击搜索结果中的文档名称就会跳转显示对应 Wiki 文档内容。</p>
<h2 id="总结">总结</h2>
<p>经过对 Wikitten 和 MDwiki 进行修改，目前 Wiki 知识库的显示和查询效果基本都能满足我的需求了。虽然还存在搜索索引文件体积稍大的隐患，后续也可以考虑使用 Elasticlunr.js 或者其它方式进行改进咯。</p>
]]></content:encoded>
			<wfw:commentRss>https://zohead.com/archives/wiki-lunr-js/feed/</wfw:commentRss>
		<slash:comments>12</slash:comments>
		</item>
	</channel>
</rss>
