【问题标题】:Cheerio (node.js) returns an error on html readCheerio (node.js) 在读取 html 时返回错误
【发布时间】:2014-05-11 00:46:07
【问题描述】:

我对 JS 完全陌生,完全被 Node Cheerio 困住了。如果有人可以帮助我,我将不胜感激。

我正在处理的代码在这里:https://github.com/zafartahirov/bitstarter

(找到修复后不起作用的代码将被称为grader.old.js)。

当我跑步时

node ./grader.js --file index.html --checks checks.json | less

我收到一个错误:

TypeError: Cannot call method 'utf8Slice' of null
    at Buffer.toString (buffer.js:416:26)
    at exports.isTag (/home/ubuntu/GitHub/bitstarter/node_modules/cheerio/lib/utils.js:15:14)
    at Function.filter (/home/ubuntu/GitHub/bitstarter/node_modules/cheerio/node_modules/lodash/dist/lodash.js:3150:15)
    at /home/ubuntu/GitHub/bitstarter/node_modules/cheerio/lib/api/traversing.js:9:26
    at Function.reduce (/home/ubuntu/GitHub/bitstarter/node_modules/cheerio/node_modules/lodash/dist/lodash.js:3734:25)
    at exports.find (/home/ubuntu/GitHub/bitstarter/node_modules/cheerio/lib/api/traversing.js:8:17)
    at new module.exports (/home/ubuntu/GitHub/bitstarter/node_modules/cheerio/lib/cheerio.js:92:18)
    at initialize (/home/ubuntu/GitHub/bitstarter/node_modules/cheerio/lib/static.js:23:12)
    at checkHtmlFile (/home/ubuntu/GitHub/bitstarter/grader.js:59:23)
    at Object.<anonymous> (/home/ubuntu/GitHub/bitstarter/grader.js:76:21)
(END)

有什么建议吗?

【问题讨论】:

  • 我想我找到了解决方案,但我仍然不明白:var cheerioHtmlFile = function(htmlfile) { var buffer = fs.readFileSync(htmlfile); return cheerio.load(buffer.toString()); // return cheerio.load(fs.readFileSync(htmlfile)); }; 我仍然不明白为什么我必须将缓冲区转换为字符串。
  • 在这种情况下,我强烈推荐阅读joelonsoftware.com/articles/Unicode.html
  • 谢谢!我一定会的!
  • 如果使用编码选项调用 readFileSync,则不需要在缓冲区上使用 toString,例如 fs.readFileSync(htmlfile, 'utf-8')

标签: javascript node.js npm cheerio


【解决方案1】:

我们正在学习相同的课程,我花了相当长的时间来调试它。 cheerio.load() 方法似乎需要一个字符串作为参数而不是缓冲区。

【讨论】:

  • 我是如何解决的。我想我很困惑,因为 cmets 中没有“虚拟”代码,谢谢!
  • 之前它接受了一个 Buffer 对象,但是这个被改变了。我已经打开了一个问题,如果需要,我会提交一个 PR:github.com/cheeriojs/cheerio/issues/485
猜你喜欢
  • 1970-01-01
  • 2020-08-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多