【发布时间】:2021-07-04 22:37:48
【问题描述】:
我想将变量 $ 声明为对象内的 cheerio.load 函数,这样我就可以从我的任何函数中访问cheerio 函数。
但是,每当我这样做时,我都会收到错误 this.$ is not a function
我正在使用的代码
var spl = {
main: function() {
fs.readFile("index.html", "utf8", function(err, data){
if(err) throw err;
this.$ = cheerio.load(data) // Using context.$ resulted in the same problem
});
this.hasTitleTag() // this gives the error this.$ is not a function
},
hasTitleTag: function() {
return this.$('title').length > 0 ? true : false;
}
};
我猜不是在我的对象中创建一个变量 $,而是仅用于 main 函数,我在网上阅读过使用 context 关键字,但这似乎没有任何作用要么,我无法找到另一个解决方案
【问题讨论】:
-
您是如何将cheerio 导入您的应用程序的?
-
另外,仅供参考,readFile 是异步的。它在完成读取文件后调用您的回调。所以
this.$ = cheerio.load(data)在你的其余代码之后执行。 -
constcheerio = require('cheerio');
-
readFileSync 不是异步版本吗?
-
readFileSync 是同步版本。
标签: javascript node.js cheerio