| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122 |
- #!/usr/bin/env node
- /**
- * KaTeX 服务端渲染脚本
- * 用法: echo "HTML内容" | node katex-render.js
- * 或: node katex-render.js < input.html > output.html
- *
- * 将 HTML 中的 LaTeX 公式渲染为 KaTeX HTML
- */
- // 尝试多个路径加载 KaTeX
- let katex;
- const possiblePaths = [
- 'katex', // 本地 node_modules
- '/usr/lib/node_modules/katex', // Alpine 全局安装
- '/usr/local/lib/node_modules/katex', // 其他全局安装路径
- ];
- for (const path of possiblePaths) {
- try {
- katex = require(path);
- break;
- } catch (e) {
- // 继续尝试下一个路径
- }
- }
- if (!katex) {
- console.error('Error: KaTeX module not found. Please run: npm install -g katex');
- process.exit(1);
- }
- // 读取标准输入
- let input = '';
- process.stdin.setEncoding('utf8');
- process.stdin.on('readable', () => {
- let chunk;
- while ((chunk = process.stdin.read()) !== null) {
- input += chunk;
- }
- });
- process.stdin.on('end', () => {
- try {
- const output = renderMathInHtml(input);
- process.stdout.write(output);
- } catch (error) {
- console.error('KaTeX render error:', error.message);
- process.exit(1);
- }
- });
- /**
- * 渲染 HTML 中的所有数学公式
- */
- function renderMathInHtml(html) {
- // 定界符配置(按优先级排序)
- const delimiters = [
- { left: '$$', right: '$$', display: true },
- { left: '\\[', right: '\\]', display: true },
- { left: '\\(', right: '\\)', display: false },
- { left: '$', right: '$', display: false },
- ];
- let result = html;
- // 按顺序处理每种定界符
- for (const delimiter of delimiters) {
- result = processDelimiter(result, delimiter.left, delimiter.right, delimiter.display);
- }
- return result;
- }
- /**
- * 处理特定定界符的公式
- */
- function processDelimiter(html, left, right, displayMode) {
- // 转义正则特殊字符
- const escapeRegex = (str) => str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
- const leftEscaped = escapeRegex(left);
- const rightEscaped = escapeRegex(right);
- // 构建正则表达式
- // 对于 $ ... $,需要确保不匹配 $$ ... $$
- let pattern;
- if (left === '$' && right === '$') {
- // 单个 $ 不能紧跟另一个 $
- pattern = new RegExp(`(?<!\\$)\\$(?!\\$)([^$]+?)(?<!\\$)\\$(?!\\$)`, 'g');
- } else {
- pattern = new RegExp(`${leftEscaped}([\\s\\S]*?)${rightEscaped}`, 'g');
- }
- return html.replace(pattern, (match, latex) => {
- try {
- // 清理 LaTeX 内容
- let cleanLatex = latex.trim();
- // 跳过空内容
- if (!cleanLatex) {
- return match;
- }
- // 渲染 KaTeX
- const rendered = katex.renderToString(cleanLatex, {
- displayMode: displayMode,
- throwOnError: false,
- strict: false,
- trust: true,
- output: 'html', // 使用 HTML 输出(比 mathml 兼容性更好)
- });
- return rendered;
- } catch (error) {
- // 渲染失败时保留原始内容
- console.error(`KaTeX error for "${latex.substring(0, 50)}...":`, error.message);
- return match;
- }
- });
- }
|