javascript 奇怪的node.js错误:TypeError:Object #< Object>没有方法'on'

rkkpypqq  于 2023-05-27  发布在  Java
关注(0)|答案(3)|浏览(150)

我尝试在node.js中运行一个简单的屏幕抓取应用程序。代码发布在这里:https://github.com/anismiles/jsdom-based-screen-scraperhttp://anismiles.wordpress.com/2010/11/29/node-js-and-jquery-to-scrape-websites/
服务器启动正常,但是当我在上面运行查询时,我得到以下错误。有人知道为什么吗?

TypeError: Object #<Object> has no method 'on'
    at Object.<anonymous> (/Users/avishai/Downloads/anismiles-jsdom-based-screen-scraper-f0c79d3/searcher-server.js:9:10)
    at param (/Users/avishai/.node_libraries/.npm/connect/0.5.10/package/lib/connect/middleware/router.js:146:21)
    at param (/Users/avishai/.node_libraries/.npm/connect/0.5.10/package/lib/connect/middleware/router.js:157:15)
    at pass (/Users/avishai/.node_libraries/.npm/connect/0.5.10/package/lib/connect/middleware/router.js:162:10)
    at Object.router [as handle] (/Users/avishai/.node_libraries/.npm/connect/0.5.10/package/lib/connect/middleware/router.js:168:6)
    at next (/Users/avishai/.node_libraries/.npm/connect/0.5.10/package/lib/connect/index.js:218:15)
    at Server.handle (/Users/avishai/.node_libraries/.npm/connect/0.5.10/package/lib/connect/index.js:231:3)
    at Server.emit (events.js:45:17)
    at HTTPParser.onIncoming (http.js:1078:12)
    at HTTPParser.onHeadersComplete (http.js:87:31)

抛出错误的函数是:

function books(app){
    app.get('/:query', function(req, res, next) {

        res.writeHead(200, { 'Content-Type': 'text/html' });

        var rediff = require('./searcher-rediff');
        rediff.on('on_book', function(item){
            res.write(item + "<br/>");
        });
        rediff.on('completed', function(){
            res.end();
        });
        rediff.search(escape(req.params.query));

    });
}

更新

现在我注意到,在第一个请求中,我得到了这个:

SyntaxError: Unexpected strict mode reserved word
    at Module._compile (module.js:369:25)
    at Object..js (module.js:380:10)
    at Module.load (module.js:306:31)
    at Function._load (module.js:272:10)
    at require (module.js:318:19)
    at Object.<anonymous> (/Users/avishai/Downloads/anismiles-jsdom-based-screen-scraper-f0c79d3/searcher.js:2:15)
    at Module._compile (module.js:374:26)
    at Object..js (module.js:380:10)
    at Module.load (module.js:306:31)
    at Function._load (module.js:272:10)
bq9c1y66

bq9c1y661#

想到的唯一解释是所需的模块不是EventEmmiter示例。因此,它没有“on”方法。

8oomwypt

8oomwypt2#

这个bug背后的根本原因应该与EventEmittter有关。请允许我解释一下

  1. searcher.js继承自EventEmitter(第26行)Searcher.prototype = new process.EventEmitter;
  2. searcher-rediff.jssearcher-flipkart.jssearcher-landmarkonthenet.jssearcher.js扩展而来,因此它们也继承自EventEmitter
    1.'on'方法实际上是在EventEmitter中定义的。
    因此,我认为,由于某种原因,searcher.js无法从EventEmitter继承,因此缺少方法'on'。
xuo3flqw

xuo3flqw3#

您正在尝试在模块而不是EventEmitter上设置侦听器。
require('./searcher-rediff');返回Javascript模块。我想在searcher-rediff模块中实际上有一个对象,它就是您要查找的EventEmitter。
查看searcher-rediff.js代码,查看EventEmitter定义和导出的位置,然后需要引用它。
最后你可能会得到这样的东西...

var rediff = require('./searcher-rediff').searcher;

相关问题