一个快速和宽容的HTML / XML / RSS解析器。解析器可以处理流并提供回调接口。

全局安装后,连接 htmlparser2 模块到当前项目中:npm install -g htmlparser2 && npm link htmlparser2   

const htmlparser2 = require("htmlparser2"), fs = require('fs');
let fileName = 'E:\\index.html';
let fileContent = fs.readFileSync(fileName);

const parser = new htmlparser2.Parser({
constructor() {
this.name, this.attributes;
},
onopentag(name, attributes) {
this.name = name, this.attributes = attributes;
},
ontext(text) {
if (this.name === "title") {
console.log(text);//直接 title 标签
}
}
,
onclosetag(tagname) {
// if (tagname === "script") {
// console.log("That's it?!");
// }
}
}
, {decodeEntities: true}
)
;
parser.write(fileContent);
parser.end();