javascript - 元素 id 中的 Node.js 文档字数输出
问题描述
我在这段代码上遇到了困难,该代码应该读取 microsoft word 的文档文件并将单词数输出到 div 元素中。
我尝试了所有方法,代码将字数输出到控制台但不在 div 中。请在这里帮助我。太感谢了
这是我的html页面
<div id="demo"></div>
<script src="script.js"></script>
这是我的 script.js
// Installed mammoth using npm
var mammoth = require("mammoth");
// I have a doc file with some sample content
var docxFile = "file.docx";
// Below is my function to count the number of words on that document
function WordCount(str) {
return str.split(" ").length;
}
// Below is my Mammoth module extracts the text from my docx file and the function above counts the word for me and displays on the console. I want to be able to display it on my HTML page.
mammoth.extractRawText({path: docxFile})
.then(function(result){
var text = result.value; // The raw text
console.log("Word Count: " + WordCount(text));
// Below is what I want to do. but its not working.
document.getElementById('demo').innerHTML = (WordCount(text));
})
.done();
上面的代码应该将 file.docx 中的单词数显示到 div 元素 ID“demo”中,但它没有这样做。请帮忙
解决方案
您正在混淆 js 前端脚本和Mammoth包的 Nodejs 后端使用。
如果您使用 Nodejs 运行以下脚本,则无法直接更新您的 div 元素,因为document
在这种情况下没有意义。
致命参考错误:文档未定义
在这种情况下,您可以使用前端页面中的 ajax 调用来更新 div 的值。
另一方面,如果您想直接从浏览器使用Mammoth,文档建议使用专用版本mammoth.browser.js
请注意,您必须在处理之前设置一个文件阅读器来加载您的 docx 文件。您可以查看浏览器演示以获取实现示例。