[cheerio] TypeError: Cannot read property ‘parent’ of undefined

A beautiful autumn day and my little app threw the error 🙂

var oldParent = node.parent || node.root,

TypeError: Cannot read property 'parent' of undefined
at Function.exports.update (/home/kang/apps/nodecrawler/node_modules/cheerio/lib/parse.js:55:25)
at module.exports (/home/kang/apps/nodecrawler/node_modules/cheerio/lib/parse.js:17:11)
at Function.exports.load (/home/kang/apps/nodecrawler/node_modules/cheerio/lib/static.js:19:14)
at Request._callback (/home/kang/apps/nodecrawler/app.js:46:29)
at self.callback (/home/kang/apps/nodecrawler/node_modules/request/request.js:198:22)
at emitOne (events.js:77:13)
at Request.emit (events.js:169:7)
at Request.onRequestError (/home/kang/apps/nodecrawler/node_modules/request/request.js:867:8)
at emitOne (events.js:77:13)
at ClientRequest.emit (events.js:169:7)
at Socket.socketErrorListener (_http_client.js:259:9)
at emitOne (events.js:77:13)
at Socket.emit (events.js:169:7)
at connectErrorNT (net.js:993:8)
at doNTCallback2 (node.js:429:9)

The reason behind the error is that cheerio.load() is called with an empty value like null or an empty string. You should check whether the value contains something before you call load()

    var $ = cheerio.load(body);
    // body is null or empty

Leave a Comment

Your email address will not be published. Required fields are marked *