这段代码应该读取microsoft的文档文件,并将单词数输出到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“中,但是它没有这样做。请帮帮忙
发布于 2019-04-19 09:24:59
您混淆了js前端脚本和Mammoth的Nodejs后端用法。
如果使用Nodejs运行以下脚本,则无法直接更新div元素,因为document在此上下文中没有意义。
致命ReferenceError:文档未定义
在这种情况下,您可以使用来自前端页面的ajax调用来更新div的值。
另一方面,如果您想直接从浏览器中使用猛犸象,文档建议使用专用版本mammoth.browser.js。
注意,在处理之前,您必须设置一个文件读取器来加载docx文件。您可以查看浏览器演示以获得实现的示例。
发布于 2019-11-17 20:32:49
为了将文本值传回给客户端,您需要在您的http响应中将其呈现为局部变量。为了简单起见,我假设您使用的是服务器端框架(如express ),并且不使用模板引擎来呈现页面。
那么服务器端的代码应该如下所示:
mammoth.extractRawText({path: docxFile})
.then(function(result){
var text = result.value; // The raw text
var textLength = text.length;
// use textLength as a local variable and pass it to the client
res.render("the_page_you_want_to_render", { textLength: textLength }, function(err, html){
if (err) return new Error(err);
res.send(html);
}
})
.done();现在,您可以在前端代码中使用占位符,以便显示服务器正在传递的局部变量:
<div id="whatever" class="youwant">
#textLength#
</div>由于我假设您没有使用任何特定的模板引擎,请将此代码添加到您的服务器入口点,以便它可以使用您的局部变量呈现html页面:
app.engine('html', function (filePath, options, callback) {
fs.readFile(filePath, function (err, content) {
if (err) return callback(err);
var rendered = content.toString()
// this is where the magic happens
.replace('#textLength#', '<p>' + options.textLength + '</p>');
return callback(null, rendered)
});
});https://stackoverflow.com/questions/55757520
复制相似问题