【发布时间】:2022-08-18 16:59:31
【问题描述】:
抱歉这个可能是微不足道的问题,但我仍然无法了解流在 node.js 中的工作方式。
我想解析一个 html 文件并获取我遇到的第一个脚本的路径。我想在第一次匹配后中断解析,但仍然调用 onopentag() 侦听器,直到 html 文件有效结束。为什么 ?
const { WritableStream } = require(\"htmlparser2/lib/WritableStream\");
const scriptPath = await new Promise(function(resolve, reject) {
try {
const parser = new WritableStream({
onopentag: (name, attrib) => {
if (name === \"script\" && attrib.src) {
console.log(`script : ${attrib.src}`);
resolve(attrib.src); // return the first script, effectively called for each script tag
// none of below calls seem to work
indexStream.unpipe(parser);
parser.emit(\"close\");
parser.end();
parser.destroy();
}
},
onend() {
resolve();
}
});
const indexStream = got.stream(\"/index.html\", {
responseType: \'text\',
resolveBodyOnly: true
});
indexStream.pipe(parser); // and parse it
} catch (e) {
reject(e);
}
});
是否可以在 indexStream 有效结束之前关闭解析器流,如果可以,如何? 如果不是为什么?
请注意,代码有效,并且我的承诺使用第一个匹配有效地解决了。
标签: javascript node.js node-streams