You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让GB2312编码文件在localhost通过Docsify正常显示?

解决Docsify部署GB2312编码HTML文件乱码问题

Docsify默认会以UTF-8编码读取文件,而你的HTML是GB2312编码,部署后就容易出现乱码,给你几个可行的解决办法:

1. 批量转文件编码到UTF-8

这是最彻底的办法,把所有GB2312的HTML转成UTF-8,之后就不会有编码问题:

  • 用VS Code批量处理:打开存放HTML的文件夹,按Ctrl+Shift+F搜索所有.html文件,全选后右键点「更改文件编码」,选择UTF-8并保存;
  • 命令行工具(Linux/macOS):用iconv批量转换,执行这条命令:
    find . -name "*.html" -exec iconv -f GB2312 -t UTF-8 {} -o {} \;
    
  • Windows可以用Notepad++:打开所有HTML文件,依次点「编码」→「转为UTF-8编码」,或者用批量处理插件完成。

注意:转换前一定要备份文件,防止意外损坏。

2. 让Docsify用GB2312编码读取文件

如果不想转编码,可以修改Docsify的加载逻辑,强制用GB2312解码文件:
首先在你的index.html里引入处理编码的polyfill(因为浏览器原生fetch不支持GB2312):

<script src="https://cdn.jsdelivr.net/npm/text-encoding@0.7.0/lib/encoding.min.js"></script>

然后修改Docsify的配置,自定义内容加载函数:

window.$docsify = {
  loadContent: function(url, next) {
    fetch(url)
      .then(res => res.arrayBuffer())
      .then(buffer => {
        const decoder = new TextDecoder('gb2312');
        const content = decoder.decode(buffer);
        next(null, content);
      })
      .catch(err => next(err));
  }
};

这样Docsify加载HTML时就会用GB2312编码解析内容。

3. 配置服务器响应头指定GB2312编码

如果用docsify serve自带的服务器,默认不会加编码头,你可以自己搭个简单的Node.js服务器,在响应头里指定编码:
创建一个server.js文件,内容如下:

const http = require('http');
const fs = require('fs');
const path = require('path');

const server = http.createServer((req, res) => {
  let filePath = '.' + req.url;
  if (filePath === './') filePath = './index.html';

  const extname = path.extname(filePath);
  let contentType = 'text/html';
  if (extname === '.html') {
    contentType = 'text/html; charset=GB2312';
  }

  fs.readFile(filePath, (error, content) => {
    if (error) {
      res.writeHead(404);
      res.end('文件未找到');
    } else {
      res.writeHead(200, { 'Content-Type': contentType });
      res.end(content, 'binary');
    }
  });
});

server.listen(3000, () => {
  console.log('服务器运行在 http://localhost:3000/');
});

然后执行node server.js启动服务器,浏览器访问时就会按照GB2312编码解析文件,不会乱码。

内容的提问来源于stack exchange,提问作者SNORLAX

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 07:57:17