我正在尝试用于NodeJS修改外部HTML文件(位于同一目录中)。在我的index.js文件中,我写道:
fs.readFile('index.html', (err,html)=>{
if(err){
throw err;
}
html.body.innerHTML += '<div id = "asdf"></div>';
});
Run Code Online (Sandbox Code Playgroud)
因为 index.html 是一个有效的文档。但它看起来并没有正确读取它,因为我收到了一个错误:
“类型错误:无法读取未定义的属性‘innerHTML’”。
我想 html 没有得到任何东西作为正文。
如何在HTML使用中进行更改JavaScript?
这是一个使用node-html-parse的例子
HTML文件
<html>
<body>
<div id="fist">yolo</div>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
和 nodejs
const fs = require('fs');
const parse = require('node-html-parser').parse;
fs.readFile('index.html', 'utf8', (err,html)=>{
if(err){
throw err;
}
const root = parse(html);
const body = root.querySelector('body');
//body.set_content('<div id = "asdf"></div>');
body.appendChild('<div id = "asdf"></div>');
console.log(root.toString()); // This you can write back to file!
});
Run Code Online (Sandbox Code Playgroud)
考虑到下载量,可能有比 node-html-parser 更好的解决方案。例如,htmlparser2有更多的下载,但它看起来也更复杂:)