danmactough / node-feedparser

Robust RSS, Atom, and RDF feed parsing in Node.js
Other
1.97k stars 190 forks source link

Randomly started receiving `Cannot read property 'read' of undefined` #238

Closed astrotars closed 6 years ago

astrotars commented 6 years ago

I randomly started seeing Cannot read property 'read' of undefined when attempting to run my script.

req.on('response', res => {
    if (res.statusCode != 200) {
        return this.emit(
            'error',
            new Error('Bad status code'),
        );
    }

    let encoding =
            res.headers['content-encoding'] || 'identity',
        charset = getParams(
            res.headers['content-type'] || '',
        ).charset;

    res = decompress(res, encoding);
    res = translate(res, charset);

    res.pipe(feedparser);
});

feedparser.on('error', done);
feedparser.on('end', done);

feedparser.on('readable', () => {
    let post;

    let siteTitle;
    let siteLink;
    let siteDescription;

    let articleLink;
    let articleTitle;
    let articleSummary;
    let articleDescription;
    let articleDate;

    while ((post = this.read())) {
        siteTitle = post.meta.title;
        siteLink = post.meta.link;
        siteDescription = post.meta.description || '';

        articleLink = post.link;
        articleTitle = strip(
            entities.decodeHTML(post.title),
        );
        articleDescription = strip(
            entities.decodeHTML(post.description),
        );
        articleDate = post.pubdate || moment().toDate();
    }
});
danmactough commented 6 years ago

Did you recently switch to arrow functions for the event handlers? this in arrow functions gets defined differently. For event handlers, arrow functions generally won't work if the function relies on this. https://stackoverflow.com/a/34361380

astrotars commented 6 years ago

Bingo! Thanks for the heads up. I didn't even think of that.

danmactough commented 6 years ago

🎉 consider changing references to this to refer to the appropriate variable instead: req or feedparser