2011-03-03 25 views
5

我試圖在node.js中運行一個簡單的屏幕抓取應用程序。該代碼是張貼在這裏: https://github.com/anismiles/jsdom-based-screen-scraper http://anismiles.wordpress.com/2010/11/29/node-js-and-jquery-to-scrape-websites/奇怪的node.js錯誤:TypeError:對象#<Object>沒有方法'on'

服務器精細啓動,但後來當我在其上運行一個查詢時,我得到以下錯誤。有誰知道這是爲什麼?

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)); 

    }); 
} 

UPDATE

現在我注意到,第一個請求,我得到這個:

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) 

回答

1

這個bug背後根本原因應該是與EventEmittter。讓我來解釋一下,

  1. searcher.js從EventEmitter (線26)Searcher.prototype =新process.EventEmitter繼承;

  2. searcher-rediff.js,searcher-flipkart.js和searcher-landmarkonthenet.js從searcher.js擴展而來,所以它們也從EventEmitter繼承。

  3. 'on'方法實際上是在EventEmitter中定義的。

所以,我認爲,出於某種原因,searcher.js無法從EventEmitter繼承,因此「開」的方法缺失。

+0

我明白了......那麼我怎樣才能讓searcher.js能夠繼承EventEmitter? – Avishai 2011-03-05 17:41:00

2

想到的唯一解釋是需要模塊不是EventEmmiter實例。因此,它沒有'開'的方法。

0

您正嘗試在模塊上設置偵聽器而不是EventEmitter。

require('./searcher-rediff');返回一個Javascript模塊。我想searcher-rediff模塊中實際上有一個對象是您正在查找的EventEmitter。

通過searcher-rediff.js代碼查看EventEmitter的定義和導出位置,然後您需要引用該代碼。

在你可能會喜歡的東西最終會結束...

var rediff = require('./searcher-rediff').searcher; 
相關問題