0

私はproducts.jsファイルに次のようなメソッドを持っています:

var handler = function(errors, window) {...}

jsdom env コールバック内で実行したいと考えています:

jsdom.env({
    html : "http://dev.mysite.com:3000/products.html",
    scripts : [ "http://code.jquery.com/jquery.js", "page-scrapers/products.js" ],
    done : function(errors, window) {
        handler(errors, window)
        }  
});

実行すると、「ハンドラが定義されていません」と表示されます。私は近づいていますか?

4

2 に答える 2

0

変数を別のファイルからアクセスできるようにする場合は、エクスポートする必要があります。http://nodejs.org/api/modules.html

//products.js
exports.handler = function(window, error) {...}

// another.file.js
var products = require('products.js');
jsdom.env({
    html : "http://dev.mysite.com:3000/products.html",
    scripts : [ "http://code.jquery.com/jquery.js", "page-scrapers/products.js" ],
    // This can be simplified as follows 
    done : products.handler
});

これは悪い考えのように思えますが、なぜハンドラーをグローバルにするのでしょうか? コードを再構築する必要があると思います

于 2012-11-05T21:04:22.160 に答える
0

問題のコンテキストは、既存の Web サイトからデータをスクレイピングすることです。各ページに JavaScript スクレイパーを関連付け、node.js サーバー経由で提供される URL 経由でスクレイピングされたデータにアクセスします。

Juan が提案したように、重要なのは node.js モジュールを使用することです。ハンドラー メソッドの大部分は、product.js からエクスポートされます。

exports.handler = function(errors, window, resp) {...

次に、node.js ベースのサーバー インスタンスにインポートします。

//note: subdir paths must start with './' :
var products = require('./page-scrapers/products.js'); 

これにより、「products.handler」という名前でメソッドへの参照が作成され、リクエスト ハンドラーで呼び出すことができます。

var router = new director.http.Router({
'/floop' : {
    get : funkyFunc
}
})

var funkyFunc = function() {
var resp = this.res

jsdom.env({
    html : "http://dev.mySite.com:3000/products.html",
    scripts : [ "http://code.jquery.com/jquery.js"],
    done : function(errors, window) {products.handler(errors, window, resp)}
});
}

そして、それは機能します。

于 2012-11-05T22:20:12.513 に答える