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

Node.js读取Word文档统计字数并显示到HTML div失败求助

问题分析与解决方案

我来帮你解决这个问题!你的代码能在控制台输出字数但无法更新DOM,核心是两个关键问题导致的:

  1. 环境不兼容:require("mammoth")是Node.js的模块加载语法,浏览器环境不支持直接使用,必须改用浏览器兼容的方式引入mammoth。
  2. 本地文件访问限制:浏览器出于安全策略,不允许直接通过path: "file.docx"读取本地文件,需要通过用户主动上传的方式获取文件内容。

修复后的完整代码

HTML 部分

<div id="demo">请选择一个Word文档:</div>
<!-- 添加文件上传控件,限制仅能选择docx文件 -->
<input type="file" id="fileInput" accept=".docx">
<!-- 引入浏览器版的mammoth库(通过CDN) -->
<script src="https://unpkg.com/mammoth@1.6.0/mammoth.browser.min.js"></script>
<script src="script.js"></script>

JavaScript 部分(script.js)

// 提前获取DOM元素,避免重复查询
const demoDiv = document.getElementById('demo');
const fileInput = document.getElementById('fileInput');

// 优化字数统计函数:处理连续空格、空文本等边界情况
function wordCount(str) {
  // 先去除首尾空格,再按任意空白字符分割,最后过滤空字符串
  return str.trim().split(/\s+/).filter(word => word.length > 0).length;
}

// 监听文件选择事件
fileInput.addEventListener('change', function(e) {
  const selectedFile = e.target.files[0];
  if (!selectedFile) return;

  // 使用FileReader读取本地文件(浏览器允许的安全方式)
  const reader = new FileReader();
  reader.onload = function(event) {
    // 将文件转为ArrayBuffer格式传给mammoth
    mammoth.extractRawText({arrayBuffer: event.target.result})
      .then(function(result) {
        const documentText = result.value;
        const count = wordCount(documentText);
        console.log("Word Count: " + count);
        // 成功更新DOM内容
        demoDiv.innerHTML = `文档字数统计:${count}`;
      })
      .catch(function(error) {
        // 捕获并展示错误信息
        demoDiv.innerHTML = `读取文件失败:${error.message}`;
        console.error("读取错误:", error);
      });
  };
  // 以ArrayBuffer格式读取文件
  reader.readAsArrayBuffer(selectedFile);
});

关键修复点说明

  • 替换模块加载方式:用CDN引入浏览器专用的mammoth脚本,避免Node.js的require语法,让代码能在浏览器中正常运行。
  • 改用文件上传流程:通过<input type="file">让用户主动选择本地文件,利用FileReader读取文件内容为ArrayBuffer,这是浏览器允许的本地文件访问方式。
  • 优化字数统计逻辑:原函数会把连续空格误统计为多个空“单词”,优化后的逻辑能得到更准确的真实单词数。
  • 增加错误处理:捕获mammoth读取文件时的异常,给用户展示友好的错误提示,同时便于调试。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 05:06:50